No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

466 líneas
18KB

  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 422: Api_StatusLine = "422 Unprocessable Entity"
  75. Case 428: Api_StatusLine = "428 Precondition Required"
  76. Case 500: Api_StatusLine = "500 Internal Server Error"
  77. Case 503: Api_StatusLine = "503 Service Unavailable"
  78. Case Else: Api_StatusLine = status & " Status"
  79. End Select
  80. End Function
  81. Sub Api_Send(status, jsonText)
  82. Response.Clear
  83. Response.Status = Api_StatusLine(status)
  84. Response.ContentType = "application/json"
  85. Response.Charset = "utf-8"
  86. Response.AddHeader "X-Request-Id", Api_RequestId()
  87. Response.AddHeader "Cache-Control", "no-store"
  88. Response.Write jsonText
  89. End Sub
  90. Sub Api_Error(status, code, message)
  91. Api_Send status, "{""error"":{""code"":" & JsonLite_Quote(code) & ",""message"":" & JsonLite_Quote(message) & _
  92. ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
  93. End Sub
  94. Sub Api_NotFound()
  95. Api_Error 404, "not_found", "Resource not found."
  96. End Sub
  97. Dim Api_LastDbError
  98. Api_LastDbError = ""
  99. ' Call straight after a failing statement (before any rollback) so the description is kept for Api_DbFailed.
  100. Sub Api_NoteDbError()
  101. Api_LastDbError = "" & Err.Description
  102. End Sub
  103. ' A failed database call becomes a JSON 500. The database text is only included when Environment = Development.
  104. Sub Api_DbFailed(errNumber, errDescription)
  105. Dim msg
  106. Err.Clear
  107. On Error GoTo 0
  108. msg = "Internal error (" & errNumber & "). The request was not completed."
  109. If LCase(GetAppSetting("Environment")) = "development" And Len(Api_LastDbError) > 0 Then
  110. msg = msg & " [dev] " & Api_LastDbError
  111. End If
  112. Api_Error 500, "internal_error", msg
  113. End Sub
  114. '-----------------------------------------------------------------------------------------------------------------------
  115. ' Request helpers
  116. '-----------------------------------------------------------------------------------------------------------------------
  117. Function Api_Header(name)
  118. Api_Header = Trim("" & Request.ServerVariables("HTTP_" & UCase(Replace(name, "-", "_"))))
  119. End Function
  120. ' Request body as UTF-8 text, or Empty after sending a 400.
  121. Function Api_ReadBody()
  122. Dim n, text
  123. Api_ReadBody = Empty
  124. n = Request.TotalBytes
  125. If n = 0 Then
  126. Api_Error 400, "empty_body", "Request body is empty. Send a JSON object."
  127. Exit Function
  128. End If
  129. If n > 1048576 Then
  130. Api_Error 400, "body_too_large", "Request body exceeds 1 MiB."
  131. Exit Function
  132. End If
  133. Api_Utf8Unsupported = False
  134. text = Api_Utf8Decode(CStr(Request.BinaryRead(n)))
  135. If JsonLite_Parse(text) Is Nothing Then
  136. Api_Error 400, "invalid_json", "Body must be a valid JSON object."
  137. Exit Function
  138. End If
  139. ' Reject rather than store damaged text (see Api_Utf8Decode)
  140. If Api_Utf8Unsupported Or JsonLite_SurrogateSeen Then
  141. Api_Error 422, "unsupported_character", "Characters above U+FFFF (for example emoji) are not supported yet. Remove or replace them."
  142. Exit Function
  143. End If
  144. Api_ReadBody = text
  145. End Function
  146. Dim Api_Utf8Unsupported
  147. Api_Utf8Unsupported = False
  148. ' Decodes a string holding raw UTF-8 bytes (one byte per character, as AxonASP BinaryRead returns) into Unicode text.
  149. Function Api_Utf8Decode(ByVal s)
  150. Dim i, n, c, cp, extra, out, k, ok, b
  151. n = Len(s)
  152. out = ""
  153. i = 1
  154. Do While i <= n
  155. c = AscW(Mid(s, i, 1)) And 255
  156. If c < 128 Then
  157. out = out & Chr(c)
  158. i = i + 1
  159. Else
  160. extra = -1
  161. cp = 0
  162. If c >= 240 And c <= 247 Then
  163. extra = 3
  164. cp = c And 7
  165. ElseIf c >= 224 And c <= 239 Then
  166. extra = 2
  167. cp = c And 15
  168. ElseIf c >= 194 And c <= 223 Then
  169. extra = 1
  170. cp = c And 31
  171. End If
  172. ok = (extra > 0 And i + extra <= n)
  173. If ok Then
  174. For k = 1 To extra
  175. b = AscW(Mid(s, i + k, 1)) And 255
  176. If b < 128 Or b > 191 Then
  177. ok = False
  178. Else
  179. cp = cp * 64 + (b And 63)
  180. End If
  181. Next
  182. End If
  183. If ok And cp <= 1114111 Then
  184. ' On the pinned AxonASP build ChrW(cp > 65535) raises "Invalid procedure call" and a surrogate pair
  185. ' is written out as CESU-8, so code points above U+FFFF (and encoded surrogates) cannot be held.
  186. ' They become U+FFFD and set Api_Utf8Unsupported; Api_ReadBody then answers 422.
  187. If cp > 65535 Or (cp >= 55296 And cp <= 57343) Then
  188. Api_Utf8Unsupported = True
  189. out = out & ChrW(65533)
  190. Else
  191. out = out & ChrW(cp)
  192. End If
  193. i = i + extra + 1
  194. Else
  195. out = out & ChrW(65533)
  196. i = i + 1
  197. End If
  198. End If
  199. Loop
  200. Api_Utf8Decode = out
  201. End Function
  202. Function Api_ToInt(v, dflt, lo, hi)
  203. Dim s
  204. s = Trim("" & v)
  205. Api_ToInt = dflt
  206. If Len(s) > 0 Then
  207. If IsNumeric(s) Then
  208. Api_ToInt = CLng(s)
  209. End If
  210. End If
  211. If Api_ToInt < lo Then Api_ToInt = lo
  212. If Api_ToInt > hi Then Api_ToInt = hi
  213. End Function
  214. '-----------------------------------------------------------------------------------------------------------------------
  215. ' Authentication. Returns True and sets Api_TenantId / Api_PrincipalId; otherwise sends 401 and returns False.
  216. '-----------------------------------------------------------------------------------------------------------------------
  217. Function Api_Authenticate()
  218. Dim h, key, rs, expires, keyId
  219. Api_Authenticate = False
  220. Api_TenantId = ""
  221. Api_PrincipalId = ""
  222. h = Api_Header("Authorization")
  223. If LCase(Left(h, 7)) <> "bearer " Then
  224. Response.AddHeader "WWW-Authenticate", "Bearer"
  225. Api_Error 401, "unauthenticated", "Missing or malformed Authorization header. Use: Authorization: Bearer <api key>."
  226. Exit Function
  227. End If
  228. key = Trim(Mid(h, 8))
  229. If Len(key) < 16 Or Len(key) > 200 Then
  230. Response.AddHeader "WWW-Authenticate", "Bearer"
  231. Api_Error 401, "unauthenticated", "Invalid API key."
  232. Exit Function
  233. End If
  234. Set rs = DAL().Query("SELECT k.id, p.id, p.tenant_id, k.expires_at FROM api_keys k " & _
  235. "JOIN principals p ON p.id = k.principal_id JOIN tenants t ON t.id = p.tenant_id " & _
  236. "WHERE k.key_hash = ? AND k.status = 'active' AND p.status = 'active' AND t.status = 'active'", Api_Sha256(key))
  237. If rs.EOF Then
  238. rs.Close
  239. Response.AddHeader "WWW-Authenticate", "Bearer"
  240. Api_Error 401, "unauthenticated", "Invalid API key."
  241. Exit Function
  242. End If
  243. keyId = "" & rs(0)
  244. Api_PrincipalId = "" & rs(1)
  245. Api_TenantId = "" & rs(2)
  246. expires = rs(3)
  247. rs.Close
  248. If Not IsNull(expires) Then
  249. If Len("" & expires) > 0 Then
  250. If "" & expires <= Api_Now() Then
  251. Api_TenantId = ""
  252. Api_PrincipalId = ""
  253. Response.AddHeader "WWW-Authenticate", "Bearer"
  254. Api_Error 401, "unauthenticated", "API key has expired."
  255. Exit Function
  256. End If
  257. End If
  258. End If
  259. DAL().Execute "UPDATE api_keys SET last_used_at = ? WHERE id = ?", Array(Api_Now(), keyId)
  260. Api_Authenticate = True
  261. End Function
  262. '-----------------------------------------------------------------------------------------------------------------------
  263. ' Authorization
  264. '-----------------------------------------------------------------------------------------------------------------------
  265. ' Path of a namespace in the caller's tenant, or Null when it does not exist there.
  266. Function Api_NamespacePath(namespaceId)
  267. Dim rs
  268. Api_NamespacePath = Null
  269. If Not Api_IsId(namespaceId) Then Exit Function
  270. Set rs = DAL().Query("SELECT path FROM namespaces WHERE id = ? AND tenant_id = ?", Array(namespaceId, Api_TenantId))
  271. If Not rs.EOF Then
  272. Api_NamespacePath = "" & rs(0)
  273. End If
  274. rs.Close
  275. End Function
  276. ' True when the principal holds `perm` (or admin) on the path itself, or on an ancestor via an inheriting grant.
  277. Function Api_PathAllows(targetPath, perm)
  278. Dim rs, gPath, perms, inherit, allowed, expires, now_
  279. Api_PathAllows = False
  280. now_ = Api_Now()
  281. Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _
  282. "JOIN namespaces n ON n.id = g.namespace_id " & _
  283. "WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId))
  284. Do While Not rs.EOF
  285. gPath = "" & rs(0)
  286. perms = "," & LCase(Replace("" & rs(1), " ", "")) & ","
  287. inherit = rs(2)
  288. expires = rs(3)
  289. allowed = True
  290. If Not IsNull(expires) Then
  291. If Len("" & expires) > 0 Then
  292. If "" & expires <= now_ Then allowed = False
  293. End If
  294. End If
  295. If allowed Then
  296. If targetPath = gPath Then
  297. allowed = True
  298. ElseIf CLng(inherit) = 1 And Left(targetPath, Len(gPath) + 1) = gPath & "/" Then
  299. allowed = True
  300. ElseIf gPath = "/" And CLng(inherit) = 1 Then
  301. allowed = True
  302. Else
  303. allowed = False
  304. End If
  305. End If
  306. If allowed Then
  307. If InStr(perms, "," & LCase(perm) & ",") > 0 Or InStr(perms, ",admin,") > 0 Then
  308. Api_PathAllows = True
  309. Exit Do
  310. End If
  311. End If
  312. rs.MoveNext
  313. Loop
  314. rs.Close
  315. End Function
  316. ' True when the namespace exists in the caller's tenant AND the caller holds `perm` on it.
  317. Function Api_CanAccessNamespace(namespaceId, perm)
  318. Dim p
  319. Api_CanAccessNamespace = False
  320. p = Api_NamespacePath(namespaceId)
  321. If IsNull(p) Then Exit Function
  322. Api_CanAccessNamespace = Api_PathAllows(p, perm)
  323. End Function
  324. '-----------------------------------------------------------------------------------------------------------------------
  325. ' Audit trail (security-relevant actions; never log secrets or content)
  326. '-----------------------------------------------------------------------------------------------------------------------
  327. Sub Api_Audit(action, resourceType, resourceId, outcome)
  328. On Error Resume Next
  329. DAL().Execute "INSERT INTO audit_events (id, tenant_id, principal_id, action, resource_type, resource_id, outcome, request_id, created_at) " & _
  330. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", _
  331. Array(Api_NewId(), Api_TenantId, Api_PrincipalId, action, resourceType, resourceId, outcome, Api_RequestId(), Api_Now())
  332. Err.Clear
  333. On Error GoTo 0
  334. End Sub
  335. ' 422 with a list of messages. details: array of strings.
  336. Sub Api_Invalid(details)
  337. Dim i, list
  338. list = ""
  339. For i = 0 To UBound(details)
  340. If i > 0 Then list = list & ","
  341. list = list & JsonLite_Quote(details(i))
  342. Next
  343. Api_Send 422, "{""error"":{""code"":""validation_failed"",""message"":""Validation failed."",""details"":[" & list & "],""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
  344. End Sub
  345. ' SQL list of the caller's namespace ids on which `perm` is held, e.g. 'id1','id2' (ids are UUIDs, safe to inline).
  346. ' Empty string when there are none. One grants query plus one namespaces query.
  347. Function Api_AllowedNamespaceIds(perm)
  348. Dim rs, gPaths(), gPerms(), gInh(), n, i, now_, expires, okGrant, p, out, id, path, hit
  349. Api_AllowedNamespaceIds = ""
  350. now_ = Api_Now()
  351. n = 0
  352. ReDim gPaths(7)
  353. ReDim gPerms(7)
  354. ReDim gInh(7)
  355. Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _
  356. "JOIN namespaces n ON n.id = g.namespace_id WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId))
  357. Do While Not rs.EOF
  358. okGrant = True
  359. expires = rs(3)
  360. If Not IsNull(expires) Then
  361. If Len("" & expires) > 0 Then
  362. If "" & expires <= now_ Then okGrant = False
  363. End If
  364. End If
  365. p = "," & LCase(Replace("" & rs(1), " ", "")) & ","
  366. If okGrant And (InStr(p, "," & LCase(perm) & ",") > 0 Or InStr(p, ",admin,") > 0) Then
  367. If n > UBound(gPaths) Then
  368. ReDim Preserve gPaths(n * 2)
  369. ReDim Preserve gPerms(n * 2)
  370. ReDim Preserve gInh(n * 2)
  371. End If
  372. gPaths(n) = "" & rs(0)
  373. gInh(n) = CLng(rs(2))
  374. n = n + 1
  375. End If
  376. rs.MoveNext
  377. Loop
  378. rs.Close
  379. If n = 0 Then Exit Function
  380. out = ""
  381. Set rs = DAL().Query("SELECT id, path FROM namespaces WHERE tenant_id = ?", Api_TenantId)
  382. Do While Not rs.EOF
  383. id = "" & rs(0)
  384. path = "" & rs(1)
  385. hit = False
  386. For i = 0 To n - 1
  387. If path = gPaths(i) Then
  388. hit = True
  389. ElseIf gInh(i) = 1 Then
  390. If gPaths(i) = "/" Then
  391. hit = True
  392. ElseIf Left(path, Len(gPaths(i)) + 1) = gPaths(i) & "/" Then
  393. hit = True
  394. End If
  395. End If
  396. If hit Then Exit For
  397. Next
  398. If hit And Api_IsId(id) Then
  399. If Len(out) > 0 Then out = out & ","
  400. out = out & "'" & id & "'"
  401. End If
  402. rs.MoveNext
  403. Loop
  404. rs.Close
  405. Api_AllowedNamespaceIds = out
  406. End Function
  407. ' Replays the stored response for an Idempotency-Key. Returns True when the request may proceed (key unseen);
  408. ' False after sending the replayed response (same body) or a 409 (key reused with a different body).
  409. Function Api_IdempotencyGate(idemKey, requestHash)
  410. Dim rs
  411. Api_IdempotencyGate = True
  412. If Len(idemKey) = 0 Then Exit Function
  413. Set rs = DAL().Query("SELECT request_hash, status_code, response_body FROM idempotency_keys WHERE tenant_id = ? AND idem_key = ?", Array(Api_TenantId, idemKey))
  414. If Not rs.EOF Then
  415. Api_IdempotencyGate = False
  416. If "" & rs(0) = requestHash Then
  417. Dim st, bodyText
  418. st = CLng(rs(1))
  419. bodyText = "" & rs(2)
  420. rs.Close
  421. Api_Send st, bodyText
  422. Response.AddHeader "Idempotent-Replayed", "true"
  423. Else
  424. rs.Close
  425. Api_Error 409, "idempotency_conflict", "This Idempotency-Key was already used with a different request body."
  426. End If
  427. Exit Function
  428. End If
  429. rs.Close
  430. End Function
  431. Sub Api_IdempotencyStore(idemKey, requestHash, status, bodyText)
  432. If Len(idemKey) = 0 Then Exit Sub
  433. DAL().Execute "INSERT INTO idempotency_keys (tenant_id, idem_key, request_hash, status_code, response_body, created_at) VALUES (?, ?, ?, ?, ?, ?)", _
  434. Array(Api_TenantId, idemKey, requestHash, status, bodyText, Api_Now())
  435. End Sub
  436. %>

Powered by TurnKey Linux.