all repos — litestore @ 1e408c9bc74fd5d25e84ac4a6642cd8ab93e5405

A minimalist nosql document store.

src/litestorepkg/lib/server.nim

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
import
  asynchttpserver,
  asyncdispatch,
  times,
  strutils,
  pegs,
  logger,
  cgi,
  os,
  json,
  tables,
  strtabs,
  base64,
  asyncnet,
  jwt,
  sequtils
import 
  types, 
  utils, 
  api_v1,
  api_v2,
  api_v3,
  api_v4,
  api_v5,
  api_v6,
  api_v7

export
  api_v5


proc decodeUrlSafeAsString*(s: string): string =
  var s = s.replace('-', '+').replace('_', '/')
  while s.len mod 4 > 0:
    s &= "="
  base64.decode(s)

proc decodeUrlSafe*(s: string): seq[byte] =
  cast[seq[byte]](decodeUrlSafeAsString(s))

proc getReqInfo(req: LSRequest): string =
  var url = req.url.path
  if req.url.anchor != "":
    url = url & "#" & req.url.anchor
  if req.url.query != "":
    url = url & "?" & req.url.query
  return req.hostname & " " & $req.reqMethod & " " & url

proc handleCtrlC() {.noconv.} =
  echo ""
  LOG.info("Exiting...")
  quit()
  
template auth(uri: string, jwt: JWT): void =
  let cfg = access[uri]
  if cfg.hasKey(reqMethod):
    LOG.debug("Authenticating: " & reqMethod & " " & uri)
    if not req.headers.hasKey("Authorization"): 
      return resError(Http401, "Unauthorized - No token")
    let token = req.headers["Authorization"].replace(peg"^ 'Bearer '", "")
    # Validate token
    try:
      jwt = token.toJwt()
      let parts = token.split(".")
      var sig = LS.auth["signature"].getStr 
      discard verifySignature(parts[0] & "." & parts[1], decodeUrlSafe(parts[2]), sig)
      verifyTimeClaims(jwt)
      let scopes = cfg[reqMethod]
      # Validate scope
      var authorized = ""
      let reqScopes = ($jwt.claims["scope"].node.str).split(peg"\s+")
      LOG.debug("Resource scopes: " & $scopes)
      LOG.debug("Request scopes: " & $reqScopes)
      for scope in scopes:
        for reqScope in reqScopes:
          if reqScope == scope.getStr:
            authorized = scope.getStr
            break
      if authorized == "":
        return resError(Http403, "Forbidden - You are not permitted to access this resource")
      LOG.debug("Authorization successful: " & authorized)
    except:
      echo getCurrentExceptionMsg()
      writeStackTrace()
      return resError(Http401, "Unauthorized - Invalid token")

proc isAllowed(resource, id, meth: string): bool =
  if LS.config.kind != JObject or not LS.config.hasKey("resources"):
    return true
  var reqUri = "/" & resource & "/" & id
  if reqUri[^1] == '/':
    reqUri.removeSuffix({'/'})
  let parts = reqUri.split("/")
  let ancestors = parts[1..parts.len-2]
  var currentPath = ""
  var currentPaths = ""
  for p in ancestors:
    currentPath &= "/" & p
    currentPaths = currentPath & "/*"
    if LS.config["resources"].hasKey(currentPaths) and LS.config["resources"][currentPaths].hasKey(meth) and LS.config["resources"][currentPaths][meth].hasKey("allowed"):
      let allowed = LS.config["resources"][currentPaths][meth]["allowed"]
      if (allowed == %false):
        return false;
  if LS.config["resources"].hasKey(reqUri) and LS.config["resources"][reqUri].hasKey(meth) and LS.config["resources"][reqUri][meth].hasKey("allowed"):
    let allowed = LS.config["resources"][reqUri][meth]["allowed"]
    if (allowed == %false):
      return false
  return true

