You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

525 line
21KB

  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. DAL().Execute "UPDATE api_keys SET last_used_at = ? WHERE id = ?", Array(Api_Now(), keyId)
  317. Api_Authenticate = True
  318. End Function
  319. '-----------------------------------------------------------------------------------------------------------------------
  320. ' Authorization
  321. '-----------------------------------------------------------------------------------------------------------------------
  322. ' Path of a namespace in the caller's tenant, or Null when it does not exist there.
  323. Function Api_NamespacePath(namespaceId)
  324. Dim rs
  325. Api_NamespacePath = Null
  326. If Not Api_IsId(namespaceId) Then Exit Function
  327. Set rs = DAL().Query("SELECT path FROM namespaces WHERE id = ? AND tenant_id = ?", Array(namespaceId, Api_TenantId))
  328. If Not rs.EOF Then
  329. Api_NamespacePath = "" & rs(0)
  330. End If
  331. rs.Close
  332. End Function
  333. ' True when the principal holds `perm` (or admin) on the path itself, or on an ancestor via an inheriting grant.
  334. Function Api_PathAllows(targetPath, perm)
  335. Dim rs, gPath, perms, inherit, allowed, expires, now_
  336. Api_PathAllows = False
  337. now_ = Api_Now()
  338. Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _
  339. "JOIN namespaces n ON n.id = g.namespace_id " & _
  340. "WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId))
  341. Do While Not rs.EOF
  342. gPath = "" & rs(0)
  343. perms = "," & LCase(Replace("" & rs(1), " ", "")) & ","
  344. inherit = rs(2)
  345. expires = rs(3)
  346. allowed = True
  347. If Not IsNull(expires) Then
  348. If Len("" & expires) > 0 Then
  349. If "" & expires <= now_ Then allowed = False
  350. End If
  351. End If
  352. If allowed Then
  353. If targetPath = gPath Then
  354. allowed = True
  355. ElseIf CLng(inherit) = 1 And Left(targetPath, Len(gPath) + 1) = gPath & "/" Then
  356. allowed = True
  357. ElseIf gPath = "/" And CLng(inherit) = 1 Then
  358. allowed = True
  359. Else
  360. allowed = False
  361. End If
  362. End If
  363. If allowed Then
  364. If InStr(perms, "," & LCase(perm) & ",") > 0 Or InStr(perms, ",admin,") > 0 Then
  365. Api_PathAllows = True
  366. Exit Do
  367. End If
  368. End If
  369. rs.MoveNext
  370. Loop
  371. rs.Close
  372. End Function
  373. ' True when the namespace exists in the caller's tenant AND the caller holds `perm` on it.
  374. Function Api_CanAccessNamespace(namespaceId, perm)
  375. Dim p
  376. Api_CanAccessNamespace = False
  377. p = Api_NamespacePath(namespaceId)
  378. If IsNull(p) Then Exit Function
  379. Api_CanAccessNamespace = Api_PathAllows(p, perm)
  380. End Function
  381. '-----------------------------------------------------------------------------------------------------------------------
  382. ' Audit trail (security-relevant actions; never log secrets or content)
  383. '-----------------------------------------------------------------------------------------------------------------------
  384. Sub Api_Audit(action, resourceType, resourceId, outcome)
  385. On Error Resume Next
  386. DAL().Execute "INSERT INTO audit_events (id, tenant_id, principal_id, action, resource_type, resource_id, outcome, request_id, created_at) " & _
  387. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", _
  388. Array(Api_NewId(), Api_TenantId, Api_PrincipalId, action, resourceType, resourceId, outcome, Api_RequestId(), Api_Now())
  389. Err.Clear
  390. On Error GoTo 0
  391. End Sub
  392. ' 422 with a list of messages. details: array of strings.
  393. Sub Api_Invalid(details)
  394. Dim i, list
  395. list = ""
  396. For i = 0 To UBound(details)
  397. If i > 0 Then list = list & ","
  398. list = list & JsonLite_Quote(details(i))
  399. Next
  400. Api_Send 422, "{""error"":{""code"":""validation_failed"",""message"":""Validation failed."",""details"":[" & list & "],""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
  401. End Sub
  402. ' SQL list of the caller's namespace ids on which `perm` is held, e.g. 'id1','id2' (ids are UUIDs, safe to inline).
  403. ' Empty string when there are none. One grants query plus one namespaces query.
  404. Function Api_AllowedNamespaceIds(perm)
  405. Dim rs, gPaths(), gPerms(), gInh(), n, i, now_, expires, okGrant, p, out, id, path, hit
  406. Api_AllowedNamespaceIds = ""
  407. now_ = Api_Now()
  408. n = 0
  409. ReDim gPaths(7)
  410. ReDim gPerms(7)
  411. ReDim gInh(7)
  412. Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _
  413. "JOIN namespaces n ON n.id = g.namespace_id WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId))
  414. Do While Not rs.EOF
  415. okGrant = True
  416. expires = rs(3)
  417. If Not IsNull(expires) Then
  418. If Len("" & expires) > 0 Then
  419. If "" & expires <= now_ Then okGrant = False
  420. End If
  421. End If
  422. p = "," & LCase(Replace("" & rs(1), " ", "")) & ","
  423. If okGrant And (InStr(p, "," & LCase(perm) & ",") > 0 Or InStr(p, ",admin,") > 0) Then
  424. If n > UBound(gPaths) Then
  425. ReDim Preserve gPaths(n * 2)
  426. ReDim Preserve gPerms(n * 2)
  427. ReDim Preserve gInh(n * 2)
  428. End If
  429. gPaths(n) = "" & rs(0)
  430. gInh(n) = CLng(rs(2))
  431. n = n + 1
  432. End If
  433. rs.MoveNext
  434. Loop
  435. rs.Close
  436. If n = 0 Then Exit Function
  437. out = ""
  438. Set rs = DAL().Query("SELECT id, path FROM namespaces WHERE tenant_id = ?", Api_TenantId)
  439. Do While Not rs.EOF
  440. id = "" & rs(0)
  441. path = "" & rs(1)
  442. hit = False
  443. For i = 0 To n - 1
  444. If path = gPaths(i) Then
  445. hit = True
  446. ElseIf gInh(i) = 1 Then
  447. If gPaths(i) = "/" Then
  448. hit = True
  449. ElseIf Left(path, Len(gPaths(i)) + 1) = gPaths(i) & "/" Then
  450. hit = True
  451. End If
  452. End If
  453. If hit Then Exit For
  454. Next
  455. If hit And Api_IsId(id) Then
  456. If Len(out) > 0 Then out = out & ","
  457. out = out & "'" & id & "'"
  458. End If
  459. rs.MoveNext
  460. Loop
  461. rs.Close
  462. Api_AllowedNamespaceIds = out
  463. End Function
  464. ' Replays the stored response for an Idempotency-Key. Returns True when the request may proceed (key unseen);
  465. ' False after sending the replayed response (same body) or a 409 (key reused with a different body).
  466. Function Api_IdempotencyGate(idemKey, requestHash)
  467. Dim rs
  468. Api_IdempotencyGate = True
  469. If Len(idemKey) = 0 Then Exit Function
  470. Set rs = DAL().Query("SELECT request_hash, status_code, response_body FROM idempotency_keys WHERE tenant_id = ? AND idem_key = ?", Array(Api_TenantId, idemKey))
  471. If Not rs.EOF Then
  472. Api_IdempotencyGate = False
  473. If "" & rs(0) = requestHash Then
  474. Dim st, bodyText
  475. st = CLng(rs(1))
  476. bodyText = "" & rs(2)
  477. rs.Close
  478. Api_Send st, bodyText
  479. Response.AddHeader "Idempotent-Replayed", "true"
  480. Else
  481. rs.Close
  482. Api_Error 409, "idempotency_conflict", "This Idempotency-Key was already used with a different request body."
  483. End If
  484. Exit Function
  485. End If
  486. rs.Close
  487. End Function
  488. Sub Api_IdempotencyStore(idemKey, requestHash, status, bodyText)
  489. If Len(idemKey) = 0 Then Exit Sub
  490. DAL().Execute "INSERT INTO idempotency_keys (tenant_id, idem_key, request_hash, status_code, response_body, created_at) VALUES (?, ?, ?, ?, ?, ?)", _
  491. Array(Api_TenantId, idemKey, requestHash, status, bodyText, Api_Now())
  492. End Sub
  493. %>

Powered by TurnKey Linux.