gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit1d69bf7d1d69bf7dTickets conductor: park until Hermes pushmre1d69bf7d/lib/api-helpers.hl

14.8 KB

  1. // lib/api-helpers.hl — the plumbing of the function routes (lib/api.hl): query strings, bodies, answers, who is
  2. // calling (token or app key), the Markdown Accept check, the small HTML page. Statics only; no topic logic here.
  3. import { Response } from 'hl:http1'
  4. import { jsonErrorAt } from './jsoncheck.hl'
  5. import { userOfBearer, ensureUser, userRecord, setUserName } from './users.hl'
  6. import { check } from './ident-access.hl'
  7. import { connectionOfKey, personOf } from './connections.hl'
  8. import { states, stateOf } from './tickets-helpers.hl'
  9. import { partsOf, isUtf8 } from './multipart.hl'
  10. import { maxCommentBytes, maxFiles } from './attachments.hl'
  11. // SECURITY HEADERS of every answer these function routes make (mission ST; pages are hl:web's): nothing is sniffed into a type it
  12. // is not, nothing is framed, no Referer leaves a page that was opened from an answer, and a CSP that allows nothing (an answer is data)
  13. static secHeaders = { 'X-Content-Type-Options' = 'nosniff' 'X-Frame-Options' = 'DENY' 'Referrer-Policy' = 'no-referrer' 'Content-Security-Policy' = "default-src 'none'; frame-ancestors 'none'" }
  14. // the same, plus `own` (the answer's own headers win)
  15. static hdr = (own) => {
  16. out = {}
  17. for (k of secHeaders.keys()) { out[k] = secHeaders[k] }
  18. for (k of own.keys()) { out[k] = own[k] }
  19. return out
  20. }
  21. static jsonHeaders = hdr({ 'Content-Type' = 'application/json; charset=utf-8' })
  22. // the largest JSON body the API reads (mission ST): jsoncheck.hl walks a body character by character IN HYBRIEL, so a multi-megabyte
  23. // body from any token holder held the single-threaded server for minutes. Texts are far smaller (a comment's files travel as multipart).
  24. static maxJsonBytes = 1048576
  25. static reply = (status, value) => {
  26. return new Response(JSON.stringify(value), { status = status headers = jsonHeaders })
  27. }
  28. static fail = (status, message) => { return reply(status, { error = message }) }
  29. // `?a=1&b=x` of a request path → { a = '1', b = 'x' } ('+' is a space; hl:http1
  30. // has already percent-decoded the path)
  31. static queryOf = (path) => {
  32. out = {}
  33. q = path.indexOf('?')
  34. if (q < 0) { return out }
  35. for (pair of path.slice(q + 1).split('&')) {
  36. if (pair != '') {
  37. eq = pair.indexOf('=')
  38. if (eq < 0) { out[pair] = '' } else { out[pair.slice(0, eq)] = pair.slice(eq + 1).replaceAll('+', ' ') }
  39. }
  40. }
  41. return out
  42. }
  43. // the request body as JSON, or null when it is not
  44. static bodyOf = (req) => {
  45. if (req.body == null || req.body == '') { return null }
  46. return JSON.parse(req.body)
  47. }
  48. // THE API IS STRICT (ticket #10): a malformed report must not be filed half-read. A body
  49. // is a JSON object whose keys are all in `required` or `optional`, every value is a
  50. // String, and every required one is non-empty after trimming. Answers null (fine) or
  51. // { error, field } — the first offence, naming the field.
  52. // (a list has no concat() in this build — NotCallable, hybriel #6's family)
  53. static allowedOf = (required, optional) => {
  54. all = []
  55. for (k of required) { all.push(k) }
  56. for (k of optional) { all.push(k) }
  57. return all.join(', ')
  58. }
  59. static bodyError = (b, required, optional) => {
  60. if (b == null || hlTypeName(b) != 'Hybrid' || b.length != null) {
  61. return { error = 'the body must be a JSON object' field = '' }
  62. }
  63. for (k of b.keys()) {
  64. // ticket #7: the author is the token's user — a body that still names one is refused
  65. // (not silently ignored), so a client learns that its field does nothing
  66. if (k == 'author') {
  67. return { error = "no field 'author' any more: the author is the user of your API token" field = 'author' }
  68. }
  69. if (!required.includes(k) && !optional.includes(k)) {
  70. return { error = "unknown field '" + k + "' (allowed: " + allowedOf(required, optional) + ')' field = k }
  71. }
  72. if (hlTypeName(b[k]) != 'String') {
  73. return { error = "field '" + k + "' must be a string, not " + hlTypeName(b[k]) field = k }
  74. }
  75. }
  76. for (k of required) {
  77. if (b[k] == null) { return { error = "field '" + k + "' is required" field = k } }
  78. if (b[k].trim() == '') { return { error = "field '" + k + "' must not be empty" field = k } }
  79. }
  80. return null
  81. }
  82. static refuse = (e) => { return reply(e.tooBig == true ? 413 : 400, e) }
  83. // ticket #7: an API write without a valid token (missing, malformed, unknown, revoked) → 401
  84. static unauthorized = () => { return unauthorizedFor('an API write') }
  85. // ticket #26: the event stream says what it is that needs the token
  86. static unauthorizedFor = (what) => {
  87. return new Response(JSON.stringify({ error = what + ' needs Authorization: Bearer <token> — log in with ident and create a token on /you' }), { status = 401 headers = hdr({ 'Content-Type' = 'application/json; charset=utf-8' 'WWW-Authenticate' = 'Bearer' }) })
  88. }
  89. // a POST body, checked: { body } or { bad } (bad = the 400 answer's value).
  90. // Invalid JSON is refused by jsoncheck.hl BEFORE JSON.parse ever sees it (ticket #15,
  91. // workaround for hybriel #12: an uncaught JSON.parse would answer 500 with source paths).
  92. static readBody = (req, required, optional) => {
  93. if (req.body != null && req.body != '' && req.body.length > maxJsonBytes) { return { bad = { error = 'the body is ' + req.body.length + ' characters: a JSON body may have at most ' + maxJsonBytes field = '' tooBig = true } } }
  94. if (req.body != null && req.body != '') {
  95. at = jsonErrorAt(req.body)
  96. if (at >= 0) { return { bad = { error = 'invalid JSON at character ' + at } } }
  97. }
  98. b = bodyOf(req)
  99. return { body = b bad = bodyError(b, required, optional) }
  100. }
  101. // a refusal of a topic function: 403 when the role is missing, else 400
  102. static denied = (r) => {
  103. if (r.forbidden == true) { return reply(403, { error = r.error field = r.field }) }
  104. return refuse({ error = r.error field = r.field })
  105. }
  106. // ---- who is calling --------------------------------------------------------------------------------
  107. // WRITES NEED A TOKEN (ticket #7): `Authorization: Bearer <token>` (users.hl; a logged-in user
  108. // makes tokens on /you). No / bad / revoked token → 401, checked BEFORE the body.
  109. // An IDENT ACCESS KEY (ident#27): `Authorization: Bearer idt_…` is asked of ident on every call (lib/ident-access.hl). The identity's
  110. // tickets user is the one its login made (users.hl ensureUser; made now when the identity never logged in here — a new user gets
  111. // the identity's name from ident as its display name, because nobody can type one for a key). `read` keys may only GET / HEAD (403
  112. // otherwise); a bad key is 401, ident not answering 503 (nothing is written). Answers null (not an idt_ header: the old ways go on),
  113. // { user } or { response } (the refusal).
  114. static identActorOf = (req) => {
  115. h = req.headers['authorization']
  116. if (h == null || hlTypeName(h) != 'String') { return null }
  117. t = h.trim()
  118. if (t.length < 12 || t.slice(0, 7).toLowerCase() != 'bearer ' || !t.slice(7).trim().startsWith('idt_')) { return null }
  119. who = check(req)
  120. if (!who.ok) {
  121. hs = who.status == 401 ? { 'Content-Type' = 'application/json; charset=utf-8' 'WWW-Authenticate' = 'Bearer' } : { 'Content-Type' = 'application/json; charset=utf-8' }
  122. return { response = new Response(JSON.stringify({ error = who.error }), { status = who.status headers = hdr(hs) }) }
  123. }
  124. if (who.access != 'write' && req.method != 'GET' && req.method != 'HEAD') {
  125. return { response = reply(403, { error = 'this access key is read-only' field = '' }) }
  126. }
  127. let u = ensureUser(who.identity)
  128. if (u == null) { return { response = reply(500, { error = 'could not store the user' field = '' }) } }
  129. if (u.name == '' && who.name != null && who.name != '') {
  130. setUserName(u.id, who.name)
  131. u = userRecord(u.id)
  132. }
  133. return { user = u }
  134. }
  135. // the answer for a call that has no good identity: the idt_ refusal, else the plain 401
  136. static authDenied = (a, what) => {
  137. if (a != null && a.response != null) { return a.response }
  138. return unauthorizedFor(what)
  139. }
  140. // the token's user of an API write, or null (→ 401); an idt_ key's refusal is { response }
  141. static apiUser = (req) => {
  142. ia = identActorOf(req)
  143. if (ia != null) { return ia.user != null ? ia.user : ia }
  144. return userOfBearer(req.headers['authorization'])
  145. }
  146. // WHO WRITES, for the endpoints an app's KEY may also use (ticket #21: create a ticket, comment, change the state):
  147. // { user } for a user's token, { conn } for a project key (connections.hl), { response } for a refused idt_ key, null = 401
  148. static apiAuth = (req) => {
  149. ia = identActorOf(req)
  150. if (ia != null) { return ia }
  151. h = req.headers['authorization']
  152. u = userOfBearer(h)
  153. if (u != null) { return { user = u } }
  154. c = connectionOfKey(h)
  155. return c != null ? { conn = c } : null
  156. }
  157. // the acting user inside project `projectId`: { user } or { response }. A key reaches ITS project only and names the
  158. // person by `X-Tickets-Identity`; the project's roles then decide as for any user.
  159. static actorIn = (auth, req, projectId) => {
  160. if (auth.user != null) { return { user = auth.user } }
  161. if (projectId == null || auth.conn.project != projectId) { return { response = reply(403, { error = 'this key belongs to another project' field = '' }) } }
  162. a = personOf(req.headers['x-tickets-identity'])
  163. if (a.error != null) { return { response = reply(403, { error = a.error field = '' }) } }
  164. return { user = a.user }
  165. }
  166. // ---- list filters ----------------------------------------------------------------------------------
  167. static stateFilter = (q) => {
  168. if (q.state == null || q.state == '') { return { state = null } }
  169. st = stateOf(q.state)
  170. if (st == null) { return { bad = fail(400, 'unknown state — one of: ' + states.join(', ')) } }
  171. return { state = st }
  172. }
  173. // the filters of a list, for the Markdown heading ('' = none)
  174. static filterLabel = (project, state) => {
  175. parts = []
  176. if (project != null) { parts.push('project ' + project) }
  177. if (state != null) { parts.push('state ' + state) }
  178. return parts.join(', ')
  179. }
  180. // ---- THE MARKDOWN READ VIEW's request side (ticket #6; the documents: lib/mdview.hl) -----------------
  181. // does the request ask for Markdown? `Accept` names text/markdown with q > 0 and prefers it to
  182. // application/json (a higher q, or the same q and listed first). No Accept / */* → JSON.
  183. static qOf = (part) => {
  184. let q = 1
  185. for (p of part.split(';')) {
  186. kv = p.trim()
  187. if (kv.startsWith('q=')) { q = toNumber(kv.slice(2)) }
  188. }
  189. return q == null ? 0 : q
  190. }
  191. static wantsMarkdown = (req) => {
  192. h = req.headers['accept']
  193. if (h == null || hlTypeName(h) != 'String') { return false }
  194. let md = -1
  195. let js = -1
  196. let mdAt = -1
  197. let jsAt = -1
  198. let i = 0
  199. for (part of h.toLowerCase().split(',')) {
  200. type = part.split(';')[0].trim()
  201. if (type == 'text/markdown' && mdAt < 0) {
  202. md = qOf(part)
  203. mdAt = i
  204. }
  205. if (type == 'application/json' && jsAt < 0) {
  206. js = qOf(part)
  207. jsAt = i
  208. }
  209. i = i + 1
  210. }
  211. if (md <= 0) { return false }
  212. if (js < 0) { return true }
  213. return md > js || (md == js && mdAt < jsAt)
  214. }
  215. static markdownReply = (text) => {
  216. return new Response(text, { status = 200 headers = hdr({ 'Content-Type' = 'text/markdown; charset=utf-8' 'Vary' = 'Accept' }) })
  217. }
  218. // ---- A COMMENT WITH FILES (tickets#27, mission 017): POST …/comments as multipart/form-data -----------------------------
  219. // fields: `text` (optional when there are files) and any number of file parts named `file` (or `files`, `file[]`, `files[]`), e.g.
  220. // `curl -H "Authorization: Bearer $T" -F 'text=390 px' -F [email protected] …/comments`. Answers { text, files ([{ name, type, bytes }]) }
  221. // or { bad } (the answer: 413 for a body over the limit, else 400 naming the field). The limits per file / per comment and the
  222. // content check are lib/attachments.hl's (addComment).
  223. static fileFields = ['file', 'files', 'file[]', 'files[]']
  224. static commentFormOf = (req) => {
  225. if (req.bytes != null && hlTypeName(req.bytes) == 'Bytes' && req.bytes.length > maxCommentBytes + 1048576) {
  226. return { bad = reply(413, { error = 'the body is ' + req.bytes.length + ' bytes: the files of one comment may have at most 25 MB together' field = 'files' }) }
  227. }
  228. p = partsOf(req)
  229. if (p.error != null) { return { bad = refuse({ error = p.error field = '' }) } }
  230. let text = null
  231. files = []
  232. for (part of p.parts) {
  233. if (part.name == 'author') { return { bad = refuse({ error = "no field 'author' any more: the author is the user of your API token" field = 'author' }) } }
  234. if (fileFields.includes(part.name) && part.filename != null) {
  235. files.push({ name = part.filename type = part.type bytes = part.bytes })
  236. } else if (part.name == 'text' && part.filename == null) {
  237. if (text != null) { return { bad = refuse({ error = "field 'text' is given twice" field = 'text' }) } }
  238. if (!isUtf8(part.bytes)) { return { bad = refuse({ error = "field 'text' is not UTF-8" field = 'text' }) } }
  239. text = part.bytes.toString()
  240. } else {
  241. return { bad = refuse({ error = "unknown field '" + part.name + "' (allowed: text, and files as file=@path)" field = part.name }) }
  242. }
  243. }
  244. if (files.length > maxFiles) { return { bad = refuse({ error = 'at most ' + maxFiles + ' files per comment (' + files.length + ' given)' field = 'files' }) } }
  245. return { text = text != null ? text : '' files = files }
  246. }
  247. // ---- answers that are not JSON ---------------------------------------------------------------------
  248. // an attachment's bytes (tickets#27): a picture inline, any other file as a download; its type is the one its CONTENT showed
  249. // (lib/attachments.hl); nosniff + a sandbox policy, so nothing in it can run; private to the browser that fetched it
  250. static fileReply = (f) => {
  251. disp = (f.image ? 'inline' : 'attachment') + '; filename=' + DQ + asciiName(f.name) + DQ + "; filename*=UTF-8''" + encodeURIComponent(f.name)
  252. return new Response(f.bytes, { status = 200 headers = { 'Content-Type' = f.type 'Content-Disposition' = disp 'X-Content-Type-Options' = 'nosniff' 'Content-Security-Policy' = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox" 'Cache-Control' = 'private, max-age=86400' 'Cross-Origin-Resource-Policy' = 'same-origin' } })
  253. }
  254. static DQ = '"'
  255. // a name for the plain `filename=` (ASCII only; the exact one rides in filename*)
  256. static asciiName = (name) => {
  257. let out = ''
  258. let i = 0
  259. while (i < name.length) {
  260. c = name.slice(i, i + 1)
  261. k = c.charCodeAt(0)
  262. out = out + (k >= 32 && k < 127 && c != '"' ? c : '_')
  263. i = i + 1
  264. }
  265. return out
  266. }
  267. // a refusal of /connect or /login/callback: the browser goes to the app's error page (components/problem.hl, tickets#42), which names the reason
  268. // by `code` (lib/problems.hl); `area` is 'login' or 'connect'
  269. static problemRedirect = (area, code) => {
  270. to = '/' + area + '/failed/' + code
  271. return new Response('continue at ' + to, { status = 302 headers = hdr({ 'Location' = to 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' }) })
  272. }
  273. // a page that moved for good (301) / a page that names nothing (404), as plain text
  274. static moved = (to) => {
  275. return new Response('moved to ' + to, { status = 301 headers = hdr({ 'Location' = to 'Content-Type' = 'text/plain; charset=utf-8' }) })
  276. }
  277. static missing = (message) => { return new Response(message, { status = 404 headers = hdr({ 'Content-Type' = 'text/plain; charset=utf-8' }) }) }

Branches

Latest commits

  • 1d69bf7dTickets conductor: park until Hermes pushmre
  • 80d8cfd1Tickets conductor: #51 livemre
  • 61641dd9Complete subscriptions deployment evidencemre
  • c980856cRecord successful subscriptions deployment and live checksmre
  • 4b4710adMerge branch 's51-subscriptions'mre
  • a731ef7eTickets conductor: S51 reviewed, deploy stepmre
  • b487b05aRecord verified direct push protocol handoffmre
  • 74e34cc3Verify encrypted push secrets and direct push retry semanticsmre
  • a1ac5cd0Push subscription notices directly to signed HyperConductor chat endpointsmre
  • d662ad27Remove superseded waker service for direct chat push protocolmre
  • c0ac927aTickets conductor: S51 redo for push protocolmre
  • ff2e8701Finalize subscription build verification and handoff reportmre
  • 07c6daeeTickets conductor: push allowlist URLsmre
  • 8517d14cTickets conductor: Hermes push endpointmre
  • aa4e192cTickets conductor: brief 027 push protocol changemre
  • 54bc5fe1Harden delta relevance, overflow caps and retry verificationmre
  • 8d8e2053Document subscription contract and exercise delta deliverymre
  • fd23726aAdd subscription delta API and signed wake bridgemre
  • c5d28fb5Tickets conductor: S51 startedmre
  • fd6ca1e6Tickets conductor: brief 027 waker design, push-test projectmre