proc processApiUrl(req: LSRequest, LS: LiteStore, info: ResourceInfo): LSResponse = 
  var reqUri = "/" & info.resource & "/" & info.id
  if reqUri[^1] == '/':
    reqUri.removeSuffix({'/'})
  let reqMethod = $req.reqMethod
  var jwt: JWT
  if not isAllowed(info.resource, info.id, reqMethod):
    return resError(Http405, "Method not allowed: $1" % reqMethod)
  # Authentication/Authorization
  if LS.auth != newJNull():
    var uri = reqUri
    let access = LS.auth["access"]
    while true:
      # Match exact url
      if access.hasKey(uri):
        auth(uri, jwt)
        break
      # Match exact url adding /* (e.g. /docs would match also /docs/* in auth.json)
      elif uri[^1] != '*' and uri[^1] != '/':
        if access.hasKey(uri & "/*"):
          auth(uri & "/*", jwt)
          break
      var parts = uri.split("/")
      if parts[^1] == "*":
        discard parts.pop
      discard parts.pop
      if parts.len > 0:
        # Go up one level
        uri = parts.join("/") & "/*"
      else:
        # If at the end of the URL, check generic URL
        uri = "/*"
        if access.hasKey(uri):
          auth(uri, jwt)
        break
  if info.version == "v7":
    if info.resource.match(peg"^docs / info / tags / indexes / stores$"):
      var nReq = req
      if jwt.signature.len != 0:
        nReq.jwt = jwt
      return api_v7.execute(nReq, LS, info.resource, info.id)
    elif info.resource.match(peg"^dir$"):
      if LS.directory.len > 0:
        return api_v7.serveFile(req, LS, info.id)
      else:
        return resError(Http400, "Bad Request - Not serving any directory." % info.version)
    else:
      return resError(Http404, "Resource Not Found: $1" % info.resource)
  if info.version == "v6":
    if info.resource.match(peg"^docs / info / tags / indexes$"):
      var nReq = req
      if jwt.signature.len != 0:
        nReq.jwt = jwt
      return api_v6.execute(nReq, LS, info.resource, info.id)
    elif info.resource.match(peg"^dir$"):
      if LS.directory.len > 0:
        return api_v6.serveFile(req, LS, info.id)
      else:
        return resError(Http400, "Bad Request - Not serving any directory." % info.version)
    else:
      return resError(Http404, "Resource Not Found: $1" % info.resource)
  elif info.version == "v5":
    if info.resource.match(peg"^docs / info / tags / indexes$"):
      return api_v5.route(req, LS, info.resource, info.id)
    elif info.resource.match(peg"^dir$"):
      if LS.directory.len > 0:
        return api_v5.serveFile(req, LS, info.id)
      else:
        return resError(Http400, "Bad Request - Not serving any directory." % info.version)
    else:
      return resError(Http404, "Resource Not Found: $1" % info.resource)
  elif info.version == "v4":
    if info.resource.match(peg"^docs / info / tags$"):
      return api_v4.route(req, LS, info.resource, info.id)
    elif info.resource.match(peg"^dir$"):
      if LS.directory.len > 0:
        return api_v4.serveFile(req, LS, info.id)
      else:
        return resError(Http400, "Bad Request - Not serving any directory." % info.version)
    else:
      return resError(Http404, "Resource Not Found: $1" % info.resource)
  elif info.version == "v3":
    if info.resource.match(peg"^docs / info$"):
      return api_v3.route(req, LS, info.resource, info.id)
    elif info.resource.match(peg"^dir$"):
      if LS.directory.len > 0:
        return api_v3.serveFile(req, LS, info.id)
      else:
        return resError(Http400, "Bad Request - Not serving any directory." % info.version)
    else:
      return resError(Http404, "Resource Not Found: $1" % info.resource)
  elif info.version == "v2":
    if info.resource.match(peg"^docs / info$"):
      return api_v2.route(req, LS, info.resource, info.id)
    elif info.resource.match(peg"^dir$"):
      if LS.directory.len > 0:
        return api_v2.serveFile(req, LS, info.id)
      else:
        return resError(Http400, "Bad Request - Not serving any directory." % info.version)
    else:
      return resError(Http404, "Resource Not Found: $1" % info.resource)
  elif info.version == "v1":
    if info.resource.match(peg"^docs / info$"):
      return api_v1.route(req, LS, info.resource, info.id)
    elif info.resource.match(peg"^dir$"):
      if LS.directory.len > 0:
        return api_v1.serveFile(req, LS, info.id)
      else:
        return resError(Http400, "Bad Request - Not serving any directory." % info.version)
    else:
      return resError(Http404, "Resource Not Found: $1" % info.resource)
  else:
    if info.version == "v1" or info.version == "v2" or info.version == "v3" or info.version == "v4" or info.version == "v5":
      return resError(Http400, "Bad Request - Invalid API version: $1" % info.version)
    else:
      if info.resource.decodeURL.strip == "":
        return resError(Http400, "Bad Request - No resource specified." % info.resource)
      else:
        return resError(Http404, "Resource Not Found: $1" % info.resource)

