<% ' ApiAdminController: management of namespaces, principals, API keys and grants inside the caller's tenant ' (spec section 9 "Management", FR-017, section 16 least privilege). Replaces scripts\provision.cmd for day-to-day work; ' tenants, top-level namespaces and purges stay with the CLI. ' ' GET /api/v1/me WhoAmI the caller: principal, tenant, grants ' GET /api/v1/namespaces Namespaces namespaces the caller can read, with its permissions on each ' POST /api/v1/namespaces CreateNamespace {"path":"/a/b"} (missing parents are created) ' GET /api/v1/principals Principals principals of the tenant (admins only) ' POST /api/v1/principals CreatePrincipal {"name","type":"human|agent|service"} -> principal + API key (once) ' GET /api/v1/principals/:id Principal principal, its keys (when manageable) and grants ' PATCH /api/v1/principals/:id UpdatePrincipal {"status":"active|disabled"} ' POST /api/v1/principals/:id/keys CreateKey new API key (shown once) ' DELETE /api/v1/keys/:id RevokeKey ' GET /api/v1/grants Grants ?namespace_id=&principal_id= (grants the caller administers) ' POST /api/v1/grants CreateGrant {"principal_id","namespace_id","permissions":[...],"inherit":true, ' "expires_at":"YYYY-MM-DD HH:MM:SS"} ' DELETE /api/v1/grants/:id DeleteGrant ' ' Authorization (docs/decisions.md ADR-011): ' - "admin" on a namespace lets the caller create namespaces below it, and grant or revoke access on it. Granting with ' inherit, or creating a namespace below, needs an inheriting admin grant (one that also covers descendants). ' - Listing principals and creating one needs admin on at least one namespace. ' - Managing another principal (keys, status) needs admin on every namespace that principal holds a grant on, ' inheriting where that grant inherits, so a key can never give the caller more access than it already has. ' Callers may always manage their own keys. Placeholder principals from imports cannot be managed. ' - No permission answers 404, as everywhere in the API. Responses that contain a key are sent with no-store. ' - Idempotency-Key is not supported on these endpoints: a replay would have to store the plain key. Const ADM_PERMS = ",read,write,delete,verify,admin," Class ApiAdminController_Class Private m_errs Public Property Get useLayout() useLayout = False End Property Public Property Let useLayout(v) End Property Public Property Get Title() Title = "Admin API" End Property '--------------------------------------------------------------- ' GET /api/v1/me '--------------------------------------------------------------- Public Sub WhoAmI() Dim rs, name, pType, out If Not Api_Authenticate() Then Exit Sub Set rs = DAL().Query("SELECT name, type FROM principals WHERE id = ?", Api_PrincipalId) name = "" & rs(0) pType = "" & rs(1) rs.Close out = "{""principal_id"":" & JsonLite_Quote(Api_PrincipalId) & ",""tenant_id"":" & JsonLite_Quote(Api_TenantId) & _ ",""name"":" & JsonLite_Quote(name) & ",""type"":" & JsonLite_Quote(pType) & _ ",""grants"":" & GrantsJson("g.principal_id = ?", Api_PrincipalId) & "}" Api_Send 200, out End Sub '--------------------------------------------------------------- ' GET /api/v1/namespaces '--------------------------------------------------------------- Public Sub Namespaces() Dim readable, perms(), names, i, rs, out, id, p If Not Api_Authenticate() Then Exit Sub readable = Api_AllowedNamespaceIds("read") If Len(readable) = 0 Then Api_Send 200, "{""data"":[]}" Exit Sub End If names = Array("read", "write", "delete", "verify", "admin") ReDim perms(4) For i = 0 To 4 perms(i) = "," & Api_AllowedNamespaceIds(names(i)) & "," Next out = "" Set rs = DAL().Query("SELECT id, path, parent_id, created_at FROM namespaces WHERE tenant_id = ? AND id IN (" & readable & ") ORDER BY path", Api_TenantId) Do While Not rs.EOF id = "" & rs(0) p = "" For i = 0 To 4 If InStr(perms(i), ",'" & id & "',") > 0 Then If Len(p) > 0 Then p = p & "," End If p = p & JsonLite_Quote(names(i)) End If Next If Len(out) > 0 Then out = out & "," End If out = out & "{""id"":" & JsonLite_Quote(id) & ",""path"":" & JsonLite_Quote("" & rs(1)) & _ ",""parent_id"":" & JStr(rs(2)) & ",""permissions"":[" & p & "],""created_at"":" & JsonLite_Quote("" & rs(3)) & "}" rs.MoveNext Loop rs.Close Api_Send 200, "{""data"":[" & out & "]}" End Sub '--------------------------------------------------------------- ' POST /api/v1/namespaces {"path":"/a/b"} '--------------------------------------------------------------- Public Sub CreateNamespace() Dim body, input, path, rs, parts, i, cur, parentId, id, created, k, existing If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" path = LCase(ReqString(input, "path", 400)) If Len(m_errs) = 0 Then If Not ValidPath(path) Then AddErr "path must look like /team/project: lower-case a-z, 0-9, '-', '_' and '.', separated by '/'." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If ' The new namespace must be covered by an inheriting admin grant of the caller. If Not Api_PathAllows(path, "admin") Then Api_Audit "admin.namespace.create", "namespace", "", "denied" Api_NotFound Exit Sub End If Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, path)) existing = "" If Not rs.EOF Then existing = "" & rs(0) End If rs.Close If Len(existing) > 0 Then Api_Error 409, "namespace_exists", "A namespace with this path already exists (" & existing & ")." Exit Sub End If parts = Split(Mid(path, 2), "/") cur = "" parentId = Null created = 0 On Error Resume Next DAL().BeginTransaction For i = 0 To UBound(parts) cur = cur & "/" & parts(i) Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, cur)) id = "" If Err.Number = 0 Then If Not rs.EOF Then id = "" & rs(0) End If rs.Close End If If Err.Number <> 0 Then Exit For End If If Len(id) = 0 Then id = Api_NewId() DAL().Execute "INSERT INTO namespaces (id, tenant_id, parent_id, name, path, owner_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", _ Array(id, Api_TenantId, parentId, parts(i), cur, Api_PrincipalId, Api_Now()) If Err.Number <> 0 Then Exit For End If created = created + 1 End If parentId = id Next If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Err.Clear DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "admin.namespace.create", "namespace", id, "ok" Response.AddHeader "Location", "/api/v1/namespaces" Api_Send 201, "{""id"":" & JsonLite_Quote(id) & ",""path"":" & JsonLite_Quote(path) & ",""parent_id"":" & JStr(parentAt(path)) & _ ",""namespaces_created"":" & created & "}" End Sub '--------------------------------------------------------------- ' GET /api/v1/principals '--------------------------------------------------------------- Public Sub Principals() Dim rs, out If Not Api_Authenticate() Then Exit Sub If Len(Api_AllowedNamespaceIds("admin")) = 0 Then Api_NotFound Exit Sub End If out = "" Set rs = DAL().Query("SELECT id, name, type, status, created_at FROM principals WHERE tenant_id = ? ORDER BY created_at, id", Api_TenantId) Do While Not rs.EOF If Len(out) > 0 Then out = out & "," End If out = out & PrincipalJson(rs(0), rs(1), rs(2), rs(3), rs(4)) rs.MoveNext Loop rs.Close Api_Send 200, "{""data"":[" & out & "]}" End Sub '--------------------------------------------------------------- ' POST /api/v1/principals {"name","type"} '--------------------------------------------------------------- Public Sub CreatePrincipal() Dim body, input, name, pType, id, keyId, plain, ts, k If Not Api_Authenticate() Then Exit Sub If Len(Api_AllowedNamespaceIds("admin")) = 0 Then Api_Audit "admin.principal.create", "principal", "", "denied" Api_NotFound Exit Sub End If body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" name = ReqString(input, "name", 200) pType = LCase(ReqString(input, "type", 20)) If Len(m_errs) = 0 Then If pType <> "human" And pType <> "agent" And pType <> "service" Then AddErr "type must be human, agent or service." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If id = Api_NewId() ts = Api_Now() plain = NewKeyText() keyId = Api_NewId() On Error Resume Next DAL().BeginTransaction DAL().Execute "INSERT INTO principals (id, tenant_id, type, name, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _ Array(id, Api_TenantId, pType, name, ts) If Err.Number = 0 Then DAL().Execute "INSERT INTO api_keys (id, principal_id, key_hash, key_prefix, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _ Array(keyId, id, Api_Sha256(plain), Left(plain, 8), ts) End If If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Err.Clear DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "admin.principal.create", "principal", id, "ok" Response.AddHeader "Location", "/api/v1/principals/" & id Response.AddHeader "Cache-Control", "no-store" Api_Send 201, "{""principal"":" & PrincipalJson(id, name, pType, "active", ts) & ",""api_key"":" & KeyJson(keyId, plain, ts) & "}" End Sub '--------------------------------------------------------------- ' GET /api/v1/principals/:id '--------------------------------------------------------------- Public Sub Principal(id) Dim rs, pj, isSelf, keys, grants, adminIds If Not Api_Authenticate() Then Exit Sub isSelf = (id = Api_PrincipalId) adminIds = Api_AllowedNamespaceIds("admin") If Not isSelf And Len(adminIds) = 0 Then Api_NotFound Exit Sub End If pj = LoadPrincipalJson(id) If Len(pj) = 0 Then Api_NotFound Exit Sub End If If isSelf Then grants = GrantsJson("g.principal_id = ?", id) Else grants = GrantsJson("g.principal_id = ? AND g.namespace_id IN (" & adminIds & ")", id) End If keys = "null" If CanManage(id) Then keys = "" Set rs = DAL().Query("SELECT id, key_prefix, status, created_at, expires_at, last_used_at FROM api_keys WHERE principal_id = ? ORDER BY created_at, id", id) Do While Not rs.EOF If Len(keys) > 0 Then keys = keys & "," End If keys = keys & "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""prefix"":" & JsonLite_Quote("" & rs(1)) & _ ",""status"":" & JsonLite_Quote("" & rs(2)) & ",""created_at"":" & JsonLite_Quote("" & rs(3)) & _ ",""expires_at"":" & JStr(rs(4)) & ",""last_used_at"":" & JStr(rs(5)) & "}" rs.MoveNext Loop rs.Close keys = "[" & keys & "]" End If Api_Send 200, Left(pj, Len(pj) - 1) & ",""keys"":" & keys & ",""grants"":" & grants & "}" End Sub '--------------------------------------------------------------- ' PATCH /api/v1/principals/:id {"status":"active|disabled"} '--------------------------------------------------------------- Public Sub UpdatePrincipal(id) Dim body, input, status, k, pj If Not Api_Authenticate() Then Exit Sub If Not CanManage(id) Then Api_Audit "admin.principal.update", "principal", id, "denied" Api_NotFound Exit Sub End If body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" status = LCase(ReqString(input, "status", 20)) If Len(m_errs) = 0 Then If status <> "active" And status <> "disabled" Then AddErr "status must be active or disabled." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If id = Api_PrincipalId Then Api_Error 422, "cannot_change_self", "A principal cannot change its own status." Exit Sub End If On Error Resume Next DAL().Execute "UPDATE principals SET status = ? WHERE id = ? AND tenant_id = ?", Array(status, id, Api_TenantId) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "admin.principal.update", "principal", id, status pj = LoadPrincipalJson(id) Api_Send 200, pj End Sub '--------------------------------------------------------------- ' POST /api/v1/principals/:id/keys '--------------------------------------------------------------- Public Sub CreateKey(id) Dim rs, status, keyId, plain, ts, k If Not Api_Authenticate() Then Exit Sub If Not CanManage(id) Then Api_Audit "admin.key.create", "principal", id, "denied" Api_NotFound Exit Sub End If Set rs = DAL().Query("SELECT status FROM principals WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) status = "" & rs(0) rs.Close If status <> "active" Then Api_Error 409, "principal_not_active", "Keys can only be created for an active principal; this one is " & status & "." Exit Sub End If plain = NewKeyText() keyId = Api_NewId() ts = Api_Now() On Error Resume Next DAL().Execute "INSERT INTO api_keys (id, principal_id, key_hash, key_prefix, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _ Array(keyId, id, Api_Sha256(plain), Left(plain, 8), ts) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "admin.key.create", "api_key", keyId, "ok" Response.AddHeader "Cache-Control", "no-store" Api_Send 201, "{""principal_id"":" & JsonLite_Quote(id) & ",""api_key"":" & KeyJson(keyId, plain, ts) & "}" End Sub '--------------------------------------------------------------- ' DELETE /api/v1/keys/:id '--------------------------------------------------------------- Public Sub RevokeKey(id) Dim rs, pid, k If Not Api_Authenticate() Then Exit Sub pid = "" If Api_IsId(id) Then Set rs = DAL().Query("SELECT k.principal_id FROM api_keys k JOIN principals p ON p.id = k.principal_id WHERE k.id = ? AND p.tenant_id = ?", Array(id, Api_TenantId)) If Not rs.EOF Then pid = "" & rs(0) End If rs.Close End If If Len(pid) = 0 Then Api_NotFound Exit Sub End If If Not CanManage(pid) Then Api_Audit "admin.key.revoke", "api_key", id, "denied" Api_NotFound Exit Sub End If On Error Resume Next DAL().Execute "UPDATE api_keys SET status = 'revoked' WHERE id = ?", id If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "admin.key.revoke", "api_key", id, "ok" Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""principal_id"":" & JsonLite_Quote(pid) & ",""status"":""revoked""}" End Sub '--------------------------------------------------------------- ' GET /api/v1/grants?namespace_id=&principal_id= '--------------------------------------------------------------- Public Sub Grants() Dim adminIds, ns, pid, where, params If Not Api_Authenticate() Then Exit Sub adminIds = Api_AllowedNamespaceIds("admin") If Len(adminIds) = 0 Then Api_NotFound Exit Sub End If ns = Trim("" & Request.QueryString("namespace_id")) pid = Trim("" & Request.QueryString("principal_id")) m_errs = "" If Len(ns) > 0 Then If Not Api_IsId(ns) Then AddErr "namespace_id must be a valid id." End If End If If Len(pid) > 0 Then If Not Api_IsId(pid) Then AddErr "principal_id must be a valid id." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If where = "g.namespace_id IN (" & adminIds & ")" If Len(ns) > 0 And Len(pid) > 0 Then where = where & " AND g.namespace_id = ? AND g.principal_id = ?" params = Array(ns, pid) ElseIf Len(ns) > 0 Then where = where & " AND g.namespace_id = ?" params = ns ElseIf Len(pid) > 0 Then where = where & " AND g.principal_id = ?" params = pid Else params = Empty End If Api_Send 200, "{""data"":" & GrantsJson(where, params) & "}" End Sub '--------------------------------------------------------------- ' POST /api/v1/grants '--------------------------------------------------------------- Public Sub CreateGrant() Dim body, input, pid, ns, permsArr, perms, inherit, expires, i, p, path, rs, pStatus, existing, id, ts, k If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" pid = ReqString(input, "principal_id", 64) ns = ReqString(input, "namespace_id", 64) If Len(pid) > 0 Then If Not Api_IsId(pid) Then AddErr "principal_id must be a valid id." End If End If If Len(ns) > 0 Then If Not Api_IsId(ns) Then AddErr "namespace_id must be a valid id." End If End If perms = "" If input.HasRaw("permissions") Then permsArr = JsonLite_ParseStringArray(input.Raw("permissions")) Else permsArr = Null End If If IsNull(permsArr) Then AddErr "permissions must be a non-empty array of read, write, delete, verify, admin." Else For i = 0 To UBound(permsArr) p = LCase(Trim(permsArr(i))) If InStr(ADM_PERMS, "," & p & ",") = 0 Or Len(p) = 0 Then AddErr "unknown permission: " & permsArr(i) & " (allowed: read, write, delete, verify, admin)." Exit For End If If InStr("," & perms & ",", "," & p & ",") = 0 Then If Len(perms) > 0 Then perms = perms & "," End If perms = perms & p End If Next If Len(perms) = 0 And Len(m_errs) = 0 Then AddErr "permissions must not be empty." End If End If inherit = 1 If input.Exists("inherit") Then If VarType(input.Item("inherit")) = vbBoolean Then If Not input.Item("inherit") Then inherit = 0 End If Else AddErr "inherit must be true or false." End If End If expires = OptString(input, "expires_at", 19) If Not IsNull(expires) Then If Not IsTimestamp(expires) Then AddErr "expires_at must be a UTC time like 2027-01-31 18:00:00." ElseIf expires <= Api_Now() Then AddErr "expires_at must be in the future." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If ' Admin on the namespace; an inheriting grant also needs inheriting admin (it reaches every descendant). path = Api_NamespacePath(ns) If IsNull(path) Then Api_NotFound Exit Sub End If If Not Api_PathAllows(path, "admin") Then Api_Audit "admin.grant.create", "namespace", ns, "denied" Api_NotFound Exit Sub End If If inherit = 1 Then If Not Api_PathAllows(path & "/*", "admin") Then Api_Error 422, "inherit_not_allowed", "Your admin access on this namespace does not extend to its descendants; grant with inherit false." Exit Sub End If End If Set rs = DAL().Query("SELECT status FROM principals WHERE id = ? AND tenant_id = ?", Array(pid, Api_TenantId)) pStatus = "" If Not rs.EOF Then pStatus = "" & rs(0) End If rs.Close If pStatus <> "active" Then Api_Error 422, "principal_not_found", "principal_id must be an active principal of your tenant." Exit Sub End If Set rs = DAL().Query("SELECT id FROM access_grants WHERE principal_id = ? AND namespace_id = ?", Array(pid, ns)) existing = "" If Not rs.EOF Then existing = "" & rs(0) End If rs.Close If Len(existing) > 0 Then Api_Error 409, "grant_exists", "This principal already has a grant on this namespace (" & existing & "); delete it first to change it." Exit Sub End If id = Api_NewId() ts = Api_Now() On Error Resume Next DAL().Execute "INSERT INTO access_grants (id, principal_id, namespace_id, permissions, inherit, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)", _ Array(id, pid, ns, perms, inherit, ts, expires) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "admin.grant.create", "grant", id, perms Response.AddHeader "Location", "/api/v1/grants?principal_id=" & pid Api_Send 201, GrantJson(id, pid, ns, path, perms, inherit, expires, ts) End Sub '--------------------------------------------------------------- ' DELETE /api/v1/grants/:id '--------------------------------------------------------------- Public Sub DeleteGrant(id) Dim rs, pid, path, k If Not Api_Authenticate() Then Exit Sub pid = "" If Api_IsId(id) Then Set rs = DAL().Query("SELECT g.principal_id, n.path FROM access_grants g JOIN namespaces n ON n.id = g.namespace_id WHERE g.id = ? AND n.tenant_id = ?", Array(id, Api_TenantId)) If Not rs.EOF Then pid = "" & rs(0) path = "" & rs(1) End If rs.Close End If If Len(pid) = 0 Then Api_NotFound Exit Sub End If If Not Api_PathAllows(path, "admin") Then Api_Audit "admin.grant.delete", "grant", id, "denied" Api_NotFound Exit Sub End If If pid = Api_PrincipalId Then Api_Error 422, "cannot_change_self", "A principal cannot remove its own grants; ask another admin." Exit Sub End If On Error Resume Next DAL().Execute "DELETE FROM access_grants WHERE id = ?", id If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "admin.grant.delete", "grant", id, "ok" Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""deleted"":true}" End Sub '--------------------------------------------------------------- ' Helpers '--------------------------------------------------------------- ' True when the caller may manage principal pid (keys, status): itself, or a principal of the tenant whose every ' grant lies where the caller holds admin (inheriting admin where the grant inherits). Never for placeholders. Private Function CanManage(pid) Dim rs, status, paths(), inh(), n, i CanManage = False If Not Api_IsId(pid) Then Exit Function Set rs = DAL().Query("SELECT status FROM principals WHERE id = ? AND tenant_id = ?", Array(pid, Api_TenantId)) status = "" If Not rs.EOF Then status = "" & rs(0) End If rs.Close If Len(status) = 0 Or status = "imported" Then Exit Function If pid = Api_PrincipalId Then CanManage = True Exit Function End If If Len(Api_AllowedNamespaceIds("admin")) = 0 Then Exit Function n = 0 ReDim paths(7) ReDim inh(7) Set rs = DAL().Query("SELECT n.path, g.inherit FROM access_grants g JOIN namespaces n ON n.id = g.namespace_id WHERE g.principal_id = ?", pid) Do While Not rs.EOF If n > UBound(paths) Then ReDim Preserve paths(n * 2) ReDim Preserve inh(n * 2) End If paths(n) = "" & rs(0) inh(n) = CLng(rs(1)) n = n + 1 rs.MoveNext Loop rs.Close For i = 0 To n - 1 If Not Api_PathAllows(paths(i), "admin") Then Exit Function If inh(i) = 1 Then If Not Api_PathAllows(paths(i) & "/*", "admin") Then Exit Function End If Next CanManage = True End Function Private Function LoadPrincipalJson(id) Dim rs LoadPrincipalJson = "" If Not Api_IsId(id) Then Exit Function Set rs = DAL().Query("SELECT id, name, type, status, created_at FROM principals WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If Not rs.EOF Then LoadPrincipalJson = PrincipalJson(rs(0), rs(1), rs(2), rs(3), rs(4)) End If rs.Close End Function Private Function PrincipalJson(id, name, pType, status, createdAt) PrincipalJson = "{""id"":" & JsonLite_Quote("" & id) & ",""name"":" & JsonLite_Quote("" & name) & ",""type"":" & JsonLite_Quote("" & pType) & _ ",""status"":" & JsonLite_Quote("" & status) & ",""created_at"":" & JsonLite_Quote("" & createdAt) & "}" End Function Private Function KeyJson(keyId, plain, createdAt) KeyJson = "{""id"":" & JsonLite_Quote(keyId) & ",""key"":" & JsonLite_Quote(plain) & ",""prefix"":" & JsonLite_Quote(Left(plain, 8)) & _ ",""created_at"":" & JsonLite_Quote(createdAt) & ",""note"":""Shown only in this response; store it now.""}" End Function ' JSON array of grants matching a WHERE clause on access_grants g (namespaces n joined). Private Function GrantsJson(where, params) Dim rs, out out = "" Set rs = DAL().Query("SELECT g.id, g.principal_id, g.namespace_id, n.path, g.permissions, g.inherit, g.expires_at, g.created_at " & _ "FROM access_grants g JOIN namespaces n ON n.id = g.namespace_id WHERE n.tenant_id = '" & Api_TenantId & "' AND " & where & _ " ORDER BY n.path, g.created_at", params) Do While Not rs.EOF If Len(out) > 0 Then out = out & "," End If out = out & GrantJson("" & rs(0), "" & rs(1), "" & rs(2), "" & rs(3), "" & rs(4), CLng(rs(5)), rs(6), "" & rs(7)) rs.MoveNext Loop rs.Close GrantsJson = "[" & out & "]" End Function Private Function GrantJson(id, pid, ns, path, perms, inherit, expires, createdAt) Dim a, i, p a = Split(perms, ",") p = "" For i = 0 To UBound(a) If Len(Trim(a(i))) > 0 Then If Len(p) > 0 Then p = p & "," End If p = p & JsonLite_Quote(Trim(a(i))) End If Next GrantJson = "{""id"":" & JsonLite_Quote(id) & ",""principal_id"":" & JsonLite_Quote(pid) & ",""namespace_id"":" & JsonLite_Quote(ns) & _ ",""path"":" & JsonLite_Quote(path) & ",""permissions"":[" & p & "],""inherit"":" & LCase(CStr(inherit = 1)) & _ ",""expires_at"":" & JStr(expires) & ",""created_at"":" & JsonLite_Quote(createdAt) & "}" End Function Private Function NewKeyText() Dim c Set c = Server.CreateObject("G3CRYPTO") NewKeyText = "amk_" & c.RandomHex(32) Set c = Nothing End Function Private Function parentAt(path) Dim rs, pp parentAt = Null pp = Left(path, InStrRev(path, "/") - 1) If Len(pp) = 0 Then Exit Function Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, pp)) If Not rs.EOF Then parentAt = "" & rs(0) End If rs.Close End Function Private Function ValidPath(p) Dim i, c ValidPath = False If Len(p) < 2 Or Len(p) > 400 Then Exit Function If Left(p, 1) <> "/" Or Right(p, 1) = "/" Or InStr(p, "//") > 0 Then Exit Function For i = 1 To Len(p) c = Mid(p, i, 1) If Not ((c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or c = "/" Or c = "-" Or c = "_" Or c = ".") Then Exit Function Next ValidPath = True End Function ' "YYYY-MM-DD HH:MM:SS" Private Function IsTimestamp(s) Dim re Set re = New RegExp re.Pattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$" IsTimestamp = re.Test(s) End Function Private Function JStr(v) If IsNull(v) Then JStr = "null" ElseIf IsEmpty(v) Then JStr = "null" Else JStr = JsonLite_Quote("" & v) End If End Function Private Sub AddErr(msg) If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30) End If m_errs = m_errs & msg End Sub Private Function ReqString(input, name, maxLen) Dim v ReqString = "" If Not input.Exists(name) Then AddErr name & " is required." Exit Function End If v = input.Item(name) If IsNull(v) Then AddErr name & " is required." Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If v = Trim(v) If Len(v) = 0 Then AddErr name & " must not be empty." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If ReqString = v End Function Private Function OptString(input, name, maxLen) Dim v OptString = Null If Not input.Exists(name) Then Exit Function End If v = input.Item(name) If IsNull(v) Then Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If OptString = v End Function Public Sub Invoke(actionName, args) Select Case LCase(actionName) Case "whoami" : WhoAmI Case "namespaces" : Namespaces Case "createnamespace" : CreateNamespace Case "principals" : Principals Case "createprincipal" : CreatePrincipal Case "principal" : Principal args(0) Case "updateprincipal" : UpdatePrincipal args(0) Case "createkey" : CreateKey args(0) Case "revokekey" : RevokeKey args(0) Case "grants" : Grants Case "creategrant" : CreateGrant Case "deletegrant" : DeleteGrant args(0) Case Else Err.Raise 438, "ApiAdminController_Class", "Action '" & actionName & "' not found" End Select End Sub End Class Dim ApiAdminController_Class__Singleton Function ApiAdminController() If IsEmpty(ApiAdminController_Class__Singleton) Then Set ApiAdminController_Class__Singleton = New ApiAdminController_Class End If Set ApiAdminController = ApiAdminController_Class__Singleton End Function ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) Sub ApiAdminController_Invoke(actionName, args) ApiAdminController().Invoke actionName, args End Sub %>