Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

451 linhas
17KB

  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. text = Api_Utf8Decode(CStr(Request.BinaryRead(n)))
  134. If JsonLite_Parse(text) Is Nothing Then
  135. Api_Error 400, "invalid_json", "Body must be a valid JSON object."
  136. Exit Function
  137. End If
  138. Api_ReadBody = text
  139. End Function
  140. ' Decodes a string holding raw UTF-8 bytes (one byte per character, as AxonASP BinaryRead returns) into Unicode text.
  141. Function Api_Utf8Decode(ByVal s)
  142. Dim i, n, c, cp, extra, out, k, ok, b
  143. n = Len(s)
  144. out = ""
  145. i = 1
  146. Do While i <= n
  147. c = AscW(Mid(s, i, 1)) And 255
  148. If c < 128 Then
  149. out = out & Chr(c)
  150. i = i + 1
  151. Else
  152. extra = -1
  153. cp = 0
  154. If c >= 240 And c <= 247 Then
  155. extra = 3
  156. cp = c And 7
  157. ElseIf c >= 224 And c <= 239 Then
  158. extra = 2
  159. cp = c And 15
  160. ElseIf c >= 194 And c <= 223 Then
  161. extra = 1
  162. cp = c And 31
  163. End If
  164. ok = (extra > 0 And i + extra <= n)
  165. If ok Then
  166. For k = 1 To extra
  167. b = AscW(Mid(s, i + k, 1)) And 255
  168. If b < 128 Or b > 191 Then
  169. ok = False
  170. Else
  171. cp = cp * 64 + (b And 63)
  172. End If
  173. Next
  174. End If
  175. If ok And cp <= 1114111 Then
  176. ' AxonASP strings hold whole code points: ChrW(cp) works above U+FFFF, while a UTF-16
  177. ' surrogate pair would be stored as two U+FFFD characters.
  178. out = out & ChrW(cp)
  179. i = i + extra + 1
  180. Else
  181. out = out & ChrW(65533)
  182. i = i + 1
  183. End If
  184. End If
  185. Loop
  186. Api_Utf8Decode = out
  187. End Function
  188. Function Api_ToInt(v, dflt, lo, hi)
  189. Dim s
  190. s = Trim("" & v)
  191. Api_ToInt = dflt
  192. If Len(s) > 0 Then
  193. If IsNumeric(s) Then
  194. Api_ToInt = CLng(s)
  195. End If
  196. End If
  197. If Api_ToInt < lo Then Api_ToInt = lo
  198. If Api_ToInt > hi Then Api_ToInt = hi
  199. End Function
  200. '-----------------------------------------------------------------------------------------------------------------------
  201. ' Authentication. Returns True and sets Api_TenantId / Api_PrincipalId; otherwise sends 401 and returns False.
  202. '-----------------------------------------------------------------------------------------------------------------------
  203. Function Api_Authenticate()
  204. Dim h, key, rs, expires, keyId
  205. Api_Authenticate = False
  206. Api_TenantId = ""
  207. Api_PrincipalId = ""
  208. h = Api_Header("Authorization")
  209. If LCase(Left(h, 7)) <> "bearer " Then
  210. Response.AddHeader "WWW-Authenticate", "Bearer"
  211. Api_Error 401, "unauthenticated", "Missing or malformed Authorization header. Use: Authorization: Bearer <api key>."
  212. Exit Function
  213. End If
  214. key = Trim(Mid(h, 8))
  215. If Len(key) < 16 Or Len(key) > 200 Then
  216. Response.AddHeader "WWW-Authenticate", "Bearer"
  217. Api_Error 401, "unauthenticated", "Invalid API key."
  218. Exit Function
  219. End If
  220. Set rs = DAL().Query("SELECT k.id, p.id, p.tenant_id, k.expires_at FROM api_keys k " & _
  221. "JOIN principals p ON p.id = k.principal_id JOIN tenants t ON t.id = p.tenant_id " & _
  222. "WHERE k.key_hash = ? AND k.status = 'active' AND p.status = 'active' AND t.status = 'active'", Api_Sha256(key))
  223. If rs.EOF Then
  224. rs.Close
  225. Response.AddHeader "WWW-Authenticate", "Bearer"
  226. Api_Error 401, "unauthenticated", "Invalid API key."
  227. Exit Function
  228. End If
  229. keyId = "" & rs(0)
  230. Api_PrincipalId = "" & rs(1)
  231. Api_TenantId = "" & rs(2)
  232. expires = rs(3)
  233. rs.Close
  234. If Not IsNull(expires) Then
  235. If Len("" & expires) > 0 Then
  236. If "" & expires <= Api_Now() Then
  237. Api_TenantId = ""
  238. Api_PrincipalId = ""
  239. Response.AddHeader "WWW-Authenticate", "Bearer"
  240. Api_Error 401, "unauthenticated", "API key has expired."
  241. Exit Function
  242. End If
  243. End If
  244. End If
  245. DAL().Execute "UPDATE api_keys SET last_used_at = ? WHERE id = ?", Array(Api_Now(), keyId)
  246. Api_Authenticate = True
  247. End Function
  248. '-----------------------------------------------------------------------------------------------------------------------
  249. ' Authorization
  250. '-----------------------------------------------------------------------------------------------------------------------
  251. ' Path of a namespace in the caller's tenant, or Null when it does not exist there.
  252. Function Api_NamespacePath(namespaceId)
  253. Dim rs
  254. Api_NamespacePath = Null
  255. If Not Api_IsId(namespaceId) Then Exit Function
  256. Set rs = DAL().Query("SELECT path FROM namespaces WHERE id = ? AND tenant_id = ?", Array(namespaceId, Api_TenantId))
  257. If Not rs.EOF Then
  258. Api_NamespacePath = "" & rs(0)
  259. End If
  260. rs.Close
  261. End Function
  262. ' True when the principal holds `perm` (or admin) on the path itself, or on an ancestor via an inheriting grant.
  263. Function Api_PathAllows(targetPath, perm)
  264. Dim rs, gPath, perms, inherit, allowed, expires, now_
  265. Api_PathAllows = False
  266. now_ = Api_Now()
  267. Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _
  268. "JOIN namespaces n ON n.id = g.namespace_id " & _
  269. "WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId))
  270. Do While Not rs.EOF
  271. gPath = "" & rs(0)
  272. perms = "," & LCase(Replace("" & rs(1), " ", "")) & ","
  273. inherit = rs(2)
  274. expires = rs(3)
  275. allowed = True
  276. If Not IsNull(expires) Then
  277. If Len("" & expires) > 0 Then
  278. If "" & expires <= now_ Then allowed = False
  279. End If
  280. End If
  281. If allowed Then
  282. If targetPath = gPath Then
  283. allowed = True
  284. ElseIf CLng(inherit) = 1 And Left(targetPath, Len(gPath) + 1) = gPath & "/" Then
  285. allowed = True
  286. ElseIf gPath = "/" And CLng(inherit) = 1 Then
  287. allowed = True
  288. Else
  289. allowed = False
  290. End If
  291. End If
  292. If allowed Then
  293. If InStr(perms, "," & LCase(perm) & ",") > 0 Or InStr(perms, ",admin,") > 0 Then
  294. Api_PathAllows = True
  295. Exit Do
  296. End If
  297. End If
  298. rs.MoveNext
  299. Loop
  300. rs.Close
  301. End Function
  302. ' True when the namespace exists in the caller's tenant AND the caller holds `perm` on it.
  303. Function Api_CanAccessNamespace(namespaceId, perm)
  304. Dim p
  305. Api_CanAccessNamespace = False
  306. p = Api_NamespacePath(namespaceId)
  307. If IsNull(p) Then Exit Function
  308. Api_CanAccessNamespace = Api_PathAllows(p, perm)
  309. End Function
  310. '-----------------------------------------------------------------------------------------------------------------------
  311. ' Audit trail (security-relevant actions; never log secrets or content)
  312. '-----------------------------------------------------------------------------------------------------------------------
  313. Sub Api_Audit(action, resourceType, resourceId, outcome)
  314. On Error Resume Next
  315. DAL().Execute "INSERT INTO audit_events (id, tenant_id, principal_id, action, resource_type, resource_id, outcome, request_id, created_at) " & _
  316. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", _
  317. Array(Api_NewId(), Api_TenantId, Api_PrincipalId, action, resourceType, resourceId, outcome, Api_RequestId(), Api_Now())
  318. Err.Clear
  319. On Error GoTo 0
  320. End Sub
  321. ' 422 with a list of messages. details: array of strings.
  322. Sub Api_Invalid(details)
  323. Dim i, list
  324. list = ""
  325. For i = 0 To UBound(details)
  326. If i > 0 Then list = list & ","
  327. list = list & JsonLite_Quote(details(i))
  328. Next
  329. Api_Send 422, "{""error"":{""code"":""validation_failed"",""message"":""Validation failed."",""details"":[" & list & "],""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
  330. End Sub
  331. ' SQL list of the caller's namespace ids on which `perm` is held, e.g. 'id1','id2' (ids are UUIDs, safe to inline).
  332. ' Empty string when there are none. One grants query plus one namespaces query.
  333. Function Api_AllowedNamespaceIds(perm)
  334. Dim rs, gPaths(), gPerms(), gInh(), n, i, now_, expires, okGrant, p, out, id, path, hit
  335. Api_AllowedNamespaceIds = ""
  336. now_ = Api_Now()
  337. n = 0
  338. ReDim gPaths(7)
  339. ReDim gPerms(7)
  340. ReDim gInh(7)
  341. Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _
  342. "JOIN namespaces n ON n.id = g.namespace_id WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId))
  343. Do While Not rs.EOF
  344. okGrant = True
  345. expires = rs(3)
  346. If Not IsNull(expires) Then
  347. If Len("" & expires) > 0 Then
  348. If "" & expires <= now_ Then okGrant = False
  349. End If
  350. End If
  351. p = "," & LCase(Replace("" & rs(1), " ", "")) & ","
  352. If okGrant And (InStr(p, "," & LCase(perm) & ",") > 0 Or InStr(p, ",admin,") > 0) Then
  353. If n > UBound(gPaths) Then
  354. ReDim Preserve gPaths(n * 2)
  355. ReDim Preserve gPerms(n * 2)
  356. ReDim Preserve gInh(n * 2)
  357. End If
  358. gPaths(n) = "" & rs(0)
  359. gInh(n) = CLng(rs(2))
  360. n = n + 1
  361. End If
  362. rs.MoveNext
  363. Loop
  364. rs.Close
  365. If n = 0 Then Exit Function
  366. out = ""
  367. Set rs = DAL().Query("SELECT id, path FROM namespaces WHERE tenant_id = ?", Api_TenantId)
  368. Do While Not rs.EOF
  369. id = "" & rs(0)
  370. path = "" & rs(1)
  371. hit = False
  372. For i = 0 To n - 1
  373. If path = gPaths(i) Then
  374. hit = True
  375. ElseIf gInh(i) = 1 Then
  376. If gPaths(i) = "/" Then
  377. hit = True
  378. ElseIf Left(path, Len(gPaths(i)) + 1) = gPaths(i) & "/" Then
  379. hit = True
  380. End If
  381. End If
  382. If hit Then Exit For
  383. Next
  384. If hit And Api_IsId(id) Then
  385. If Len(out) > 0 Then out = out & ","
  386. out = out & "'" & id & "'"
  387. End If
  388. rs.MoveNext
  389. Loop
  390. rs.Close
  391. Api_AllowedNamespaceIds = out
  392. End Function
  393. ' Replays the stored response for an Idempotency-Key. Returns True when the request may proceed (key unseen);
  394. ' False after sending the replayed response (same body) or a 409 (key reused with a different body).
  395. Function Api_IdempotencyGate(idemKey, requestHash)
  396. Dim rs
  397. Api_IdempotencyGate = True
  398. If Len(idemKey) = 0 Then Exit Function
  399. Set rs = DAL().Query("SELECT request_hash, status_code, response_body FROM idempotency_keys WHERE tenant_id = ? AND idem_key = ?", Array(Api_TenantId, idemKey))
  400. If Not rs.EOF Then
  401. Api_IdempotencyGate = False
  402. If "" & rs(0) = requestHash Then
  403. Dim st, bodyText
  404. st = CLng(rs(1))
  405. bodyText = "" & rs(2)
  406. rs.Close
  407. Api_Send st, bodyText
  408. Response.AddHeader "Idempotent-Replayed", "true"
  409. Else
  410. rs.Close
  411. Api_Error 409, "idempotency_conflict", "This Idempotency-Key was already used with a different request body."
  412. End If
  413. Exit Function
  414. End If
  415. rs.Close
  416. End Function
  417. Sub Api_IdempotencyStore(idemKey, requestHash, status, bodyText)
  418. If Len(idemKey) = 0 Then Exit Sub
  419. DAL().Execute "INSERT INTO idempotency_keys (tenant_id, idem_key, request_hash, status_code, response_body, created_at) VALUES (?, ?, ?, ?, ?, ?)", _
  420. Array(Api_TenantId, idemKey, requestHash, status, bodyText, Api_Now())
  421. End Sub
  422. %>

Powered by TurnKey Linux.