Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

873 wiersze
34KB

  1. <%
  2. ' ApiAdminController: management of namespaces, principals, API keys and grants inside the caller's tenant
  3. ' (spec section 9 "Management", FR-017, section 16 least privilege). Replaces scripts\provision.cmd for day-to-day work;
  4. ' tenants, top-level namespaces and purges stay with the CLI.
  5. '
  6. ' GET /api/v1/me WhoAmI the caller: principal, tenant, grants
  7. ' GET /api/v1/namespaces Namespaces namespaces the caller can read, with its permissions on each
  8. ' POST /api/v1/namespaces CreateNamespace {"path":"/a/b"} (missing parents are created)
  9. ' GET /api/v1/principals Principals principals of the tenant (admins only)
  10. ' POST /api/v1/principals CreatePrincipal {"name","type":"human|agent|service"} -> principal + API key (once)
  11. ' GET /api/v1/principals/:id Principal principal, its keys (when manageable) and grants
  12. ' PATCH /api/v1/principals/:id UpdatePrincipal {"status":"active|disabled"}
  13. ' POST /api/v1/principals/:id/keys CreateKey new API key (shown once)
  14. ' DELETE /api/v1/keys/:id RevokeKey
  15. ' GET /api/v1/grants Grants ?namespace_id=&principal_id= (grants the caller administers)
  16. ' POST /api/v1/grants CreateGrant {"principal_id","namespace_id","permissions":[...],"inherit":true,
  17. ' "expires_at":"YYYY-MM-DD HH:MM:SS"}
  18. ' DELETE /api/v1/grants/:id DeleteGrant
  19. '
  20. ' Authorization (docs/decisions.md ADR-011):
  21. ' - "admin" on a namespace lets the caller create namespaces below it, and grant or revoke access on it. Granting with
  22. ' inherit, or creating a namespace below, needs an inheriting admin grant (one that also covers descendants).
  23. ' - Listing principals and creating one needs admin on at least one namespace.
  24. ' - Managing another principal (keys, status) needs admin on every namespace that principal holds a grant on,
  25. ' inheriting where that grant inherits, so a key can never give the caller more access than it already has.
  26. ' Callers may always manage their own keys. Placeholder principals from imports cannot be managed.
  27. ' - No permission answers 404, as everywhere in the API. Responses that contain a key are sent with no-store.
  28. ' - Idempotency-Key is not supported on these endpoints: a replay would have to store the plain key.
  29. Const ADM_PERMS = ",read,write,delete,verify,admin,"
  30. Class ApiAdminController_Class
  31. Private m_errs
  32. Public Property Get useLayout()
  33. useLayout = False
  34. End Property
  35. Public Property Let useLayout(v)
  36. End Property
  37. Public Property Get Title()
  38. Title = "Admin API"
  39. End Property
  40. '---------------------------------------------------------------
  41. ' GET /api/v1/me
  42. '---------------------------------------------------------------
  43. Public Sub WhoAmI()
  44. Dim rs, name, pType, out
  45. If Not Api_Authenticate() Then Exit Sub
  46. Set rs = DAL().Query("SELECT name, type FROM principals WHERE id = ?", Api_PrincipalId)
  47. name = "" & rs(0)
  48. pType = "" & rs(1)
  49. rs.Close
  50. out = "{""principal_id"":" & JsonLite_Quote(Api_PrincipalId) & ",""tenant_id"":" & JsonLite_Quote(Api_TenantId) & _
  51. ",""name"":" & JsonLite_Quote(name) & ",""type"":" & JsonLite_Quote(pType) & _
  52. ",""grants"":" & GrantsJson("g.principal_id = ?", Api_PrincipalId) & "}"
  53. Api_Send 200, out
  54. End Sub
  55. '---------------------------------------------------------------
  56. ' GET /api/v1/namespaces
  57. '---------------------------------------------------------------
  58. Public Sub Namespaces()
  59. Dim readable, perms(), names, i, rs, out, id, p
  60. If Not Api_Authenticate() Then Exit Sub
  61. readable = Api_AllowedNamespaceIds("read")
  62. If Len(readable) = 0 Then
  63. Api_Send 200, "{""data"":[]}"
  64. Exit Sub
  65. End If
  66. names = Array("read", "write", "delete", "verify", "admin")
  67. ReDim perms(4)
  68. For i = 0 To 4
  69. perms(i) = "," & Api_AllowedNamespaceIds(names(i)) & ","
  70. Next
  71. out = ""
  72. 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)
  73. Do While Not rs.EOF
  74. id = "" & rs(0)
  75. p = ""
  76. For i = 0 To 4
  77. If InStr(perms(i), ",'" & id & "',") > 0 Then
  78. If Len(p) > 0 Then
  79. p = p & ","
  80. End If
  81. p = p & JsonLite_Quote(names(i))
  82. End If
  83. Next
  84. If Len(out) > 0 Then
  85. out = out & ","
  86. End If
  87. out = out & "{""id"":" & JsonLite_Quote(id) & ",""path"":" & JsonLite_Quote("" & rs(1)) & _
  88. ",""parent_id"":" & JStr(rs(2)) & ",""permissions"":[" & p & "],""created_at"":" & JsonLite_Quote("" & rs(3)) & "}"
  89. rs.MoveNext
  90. Loop
  91. rs.Close
  92. Api_Send 200, "{""data"":[" & out & "]}"
  93. End Sub
  94. '---------------------------------------------------------------
  95. ' POST /api/v1/namespaces {"path":"/a/b"}
  96. '---------------------------------------------------------------
  97. Public Sub CreateNamespace()
  98. Dim body, input, path, rs, parts, i, cur, parentId, id, created, k, existing
  99. If Not Api_Authenticate() Then Exit Sub
  100. body = Api_ReadBody()
  101. If IsEmpty(body) Then Exit Sub
  102. Set input = JsonLite_Parse(body)
  103. m_errs = ""
  104. path = LCase(ReqString(input, "path", 400))
  105. If Len(m_errs) = 0 Then
  106. If Not ValidPath(path) Then
  107. AddErr "path must look like /team/project: lower-case a-z, 0-9, '-', '_' and '.', separated by '/'."
  108. End If
  109. End If
  110. If Len(m_errs) > 0 Then
  111. Api_Invalid Split(m_errs, Chr(30))
  112. Exit Sub
  113. End If
  114. ' The new namespace must be covered by an inheriting admin grant of the caller.
  115. If Not Api_PathAllows(path, "admin") Then
  116. Api_Audit "admin.namespace.create", "namespace", "", "denied"
  117. Api_NotFound
  118. Exit Sub
  119. End If
  120. Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, path))
  121. existing = ""
  122. If Not rs.EOF Then
  123. existing = "" & rs(0)
  124. End If
  125. rs.Close
  126. If Len(existing) > 0 Then
  127. Api_Error 409, "namespace_exists", "A namespace with this path already exists (" & existing & ")."
  128. Exit Sub
  129. End If
  130. parts = Split(Mid(path, 2), "/")
  131. cur = ""
  132. parentId = Null
  133. created = 0
  134. On Error Resume Next
  135. DAL().BeginTransaction
  136. For i = 0 To UBound(parts)
  137. cur = cur & "/" & parts(i)
  138. Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, cur))
  139. id = ""
  140. If Err.Number = 0 Then
  141. If Not rs.EOF Then
  142. id = "" & rs(0)
  143. End If
  144. rs.Close
  145. End If
  146. If Err.Number <> 0 Then
  147. Exit For
  148. End If
  149. If Len(id) = 0 Then
  150. id = Api_NewId()
  151. DAL().Execute "INSERT INTO namespaces (id, tenant_id, parent_id, name, path, owner_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", _
  152. Array(id, Api_TenantId, parentId, parts(i), cur, Api_PrincipalId, Api_Now())
  153. If Err.Number <> 0 Then
  154. Exit For
  155. End If
  156. created = created + 1
  157. End If
  158. parentId = id
  159. Next
  160. If Err.Number <> 0 Then
  161. k = Err.Number : Api_NoteDbError
  162. Err.Clear
  163. DAL().RollbackTransaction
  164. Api_DbFailed k, ""
  165. Exit Sub
  166. End If
  167. DAL().CommitTransaction
  168. If Err.Number <> 0 Then
  169. k = Err.Number : Api_NoteDbError
  170. Api_DbFailed k, ""
  171. Exit Sub
  172. End If
  173. On Error GoTo 0
  174. Api_Audit "admin.namespace.create", "namespace", id, "ok"
  175. Response.AddHeader "Location", "/api/v1/namespaces"
  176. Api_Send 201, "{""id"":" & JsonLite_Quote(id) & ",""path"":" & JsonLite_Quote(path) & ",""parent_id"":" & JStr(parentAt(path)) & _
  177. ",""namespaces_created"":" & created & "}"
  178. End Sub
  179. '---------------------------------------------------------------
  180. ' GET /api/v1/principals
  181. '---------------------------------------------------------------
  182. Public Sub Principals()
  183. Dim rs, out
  184. If Not Api_Authenticate() Then Exit Sub
  185. If Len(Api_AllowedNamespaceIds("admin")) = 0 Then
  186. Api_NotFound
  187. Exit Sub
  188. End If
  189. out = ""
  190. Set rs = DAL().Query("SELECT id, name, type, status, created_at FROM principals WHERE tenant_id = ? ORDER BY created_at, id", Api_TenantId)
  191. Do While Not rs.EOF
  192. If Len(out) > 0 Then
  193. out = out & ","
  194. End If
  195. out = out & PrincipalJson(rs(0), rs(1), rs(2), rs(3), rs(4))
  196. rs.MoveNext
  197. Loop
  198. rs.Close
  199. Api_Send 200, "{""data"":[" & out & "]}"
  200. End Sub
  201. '---------------------------------------------------------------
  202. ' POST /api/v1/principals {"name","type"}
  203. '---------------------------------------------------------------
  204. Public Sub CreatePrincipal()
  205. Dim body, input, name, pType, id, keyId, plain, ts, k
  206. If Not Api_Authenticate() Then Exit Sub
  207. If Len(Api_AllowedNamespaceIds("admin")) = 0 Then
  208. Api_Audit "admin.principal.create", "principal", "", "denied"
  209. Api_NotFound
  210. Exit Sub
  211. End If
  212. body = Api_ReadBody()
  213. If IsEmpty(body) Then Exit Sub
  214. Set input = JsonLite_Parse(body)
  215. m_errs = ""
  216. name = ReqString(input, "name", 200)
  217. pType = LCase(ReqString(input, "type", 20))
  218. If Len(m_errs) = 0 Then
  219. If pType <> "human" And pType <> "agent" And pType <> "service" Then
  220. AddErr "type must be human, agent or service."
  221. End If
  222. End If
  223. If Len(m_errs) > 0 Then
  224. Api_Invalid Split(m_errs, Chr(30))
  225. Exit Sub
  226. End If
  227. id = Api_NewId()
  228. ts = Api_Now()
  229. plain = NewKeyText()
  230. keyId = Api_NewId()
  231. On Error Resume Next
  232. DAL().BeginTransaction
  233. DAL().Execute "INSERT INTO principals (id, tenant_id, type, name, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _
  234. Array(id, Api_TenantId, pType, name, ts)
  235. If Err.Number = 0 Then
  236. DAL().Execute "INSERT INTO api_keys (id, principal_id, key_hash, key_prefix, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _
  237. Array(keyId, id, Api_Sha256(plain), Left(plain, 8), ts)
  238. End If
  239. If Err.Number <> 0 Then
  240. k = Err.Number : Api_NoteDbError
  241. Err.Clear
  242. DAL().RollbackTransaction
  243. Api_DbFailed k, ""
  244. Exit Sub
  245. End If
  246. DAL().CommitTransaction
  247. If Err.Number <> 0 Then
  248. k = Err.Number : Api_NoteDbError
  249. Api_DbFailed k, ""
  250. Exit Sub
  251. End If
  252. On Error GoTo 0
  253. Api_Audit "admin.principal.create", "principal", id, "ok"
  254. Response.AddHeader "Location", "/api/v1/principals/" & id
  255. Response.AddHeader "Cache-Control", "no-store"
  256. Api_Send 201, "{""principal"":" & PrincipalJson(id, name, pType, "active", ts) & ",""api_key"":" & KeyJson(keyId, plain, ts) & "}"
  257. End Sub
  258. '---------------------------------------------------------------
  259. ' GET /api/v1/principals/:id
  260. '---------------------------------------------------------------
  261. Public Sub Principal(id)
  262. Dim rs, pj, isSelf, keys, grants, adminIds
  263. If Not Api_Authenticate() Then Exit Sub
  264. isSelf = (id = Api_PrincipalId)
  265. adminIds = Api_AllowedNamespaceIds("admin")
  266. If Not isSelf And Len(adminIds) = 0 Then
  267. Api_NotFound
  268. Exit Sub
  269. End If
  270. pj = LoadPrincipalJson(id)
  271. If Len(pj) = 0 Then
  272. Api_NotFound
  273. Exit Sub
  274. End If
  275. If isSelf Then
  276. grants = GrantsJson("g.principal_id = ?", id)
  277. Else
  278. grants = GrantsJson("g.principal_id = ? AND g.namespace_id IN (" & adminIds & ")", id)
  279. End If
  280. keys = "null"
  281. If CanManage(id) Then
  282. keys = ""
  283. 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)
  284. Do While Not rs.EOF
  285. If Len(keys) > 0 Then
  286. keys = keys & ","
  287. End If
  288. keys = keys & "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""prefix"":" & JsonLite_Quote("" & rs(1)) & _
  289. ",""status"":" & JsonLite_Quote("" & rs(2)) & ",""created_at"":" & JsonLite_Quote("" & rs(3)) & _
  290. ",""expires_at"":" & JStr(rs(4)) & ",""last_used_at"":" & JStr(rs(5)) & "}"
  291. rs.MoveNext
  292. Loop
  293. rs.Close
  294. keys = "[" & keys & "]"
  295. End If
  296. Api_Send 200, Left(pj, Len(pj) - 1) & ",""keys"":" & keys & ",""grants"":" & grants & "}"
  297. End Sub
  298. '---------------------------------------------------------------
  299. ' PATCH /api/v1/principals/:id {"status":"active|disabled"}
  300. '---------------------------------------------------------------
  301. Public Sub UpdatePrincipal(id)
  302. Dim body, input, status, k, pj
  303. If Not Api_Authenticate() Then Exit Sub
  304. If Not CanManage(id) Then
  305. Api_Audit "admin.principal.update", "principal", id, "denied"
  306. Api_NotFound
  307. Exit Sub
  308. End If
  309. body = Api_ReadBody()
  310. If IsEmpty(body) Then Exit Sub
  311. Set input = JsonLite_Parse(body)
  312. m_errs = ""
  313. status = LCase(ReqString(input, "status", 20))
  314. If Len(m_errs) = 0 Then
  315. If status <> "active" And status <> "disabled" Then
  316. AddErr "status must be active or disabled."
  317. End If
  318. End If
  319. If Len(m_errs) > 0 Then
  320. Api_Invalid Split(m_errs, Chr(30))
  321. Exit Sub
  322. End If
  323. If id = Api_PrincipalId Then
  324. Api_Error 422, "cannot_change_self", "A principal cannot change its own status."
  325. Exit Sub
  326. End If
  327. On Error Resume Next
  328. DAL().Execute "UPDATE principals SET status = ? WHERE id = ? AND tenant_id = ?", Array(status, id, Api_TenantId)
  329. If Err.Number <> 0 Then
  330. k = Err.Number : Api_NoteDbError
  331. Api_DbFailed k, ""
  332. Exit Sub
  333. End If
  334. On Error GoTo 0
  335. Api_Audit "admin.principal.update", "principal", id, status
  336. pj = LoadPrincipalJson(id)
  337. Api_Send 200, pj
  338. End Sub
  339. '---------------------------------------------------------------
  340. ' POST /api/v1/principals/:id/keys
  341. '---------------------------------------------------------------
  342. Public Sub CreateKey(id)
  343. Dim rs, status, keyId, plain, ts, k
  344. If Not Api_Authenticate() Then Exit Sub
  345. If Not CanManage(id) Then
  346. Api_Audit "admin.key.create", "principal", id, "denied"
  347. Api_NotFound
  348. Exit Sub
  349. End If
  350. Set rs = DAL().Query("SELECT status FROM principals WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  351. status = "" & rs(0)
  352. rs.Close
  353. If status <> "active" Then
  354. Api_Error 409, "principal_not_active", "Keys can only be created for an active principal; this one is " & status & "."
  355. Exit Sub
  356. End If
  357. plain = NewKeyText()
  358. keyId = Api_NewId()
  359. ts = Api_Now()
  360. On Error Resume Next
  361. DAL().Execute "INSERT INTO api_keys (id, principal_id, key_hash, key_prefix, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _
  362. Array(keyId, id, Api_Sha256(plain), Left(plain, 8), ts)
  363. If Err.Number <> 0 Then
  364. k = Err.Number : Api_NoteDbError
  365. Api_DbFailed k, ""
  366. Exit Sub
  367. End If
  368. On Error GoTo 0
  369. Api_Audit "admin.key.create", "api_key", keyId, "ok"
  370. Response.AddHeader "Cache-Control", "no-store"
  371. Api_Send 201, "{""principal_id"":" & JsonLite_Quote(id) & ",""api_key"":" & KeyJson(keyId, plain, ts) & "}"
  372. End Sub
  373. '---------------------------------------------------------------
  374. ' DELETE /api/v1/keys/:id
  375. '---------------------------------------------------------------
  376. Public Sub RevokeKey(id)
  377. Dim rs, pid, k
  378. If Not Api_Authenticate() Then Exit Sub
  379. pid = ""
  380. If Api_IsId(id) Then
  381. 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))
  382. If Not rs.EOF Then
  383. pid = "" & rs(0)
  384. End If
  385. rs.Close
  386. End If
  387. If Len(pid) = 0 Then
  388. Api_NotFound
  389. Exit Sub
  390. End If
  391. If Not CanManage(pid) Then
  392. Api_Audit "admin.key.revoke", "api_key", id, "denied"
  393. Api_NotFound
  394. Exit Sub
  395. End If
  396. On Error Resume Next
  397. DAL().Execute "UPDATE api_keys SET status = 'revoked' WHERE id = ?", id
  398. If Err.Number <> 0 Then
  399. k = Err.Number : Api_NoteDbError
  400. Api_DbFailed k, ""
  401. Exit Sub
  402. End If
  403. On Error GoTo 0
  404. Api_Audit "admin.key.revoke", "api_key", id, "ok"
  405. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""principal_id"":" & JsonLite_Quote(pid) & ",""status"":""revoked""}"
  406. End Sub
  407. '---------------------------------------------------------------
  408. ' GET /api/v1/grants?namespace_id=&principal_id=
  409. '---------------------------------------------------------------
  410. Public Sub Grants()
  411. Dim adminIds, ns, pid, where, params
  412. If Not Api_Authenticate() Then Exit Sub
  413. adminIds = Api_AllowedNamespaceIds("admin")
  414. If Len(adminIds) = 0 Then
  415. Api_NotFound
  416. Exit Sub
  417. End If
  418. ns = Trim("" & Request.QueryString("namespace_id"))
  419. pid = Trim("" & Request.QueryString("principal_id"))
  420. m_errs = ""
  421. If Len(ns) > 0 Then
  422. If Not Api_IsId(ns) Then
  423. AddErr "namespace_id must be a valid id."
  424. End If
  425. End If
  426. If Len(pid) > 0 Then
  427. If Not Api_IsId(pid) Then
  428. AddErr "principal_id must be a valid id."
  429. End If
  430. End If
  431. If Len(m_errs) > 0 Then
  432. Api_Invalid Split(m_errs, Chr(30))
  433. Exit Sub
  434. End If
  435. where = "g.namespace_id IN (" & adminIds & ")"
  436. If Len(ns) > 0 And Len(pid) > 0 Then
  437. where = where & " AND g.namespace_id = ? AND g.principal_id = ?"
  438. params = Array(ns, pid)
  439. ElseIf Len(ns) > 0 Then
  440. where = where & " AND g.namespace_id = ?"
  441. params = ns
  442. ElseIf Len(pid) > 0 Then
  443. where = where & " AND g.principal_id = ?"
  444. params = pid
  445. Else
  446. params = Empty
  447. End If
  448. Api_Send 200, "{""data"":" & GrantsJson(where, params) & "}"
  449. End Sub
  450. '---------------------------------------------------------------
  451. ' POST /api/v1/grants
  452. '---------------------------------------------------------------
  453. Public Sub CreateGrant()
  454. Dim body, input, pid, ns, permsArr, perms, inherit, expires, i, p, path, rs, pStatus, existing, id, ts, k
  455. If Not Api_Authenticate() Then Exit Sub
  456. body = Api_ReadBody()
  457. If IsEmpty(body) Then Exit Sub
  458. Set input = JsonLite_Parse(body)
  459. m_errs = ""
  460. pid = ReqString(input, "principal_id", 64)
  461. ns = ReqString(input, "namespace_id", 64)
  462. If Len(pid) > 0 Then
  463. If Not Api_IsId(pid) Then
  464. AddErr "principal_id must be a valid id."
  465. End If
  466. End If
  467. If Len(ns) > 0 Then
  468. If Not Api_IsId(ns) Then
  469. AddErr "namespace_id must be a valid id."
  470. End If
  471. End If
  472. perms = ""
  473. If input.HasRaw("permissions") Then
  474. permsArr = JsonLite_ParseStringArray(input.Raw("permissions"))
  475. Else
  476. permsArr = Null
  477. End If
  478. If IsNull(permsArr) Then
  479. AddErr "permissions must be a non-empty array of read, write, delete, verify, admin."
  480. Else
  481. For i = 0 To UBound(permsArr)
  482. p = LCase(Trim(permsArr(i)))
  483. If InStr(ADM_PERMS, "," & p & ",") = 0 Or Len(p) = 0 Then
  484. AddErr "unknown permission: " & permsArr(i) & " (allowed: read, write, delete, verify, admin)."
  485. Exit For
  486. End If
  487. If InStr("," & perms & ",", "," & p & ",") = 0 Then
  488. If Len(perms) > 0 Then
  489. perms = perms & ","
  490. End If
  491. perms = perms & p
  492. End If
  493. Next
  494. If Len(perms) = 0 And Len(m_errs) = 0 Then
  495. AddErr "permissions must not be empty."
  496. End If
  497. End If
  498. inherit = 1
  499. If input.Exists("inherit") Then
  500. If VarType(input.Item("inherit")) = vbBoolean Then
  501. If Not input.Item("inherit") Then
  502. inherit = 0
  503. End If
  504. Else
  505. AddErr "inherit must be true or false."
  506. End If
  507. End If
  508. expires = OptString(input, "expires_at", 19)
  509. If Not IsNull(expires) Then
  510. If Not IsTimestamp(expires) Then
  511. AddErr "expires_at must be a UTC time like 2027-01-31 18:00:00."
  512. ElseIf expires <= Api_Now() Then
  513. AddErr "expires_at must be in the future."
  514. End If
  515. End If
  516. If Len(m_errs) > 0 Then
  517. Api_Invalid Split(m_errs, Chr(30))
  518. Exit Sub
  519. End If
  520. ' Admin on the namespace; an inheriting grant also needs inheriting admin (it reaches every descendant).
  521. path = Api_NamespacePath(ns)
  522. If IsNull(path) Then
  523. Api_NotFound
  524. Exit Sub
  525. End If
  526. If Not Api_PathAllows(path, "admin") Then
  527. Api_Audit "admin.grant.create", "namespace", ns, "denied"
  528. Api_NotFound
  529. Exit Sub
  530. End If
  531. If inherit = 1 Then
  532. If Not Api_PathAllows(path & "/*", "admin") Then
  533. Api_Error 422, "inherit_not_allowed", "Your admin access on this namespace does not extend to its descendants; grant with inherit false."
  534. Exit Sub
  535. End If
  536. End If
  537. Set rs = DAL().Query("SELECT status FROM principals WHERE id = ? AND tenant_id = ?", Array(pid, Api_TenantId))
  538. pStatus = ""
  539. If Not rs.EOF Then
  540. pStatus = "" & rs(0)
  541. End If
  542. rs.Close
  543. If pStatus <> "active" Then
  544. Api_Error 422, "principal_not_found", "principal_id must be an active principal of your tenant."
  545. Exit Sub
  546. End If
  547. Set rs = DAL().Query("SELECT id FROM access_grants WHERE principal_id = ? AND namespace_id = ?", Array(pid, ns))
  548. existing = ""
  549. If Not rs.EOF Then
  550. existing = "" & rs(0)
  551. End If
  552. rs.Close
  553. If Len(existing) > 0 Then
  554. Api_Error 409, "grant_exists", "This principal already has a grant on this namespace (" & existing & "); delete it first to change it."
  555. Exit Sub
  556. End If
  557. id = Api_NewId()
  558. ts = Api_Now()
  559. On Error Resume Next
  560. DAL().Execute "INSERT INTO access_grants (id, principal_id, namespace_id, permissions, inherit, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)", _
  561. Array(id, pid, ns, perms, inherit, ts, expires)
  562. If Err.Number <> 0 Then
  563. k = Err.Number : Api_NoteDbError
  564. Api_DbFailed k, ""
  565. Exit Sub
  566. End If
  567. On Error GoTo 0
  568. Api_Audit "admin.grant.create", "grant", id, perms
  569. Response.AddHeader "Location", "/api/v1/grants?principal_id=" & pid
  570. Api_Send 201, GrantJson(id, pid, ns, path, perms, inherit, expires, ts)
  571. End Sub
  572. '---------------------------------------------------------------
  573. ' DELETE /api/v1/grants/:id
  574. '---------------------------------------------------------------
  575. Public Sub DeleteGrant(id)
  576. Dim rs, pid, path, k
  577. If Not Api_Authenticate() Then Exit Sub
  578. pid = ""
  579. If Api_IsId(id) Then
  580. 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))
  581. If Not rs.EOF Then
  582. pid = "" & rs(0)
  583. path = "" & rs(1)
  584. End If
  585. rs.Close
  586. End If
  587. If Len(pid) = 0 Then
  588. Api_NotFound
  589. Exit Sub
  590. End If
  591. If Not Api_PathAllows(path, "admin") Then
  592. Api_Audit "admin.grant.delete", "grant", id, "denied"
  593. Api_NotFound
  594. Exit Sub
  595. End If
  596. If pid = Api_PrincipalId Then
  597. Api_Error 422, "cannot_change_self", "A principal cannot remove its own grants; ask another admin."
  598. Exit Sub
  599. End If
  600. On Error Resume Next
  601. DAL().Execute "DELETE FROM access_grants WHERE id = ?", id
  602. If Err.Number <> 0 Then
  603. k = Err.Number : Api_NoteDbError
  604. Api_DbFailed k, ""
  605. Exit Sub
  606. End If
  607. On Error GoTo 0
  608. Api_Audit "admin.grant.delete", "grant", id, "ok"
  609. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""deleted"":true}"
  610. End Sub
  611. '---------------------------------------------------------------
  612. ' Helpers
  613. '---------------------------------------------------------------
  614. ' True when the caller may manage principal pid (keys, status): itself, or a principal of the tenant whose every
  615. ' grant lies where the caller holds admin (inheriting admin where the grant inherits). Never for placeholders.
  616. Private Function CanManage(pid)
  617. Dim rs, status, paths(), inh(), n, i
  618. CanManage = False
  619. If Not Api_IsId(pid) Then Exit Function
  620. Set rs = DAL().Query("SELECT status FROM principals WHERE id = ? AND tenant_id = ?", Array(pid, Api_TenantId))
  621. status = ""
  622. If Not rs.EOF Then
  623. status = "" & rs(0)
  624. End If
  625. rs.Close
  626. If Len(status) = 0 Or status = "imported" Then Exit Function
  627. If pid = Api_PrincipalId Then
  628. CanManage = True
  629. Exit Function
  630. End If
  631. If Len(Api_AllowedNamespaceIds("admin")) = 0 Then Exit Function
  632. n = 0
  633. ReDim paths(7)
  634. ReDim inh(7)
  635. 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)
  636. Do While Not rs.EOF
  637. If n > UBound(paths) Then
  638. ReDim Preserve paths(n * 2)
  639. ReDim Preserve inh(n * 2)
  640. End If
  641. paths(n) = "" & rs(0)
  642. inh(n) = CLng(rs(1))
  643. n = n + 1
  644. rs.MoveNext
  645. Loop
  646. rs.Close
  647. For i = 0 To n - 1
  648. If Not Api_PathAllows(paths(i), "admin") Then Exit Function
  649. If inh(i) = 1 Then
  650. If Not Api_PathAllows(paths(i) & "/*", "admin") Then Exit Function
  651. End If
  652. Next
  653. CanManage = True
  654. End Function
  655. Private Function LoadPrincipalJson(id)
  656. Dim rs
  657. LoadPrincipalJson = ""
  658. If Not Api_IsId(id) Then Exit Function
  659. Set rs = DAL().Query("SELECT id, name, type, status, created_at FROM principals WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  660. If Not rs.EOF Then
  661. LoadPrincipalJson = PrincipalJson(rs(0), rs(1), rs(2), rs(3), rs(4))
  662. End If
  663. rs.Close
  664. End Function
  665. Private Function PrincipalJson(id, name, pType, status, createdAt)
  666. PrincipalJson = "{""id"":" & JsonLite_Quote("" & id) & ",""name"":" & JsonLite_Quote("" & name) & ",""type"":" & JsonLite_Quote("" & pType) & _
  667. ",""status"":" & JsonLite_Quote("" & status) & ",""created_at"":" & JsonLite_Quote("" & createdAt) & "}"
  668. End Function
  669. Private Function KeyJson(keyId, plain, createdAt)
  670. KeyJson = "{""id"":" & JsonLite_Quote(keyId) & ",""key"":" & JsonLite_Quote(plain) & ",""prefix"":" & JsonLite_Quote(Left(plain, 8)) & _
  671. ",""created_at"":" & JsonLite_Quote(createdAt) & ",""note"":""Shown only in this response; store it now.""}"
  672. End Function
  673. ' JSON array of grants matching a WHERE clause on access_grants g (namespaces n joined).
  674. Private Function GrantsJson(where, params)
  675. Dim rs, out
  676. out = ""
  677. 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 " & _
  678. "FROM access_grants g JOIN namespaces n ON n.id = g.namespace_id WHERE n.tenant_id = '" & Api_TenantId & "' AND " & where & _
  679. " ORDER BY n.path, g.created_at", params)
  680. Do While Not rs.EOF
  681. If Len(out) > 0 Then
  682. out = out & ","
  683. End If
  684. out = out & GrantJson("" & rs(0), "" & rs(1), "" & rs(2), "" & rs(3), "" & rs(4), CLng(rs(5)), rs(6), "" & rs(7))
  685. rs.MoveNext
  686. Loop
  687. rs.Close
  688. GrantsJson = "[" & out & "]"
  689. End Function
  690. Private Function GrantJson(id, pid, ns, path, perms, inherit, expires, createdAt)
  691. Dim a, i, p
  692. a = Split(perms, ",")
  693. p = ""
  694. For i = 0 To UBound(a)
  695. If Len(Trim(a(i))) > 0 Then
  696. If Len(p) > 0 Then
  697. p = p & ","
  698. End If
  699. p = p & JsonLite_Quote(Trim(a(i)))
  700. End If
  701. Next
  702. GrantJson = "{""id"":" & JsonLite_Quote(id) & ",""principal_id"":" & JsonLite_Quote(pid) & ",""namespace_id"":" & JsonLite_Quote(ns) & _
  703. ",""path"":" & JsonLite_Quote(path) & ",""permissions"":[" & p & "],""inherit"":" & LCase(CStr(inherit = 1)) & _
  704. ",""expires_at"":" & JStr(expires) & ",""created_at"":" & JsonLite_Quote(createdAt) & "}"
  705. End Function
  706. Private Function NewKeyText()
  707. Dim c
  708. Set c = Server.CreateObject("G3CRYPTO")
  709. NewKeyText = "amk_" & c.RandomHex(32)
  710. Set c = Nothing
  711. End Function
  712. Private Function parentAt(path)
  713. Dim rs, pp
  714. parentAt = Null
  715. pp = Left(path, InStrRev(path, "/") - 1)
  716. If Len(pp) = 0 Then Exit Function
  717. Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, pp))
  718. If Not rs.EOF Then
  719. parentAt = "" & rs(0)
  720. End If
  721. rs.Close
  722. End Function
  723. Private Function ValidPath(p)
  724. Dim i, c
  725. ValidPath = False
  726. If Len(p) < 2 Or Len(p) > 400 Then Exit Function
  727. If Left(p, 1) <> "/" Or Right(p, 1) = "/" Or InStr(p, "//") > 0 Then Exit Function
  728. For i = 1 To Len(p)
  729. c = Mid(p, i, 1)
  730. If Not ((c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or c = "/" Or c = "-" Or c = "_" Or c = ".") Then Exit Function
  731. Next
  732. ValidPath = True
  733. End Function
  734. ' "YYYY-MM-DD HH:MM:SS"
  735. Private Function IsTimestamp(s)
  736. Dim re
  737. Set re = New RegExp
  738. re.Pattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$"
  739. IsTimestamp = re.Test(s)
  740. End Function
  741. Private Function JStr(v)
  742. If IsNull(v) Then
  743. JStr = "null"
  744. ElseIf IsEmpty(v) Then
  745. JStr = "null"
  746. Else
  747. JStr = JsonLite_Quote("" & v)
  748. End If
  749. End Function
  750. Private Sub AddErr(msg)
  751. If Len(m_errs) > 0 Then
  752. m_errs = m_errs & Chr(30)
  753. End If
  754. m_errs = m_errs & msg
  755. End Sub
  756. Private Function ReqString(input, name, maxLen)
  757. Dim v
  758. ReqString = ""
  759. If Not input.Exists(name) Then
  760. AddErr name & " is required."
  761. Exit Function
  762. End If
  763. v = input.Item(name)
  764. If IsNull(v) Then
  765. AddErr name & " is required."
  766. Exit Function
  767. End If
  768. If VarType(v) <> vbString Then
  769. AddErr name & " must be a string."
  770. Exit Function
  771. End If
  772. v = Trim(v)
  773. If Len(v) = 0 Then
  774. AddErr name & " must not be empty."
  775. Exit Function
  776. End If
  777. If Len(v) > maxLen Then
  778. AddErr name & " must be at most " & maxLen & " characters."
  779. Exit Function
  780. End If
  781. ReqString = v
  782. End Function
  783. Private Function OptString(input, name, maxLen)
  784. Dim v
  785. OptString = Null
  786. If Not input.Exists(name) Then
  787. Exit Function
  788. End If
  789. v = input.Item(name)
  790. If IsNull(v) Then
  791. Exit Function
  792. End If
  793. If VarType(v) <> vbString Then
  794. AddErr name & " must be a string."
  795. Exit Function
  796. End If
  797. If Len(v) > maxLen Then
  798. AddErr name & " must be at most " & maxLen & " characters."
  799. Exit Function
  800. End If
  801. OptString = v
  802. End Function
  803. Public Sub Invoke(actionName, args)
  804. Select Case LCase(actionName)
  805. Case "whoami" : WhoAmI
  806. Case "namespaces" : Namespaces
  807. Case "createnamespace" : CreateNamespace
  808. Case "principals" : Principals
  809. Case "createprincipal" : CreatePrincipal
  810. Case "principal" : Principal args(0)
  811. Case "updateprincipal" : UpdatePrincipal args(0)
  812. Case "createkey" : CreateKey args(0)
  813. Case "revokekey" : RevokeKey args(0)
  814. Case "grants" : Grants
  815. Case "creategrant" : CreateGrant
  816. Case "deletegrant" : DeleteGrant args(0)
  817. Case Else
  818. Err.Raise 438, "ApiAdminController_Class", "Action '" & actionName & "' not found"
  819. End Select
  820. End Sub
  821. End Class
  822. Dim ApiAdminController_Class__Singleton
  823. Function ApiAdminController()
  824. If IsEmpty(ApiAdminController_Class__Singleton) Then
  825. Set ApiAdminController_Class__Singleton = New ApiAdminController_Class
  826. End If
  827. Set ApiAdminController = ApiAdminController_Class__Singleton
  828. End Function
  829. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  830. Sub ApiAdminController_Invoke(actionName, args)
  831. ApiAdminController().Invoke actionName, args
  832. End Sub
  833. %>

Powered by TurnKey Linux.