proc process*(req: LSRequest, LS: LiteStore): LSResponse {.gcsafe.}=
  var matches = @["", "", ""]
  template route(req: LSRequest, peg: Peg, op: untyped): untyped =
    if req.url.path.find(peg, matches) != -1:
      op
  try:
    var info: ResourceInfo
    req.route peg"^\/?$":
      info.version = "v7"
      info.resource = "info"
      return req.processApiUrl(LS, info)
    req.route peg"^\/favicon.ico$":
      result.code = Http200
      result.content = LS.favicon
      result.headers = ctHeader("image/x-icon")
      return result
    req.route PEG_DEFAULT_URL:
      info.version = "v7"
      info.resource = matches[0]
      info.id = matches[1]
      return req.processApiUrl(LS, info)
    req.route PEG_URL:
      info.version = matches[0]
      info.resource = matches[1]
      info.id = matches[2]
      return req.processApiUrl(LS, info)
    raise newException(EInvalidRequest, req.getReqInfo())
  except EInvalidRequest:
    let e = (ref EInvalidRequest)(getCurrentException())
    let trace = e.getStackTrace()
    return resError(Http404, "Resource Not Found: $1" % getCurrentExceptionMsg().split(" ")[2], trace)
  except:
    let e = getCurrentException()
    let trace = e.getStackTrace()
    return resError(Http500, "Internal Server Error: $1" % getCurrentExceptionMsg(), trace)


proc process*(req: LSRequest, LSDICT: OrderedTable[string, LiteStore]): LSResponse {.gcsafe.}=
  var matches = @["", ""]
  if req.url.path.find(PEG_STORE_URL, matches) != -1:
    let id = matches[0]
    let path = matches[1]
    if path == "":
      var info: ResourceInfo
      info.version = "v7"
      info.resource = "stores"
      info.id = id
      return req.processApiUrl(LS, info)
    else:
      var newReq = req
      newReq.url.path = "/$1" % path
      return newReq.process(LSDICT[id])
  else:
    return req.process(LS)

setControlCHook(handleCtrlC)

proc serve*(LS: LiteStore) =
  var server = newAsyncHttpServer()
  proc handleHttpRequest(origReq: Request): Future[void] {.async, gcsafe, closure.} =
    var client = origReq.client
    var req = newLSRequest(origReq)
    let address = client.getLocalAddr()
    req.url.hostname = address[0]
    req.url.port = $int(address[1])
    LOG.info(getReqInfo(req).replace("$", "$$"))
    let res = req.process(LSDICT)
    var newReq = newRequest(req, client)
    await newReq.respond(res.code, res.content, res.headers)
  echo(LS.appname & " v" & LS.appversion & " started on " & LS.address & ":" & $LS.port & ".")
  if LS.configFile != "":
    echo "- Configuration file: " & LS.configFile
  if LS.authFile != "":
    echo "- Auth file: " & LS.authFile
  if LS.mount:
    echo "- Mirroring datastore changes to: " & LS.directory
  elif LS.directory != "":
    echo "- Serving directory: " & LS.directory
  if LS.readonly:
    echo "- Read-only mode"
  echo "- Log level: " & LS.loglevel
  echo "- Stores:"
  let storeIds = toSeq(LSDICT.keys)
  for i in countdown(storeIds.len-1, 0):
    let file = LSDICT[storeIds[i]].file
    echo "  - $1: $2" % [storeIds[i], file]
  if LS.middleware.len > 0:
    echo "- Middleware configured"
  if LS.auth != newJNull():
    echo "- Authorization configured"
  asyncCheck server.serve(LS.port.Port, handleHttpRequest, LS.address)