<% '======================================================================================================================= ' Api support for the memory platform JSON API (/api/v1/...). ' ' Plain global functions (no native object is held across calls: G3CRYPTO is created per use, see AGENTS.md). ' Per-request identity lives in Api_TenantId / Api_PrincipalId, set by Api_Authenticate(). ' ' Authentication : "Authorization: Bearer "; only the SHA-256 of a key is stored (table api_keys). ' Authorization : scope is not permission. A principal can touch a namespace only through an access_grants row ' on that namespace (or an ancestor when the grant has inherit = 1). Permissions: read, write, ' delete, admin (admin implies all). Anything the caller may not see is reported as 404. ' Errors : {"error":{"code":"...","message":"...","request_id":"..."}} '======================================================================================================================= Dim Api_TenantId, Api_PrincipalId, Api_RequestIdValue Api_TenantId = "" Api_PrincipalId = "" Api_RequestIdValue = "" '----------------------------------------------------------------------------------------------------------------------- ' Identifiers, time, hashing '----------------------------------------------------------------------------------------------------------------------- Function Api_NewId() Dim c Set c = Server.CreateObject("G3CRYPTO") Api_NewId = LCase(c.UUID()) End Function Function Api_Sha256(text) Dim c Set c = Server.CreateObject("G3CRYPTO") Api_Sha256 = LCase(c.SHA256("" & text)) End Function ' UTC timestamp as 'YYYY-MM-DD HH:MM:SS'. The container runs in UTC, so Now() is UTC. Function Api_Now() Dim d d = Now() Api_Now = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2) & " " & _ Right("0" & Hour(d), 2) & ":" & Right("0" & Minute(d), 2) & ":" & Right("0" & Second(d), 2) End Function Function Api_RequestId() If Len(Api_RequestIdValue) = 0 Then Api_RequestIdValue = "req-" & Api_NewId() End If Api_RequestId = Api_RequestIdValue End Function ' True for the opaque ids this API issues (UUID text). Used before an id goes anywhere near SQL or a path. Function Api_IsId(s) Dim t, i, c Api_IsId = False t = "" & s If Len(t) <> 36 Then Exit Function For i = 1 To 36 c = Mid(t, i, 1) If i = 9 Or i = 14 Or i = 19 Or i = 24 Then If c <> "-" Then Exit Function Else If Not ((c >= "0" And c <= "9") Or (c >= "a" And c <= "f")) Then Exit Function End If Next Api_IsId = True End Function '----------------------------------------------------------------------------------------------------------------------- ' Responses '----------------------------------------------------------------------------------------------------------------------- Function Api_StatusLine(status) Select Case status Case 200: Api_StatusLine = "200 OK" Case 201: Api_StatusLine = "201 Created" Case 400: Api_StatusLine = "400 Bad Request" Case 401: Api_StatusLine = "401 Unauthorized" Case 403: Api_StatusLine = "403 Forbidden" Case 404: Api_StatusLine = "404 Not Found" Case 405: Api_StatusLine = "405 Method Not Allowed" Case 409: Api_StatusLine = "409 Conflict" Case 412: Api_StatusLine = "412 Precondition Failed" Case 413: Api_StatusLine = "413 Payload Too Large" Case 422: Api_StatusLine = "422 Unprocessable Entity" Case 428: Api_StatusLine = "428 Precondition Required" Case 500: Api_StatusLine = "500 Internal Server Error" Case 503: Api_StatusLine = "503 Service Unavailable" Case Else: Api_StatusLine = status & " Status" End Select End Function Sub Api_Send(status, jsonText) Response.Clear Response.Status = Api_StatusLine(status) Response.ContentType = "application/json" Response.Charset = "utf-8" Response.AddHeader "X-Request-Id", Api_RequestId() Response.AddHeader "Cache-Control", "no-store" Response.Write jsonText End Sub Sub Api_Error(status, code, message) Api_Send status, "{""error"":{""code"":" & JsonLite_Quote(code) & ",""message"":" & JsonLite_Quote(message) & _ ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}" End Sub Sub Api_NotFound() Api_Error 404, "not_found", "Resource not found." End Sub Dim Api_LastDbError Api_LastDbError = "" ' Call straight after a failing statement (before any rollback) so the description is kept for Api_DbFailed. Sub Api_NoteDbError() Api_LastDbError = "" & Err.Description End Sub ' A failed database call becomes a JSON 500. The database text is only included when Environment = Development. Sub Api_DbFailed(errNumber, errDescription) Dim msg Err.Clear On Error GoTo 0 msg = "Internal error (" & errNumber & "). The request was not completed." If LCase(GetAppSetting("Environment")) = "development" And Len(Api_LastDbError) > 0 Then msg = msg & " [dev] " & Api_LastDbError End If Api_Error 500, "internal_error", msg End Sub '----------------------------------------------------------------------------------------------------------------------- ' Request helpers '----------------------------------------------------------------------------------------------------------------------- Function Api_Header(name) Api_Header = Trim("" & Request.ServerVariables("HTTP_" & UCase(Replace(name, "-", "_")))) End Function ' Request body as UTF-8 text, or Empty after sending a 400. Function Api_ReadBody() Api_ReadBody = Api_ReadBodyMax(1048576) End Function ' Same with a caller-chosen size limit in bytes (imports accept more than ordinary writes). Function Api_ReadBodyMax(maxBytes) Dim n, text Api_ReadBodyMax = Empty n = Request.TotalBytes If n = 0 Then Api_Error 400, "empty_body", "Request body is empty. Send a JSON object." Exit Function End If If n > maxBytes Then Api_Error 413, "body_too_large", "Request body exceeds " & (maxBytes \ 1048576) & " MiB." Exit Function End If Api_Utf8Unsupported = False text = Api_Utf8Decode(CStr(Request.BinaryRead(n))) If JsonLite_Parse(text) Is Nothing Then Api_Error 400, "invalid_json", "Body must be a valid JSON object." Exit Function End If ' Reject rather than store damaged text (see Api_Utf8Decode) If Api_Utf8Unsupported Or JsonLite_SurrogateSeen Then Api_Error 422, "unsupported_character", "Characters above U+FFFF (for example emoji) are not supported yet. Remove or replace them." Exit Function End If Api_ReadBodyMax = text End Function Dim Api_Utf8Unsupported Api_Utf8Unsupported = False ' Decodes a string holding raw UTF-8 bytes (one byte per character, as AxonASP BinaryRead returns) into Unicode text. ' The bytes are split into alternating ASCII / non-ASCII runs with ONE call to the RegExp engine (character loops over a ' large body were quadratic on AxonASP and timed out). ASCII runs are copied; a strictly valid non-ASCII run is ' decoded natively (percent-encoded, then G3AXON AxUrlDecode); a run with invalid bytes, encoded surrogates or 4-byte ' sequences goes through Api_Utf8DecodeRun (U+FFFD, and Api_Utf8Unsupported for characters above U+FFFF). ' Match.FirstIndex is not used: on this build it is a byte offset into the runtime's UTF-8 string, not a character index. Function Api_Utf8Decode(ByVal s) Dim re, ms, m, sb, reOk, ax, v, enc, n Set re = Server.CreateObject("VBScript.RegExp") re.Global = True re.Pattern = "[\x00-\x7F]+|[\x80-\xFF]+" Set ms = re.Execute(s) If ms.Count <= 1 Then If ms.Count = 0 Then Api_Utf8Decode = s Exit Function End If If AscW(Left(s, 1)) < 128 Then If AscW(Left(s, 1)) >= 0 Then Api_Utf8Decode = s ' pure ASCII Exit Function End If End If End If ' well-formed UTF-8 of code points up to U+FFFF, excluding surrogates and overlong forms Set reOk = Server.CreateObject("VBScript.RegExp") reOk.Global = True reOk.Pattern = "[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF][\x80-\xBF]|\xED[\x80-\x9F][\x80-\xBF]" Set ax = Server.CreateObject("G3AXON.FUNCTIONS") Set sb = Server.CreateObject("G3STRINGBUILDER") For Each m In ms v = m.Value n = AscW(Left(v, 1)) If n >= 0 And n < 128 Then sb.Append v ElseIf Len(reOk.Replace(v, "")) = 0 Then enc = v For n = 128 To 255 enc = Replace(enc, ChrW(n), "%" & Hex(n)) Next sb.Append ax.AxUrlDecode(enc) Else Api_Utf8DecodeRun v, sb End If Next Api_Utf8Decode = sb.ToString() Set sb = Nothing End Function ' Decodes one run of bytes >= 0x80 byte by byte (the slow path for runs that are not plain valid UTF-8). A sequence cut ' 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. Sub Api_Utf8DecodeRun(run, sb) Dim i, n, c, cp, extra, k, ok, b n = Len(run) i = 1 Do While i <= n c = AscW(Mid(run, i, 1)) And 255 extra = -1 cp = 0 If c >= 240 And c <= 247 Then extra = 3 cp = c And 7 ElseIf c >= 224 And c <= 239 Then extra = 2 cp = c And 15 ElseIf c >= 194 And c <= 223 Then extra = 1 cp = c And 31 End If ok = (extra > 0 And i + extra <= n) If ok Then For k = 1 To extra b = AscW(Mid(run, i + k, 1)) And 255 If b < 128 Or b > 191 Then ok = False Else cp = cp * 64 + (b And 63) End If Next End If If ok And cp <= 1114111 Then ' On the pinned AxonASP build ChrW(cp > 65535) raises "Invalid procedure call" and a surrogate pair ' is written out as CESU-8, so code points above U+FFFF (and encoded surrogates) cannot be held. ' They become U+FFFD and set Api_Utf8Unsupported; Api_ReadBody then answers 422. If cp > 65535 Or (cp >= 55296 And cp <= 57343) Then Api_Utf8Unsupported = True sb.Append ChrW(65533) Else sb.Append ChrW(cp) End If i = i + extra + 1 Else sb.Append ChrW(65533) i = i + 1 End If Loop End Sub Function Api_ToInt(v, dflt, lo, hi) Dim s s = Trim("" & v) Api_ToInt = dflt If Len(s) > 0 Then If IsNumeric(s) Then Api_ToInt = CLng(s) End If End If If Api_ToInt < lo Then Api_ToInt = lo If Api_ToInt > hi Then Api_ToInt = hi End Function '----------------------------------------------------------------------------------------------------------------------- ' Authentication. Returns True and sets Api_TenantId / Api_PrincipalId; otherwise sends 401 and returns False. '----------------------------------------------------------------------------------------------------------------------- Function Api_Authenticate() Dim h, key, rs, expires, keyId Api_Authenticate = False Api_TenantId = "" Api_PrincipalId = "" h = Api_Header("Authorization") If LCase(Left(h, 7)) <> "bearer " Then Response.AddHeader "WWW-Authenticate", "Bearer" Api_Error 401, "unauthenticated", "Missing or malformed Authorization header. Use: Authorization: Bearer ." Exit Function End If key = Trim(Mid(h, 8)) If Len(key) < 16 Or Len(key) > 200 Then Response.AddHeader "WWW-Authenticate", "Bearer" Api_Error 401, "unauthenticated", "Invalid API key." Exit Function End If Set rs = DAL().Query("SELECT k.id, p.id, p.tenant_id, k.expires_at FROM api_keys k " & _ "JOIN principals p ON p.id = k.principal_id JOIN tenants t ON t.id = p.tenant_id " & _ "WHERE k.key_hash = ? AND k.status = 'active' AND p.status = 'active' AND t.status = 'active'", Api_Sha256(key)) If rs.EOF Then rs.Close Response.AddHeader "WWW-Authenticate", "Bearer" Api_Error 401, "unauthenticated", "Invalid API key." Exit Function End If keyId = "" & rs(0) Api_PrincipalId = "" & rs(1) Api_TenantId = "" & rs(2) expires = rs(3) rs.Close If Not IsNull(expires) Then If Len("" & expires) > 0 Then If "" & expires <= Api_Now() Then Api_TenantId = "" Api_PrincipalId = "" Response.AddHeader "WWW-Authenticate", "Bearer" Api_Error 401, "unauthenticated", "API key has expired." Exit Function End If End If End If DAL().Execute "UPDATE api_keys SET last_used_at = ? WHERE id = ?", Array(Api_Now(), keyId) Api_Authenticate = True End Function '----------------------------------------------------------------------------------------------------------------------- ' Authorization '----------------------------------------------------------------------------------------------------------------------- ' Path of a namespace in the caller's tenant, or Null when it does not exist there. Function Api_NamespacePath(namespaceId) Dim rs Api_NamespacePath = Null If Not Api_IsId(namespaceId) Then Exit Function Set rs = DAL().Query("SELECT path FROM namespaces WHERE id = ? AND tenant_id = ?", Array(namespaceId, Api_TenantId)) If Not rs.EOF Then Api_NamespacePath = "" & rs(0) End If rs.Close End Function ' True when the principal holds `perm` (or admin) on the path itself, or on an ancestor via an inheriting grant. Function Api_PathAllows(targetPath, perm) Dim rs, gPath, perms, inherit, allowed, expires, now_ Api_PathAllows = False now_ = Api_Now() Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _ "JOIN namespaces n ON n.id = g.namespace_id " & _ "WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId)) Do While Not rs.EOF gPath = "" & rs(0) perms = "," & LCase(Replace("" & rs(1), " ", "")) & "," inherit = rs(2) expires = rs(3) allowed = True If Not IsNull(expires) Then If Len("" & expires) > 0 Then If "" & expires <= now_ Then allowed = False End If End If If allowed Then If targetPath = gPath Then allowed = True ElseIf CLng(inherit) = 1 And Left(targetPath, Len(gPath) + 1) = gPath & "/" Then allowed = True ElseIf gPath = "/" And CLng(inherit) = 1 Then allowed = True Else allowed = False End If End If If allowed Then If InStr(perms, "," & LCase(perm) & ",") > 0 Or InStr(perms, ",admin,") > 0 Then Api_PathAllows = True Exit Do End If End If rs.MoveNext Loop rs.Close End Function ' True when the namespace exists in the caller's tenant AND the caller holds `perm` on it. Function Api_CanAccessNamespace(namespaceId, perm) Dim p Api_CanAccessNamespace = False p = Api_NamespacePath(namespaceId) If IsNull(p) Then Exit Function Api_CanAccessNamespace = Api_PathAllows(p, perm) End Function '----------------------------------------------------------------------------------------------------------------------- ' Audit trail (security-relevant actions; never log secrets or content) '----------------------------------------------------------------------------------------------------------------------- Sub Api_Audit(action, resourceType, resourceId, outcome) On Error Resume Next DAL().Execute "INSERT INTO audit_events (id, tenant_id, principal_id, action, resource_type, resource_id, outcome, request_id, created_at) " & _ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", _ Array(Api_NewId(), Api_TenantId, Api_PrincipalId, action, resourceType, resourceId, outcome, Api_RequestId(), Api_Now()) Err.Clear On Error GoTo 0 End Sub ' 422 with a list of messages. details: array of strings. Sub Api_Invalid(details) Dim i, list list = "" For i = 0 To UBound(details) If i > 0 Then list = list & "," list = list & JsonLite_Quote(details(i)) Next Api_Send 422, "{""error"":{""code"":""validation_failed"",""message"":""Validation failed."",""details"":[" & list & "],""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}" End Sub ' SQL list of the caller's namespace ids on which `perm` is held, e.g. 'id1','id2' (ids are UUIDs, safe to inline). ' Empty string when there are none. One grants query plus one namespaces query. Function Api_AllowedNamespaceIds(perm) Dim rs, gPaths(), gPerms(), gInh(), n, i, now_, expires, okGrant, p, out, id, path, hit Api_AllowedNamespaceIds = "" now_ = Api_Now() n = 0 ReDim gPaths(7) ReDim gPerms(7) ReDim gInh(7) Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _ "JOIN namespaces n ON n.id = g.namespace_id WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId)) Do While Not rs.EOF okGrant = True expires = rs(3) If Not IsNull(expires) Then If Len("" & expires) > 0 Then If "" & expires <= now_ Then okGrant = False End If End If p = "," & LCase(Replace("" & rs(1), " ", "")) & "," If okGrant And (InStr(p, "," & LCase(perm) & ",") > 0 Or InStr(p, ",admin,") > 0) Then If n > UBound(gPaths) Then ReDim Preserve gPaths(n * 2) ReDim Preserve gPerms(n * 2) ReDim Preserve gInh(n * 2) End If gPaths(n) = "" & rs(0) gInh(n) = CLng(rs(2)) n = n + 1 End If rs.MoveNext Loop rs.Close If n = 0 Then Exit Function out = "" Set rs = DAL().Query("SELECT id, path FROM namespaces WHERE tenant_id = ?", Api_TenantId) Do While Not rs.EOF id = "" & rs(0) path = "" & rs(1) hit = False For i = 0 To n - 1 If path = gPaths(i) Then hit = True ElseIf gInh(i) = 1 Then If gPaths(i) = "/" Then hit = True ElseIf Left(path, Len(gPaths(i)) + 1) = gPaths(i) & "/" Then hit = True End If End If If hit Then Exit For Next If hit And Api_IsId(id) Then If Len(out) > 0 Then out = out & "," out = out & "'" & id & "'" End If rs.MoveNext Loop rs.Close Api_AllowedNamespaceIds = out End Function ' Replays the stored response for an Idempotency-Key. Returns True when the request may proceed (key unseen); ' False after sending the replayed response (same body) or a 409 (key reused with a different body). Function Api_IdempotencyGate(idemKey, requestHash) Dim rs Api_IdempotencyGate = True If Len(idemKey) = 0 Then Exit Function Set rs = DAL().Query("SELECT request_hash, status_code, response_body FROM idempotency_keys WHERE tenant_id = ? AND idem_key = ?", Array(Api_TenantId, idemKey)) If Not rs.EOF Then Api_IdempotencyGate = False If "" & rs(0) = requestHash Then Dim st, bodyText st = CLng(rs(1)) bodyText = "" & rs(2) rs.Close Api_Send st, bodyText Response.AddHeader "Idempotent-Replayed", "true" Else rs.Close Api_Error 409, "idempotency_conflict", "This Idempotency-Key was already used with a different request body." End If Exit Function End If rs.Close End Function Sub Api_IdempotencyStore(idemKey, requestHash, status, bodyText) If Len(idemKey) = 0 Then Exit Sub DAL().Execute "INSERT INTO idempotency_keys (tenant_id, idem_key, request_hash, status_code, response_body, created_at) VALUES (?, ?, ?, ?, ?, ?)", _ Array(Api_TenantId, idemKey, requestHash, status, bodyText, Api_Now()) End Sub %>