server: the map-tile gate and the internal X-Accel path (#24)
This commit is contained in:
+42
-1
@@ -23,6 +23,10 @@
|
||||
## list (`encountered.remove`, recorded on every sighting), character props through `prop.*`, and the
|
||||
## players/keys half that names a player: `player.setname`, `player.rename`, `key.show` and the
|
||||
## `roster` frame. The token link (`token.create`/`token.update` `character_id`) lands here too.
|
||||
## M3 slice 9 (#24): map tiles - `GET /tiles/<scene>/v<art_version>/<x>_<y>.png` in
|
||||
## server/tiles.nim: a strict canonical URL, the player's explored rule (the GM always), `404` for a
|
||||
## tile that does not exist and a bodyless `200` with `X-Accel-Redirect` to the internal `/_tiles/`
|
||||
## location, which nginx alone can serve (DESIGN 3.3, 6.6, 11.1).
|
||||
## Close reasons (FIXED, owner decision #18): mummy 0.4.8 cannot put a code in the close frame, so
|
||||
## every server-initiated close is preceded by a `closing {reason, code}` message and the client
|
||||
## reads 1005 + that message (DESIGN 6.5).
|
||||
@@ -32,7 +36,7 @@ import std/typedthreads
|
||||
import db_connector/db_sqlite
|
||||
import mummy, mummy/routers
|
||||
import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world
|
||||
import characters, geometry, props, text, tokens, vision, views, explored, worldmap, faults, moverules
|
||||
import characters, geometry, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules
|
||||
|
||||
const
|
||||
CookieName* = "fff_session"
|
||||
@@ -562,6 +566,42 @@ proc join(request: Request) {.gcsafe.} =
|
||||
headers["Referrer-Policy"] = "no-referrer"
|
||||
request.respond(303, headers)
|
||||
|
||||
proc tileGate(request: Request) {.gcsafe.} =
|
||||
## GET /tiles/<scene>/v<art_version>/<x>_<y>.png (DESIGN 3.3, 6.6; slice 9 / #24). Order: parse
|
||||
## the URL (malformed, out of range, another scene, stale art version -> 404 whatever the session),
|
||||
## then the session (missing or unknown -> 403), then the explored grid (unexplored -> 403).
|
||||
## The GM is always allowed. Nim never opens a tile file: a `200` carries `X-Accel-Redirect` to
|
||||
## the internal `/_tiles/` location and `Cache-Control: private` (Q4), and nginx serves the bytes.
|
||||
let parsed = parseTileRequest(request.pathParams["scene"], request.pathParams["version"],
|
||||
request.pathParams["file"], app.scene)
|
||||
if parsed.outcome != toTileOk:
|
||||
request.respond(404, body = "")
|
||||
return
|
||||
|
||||
let token = sessionCookie(request)
|
||||
var player: Option[Player]
|
||||
if token.len > 0:
|
||||
withLock app.dbLock:
|
||||
player = sessionPlayer(app.db, sha256Hex(token))
|
||||
if player.isNone:
|
||||
request.respond(403, body = "")
|
||||
return
|
||||
|
||||
var allowed = player.get.role == prGm
|
||||
if not allowed:
|
||||
withLock app.dbLock:
|
||||
if app.visions.hasKey(player.get.id):
|
||||
allowed = tileCoveredByExplored(app.scene, app.visions[player.get.id].explored,
|
||||
parsed.req.x, parsed.req.y)
|
||||
if not allowed:
|
||||
request.respond(403, body = "")
|
||||
return
|
||||
|
||||
var headers: HttpHeaders
|
||||
headers["X-Accel-Redirect"] = tilePath(app.scene, parsed.req.x, parsed.req.y)
|
||||
headers["Cache-Control"] = "private"
|
||||
request.respond(200, headers)
|
||||
|
||||
proc wsUpgrade(request: Request) {.gcsafe.} =
|
||||
## GET /ws: Origin, session, proto, total cap, then the upgrade (DESIGN 6.5 rows 1-5).
|
||||
if request.headers["Origin"] != app.cfg.publicOrigin:
|
||||
@@ -1952,6 +1992,7 @@ proc heartbeat() {.thread.} =
|
||||
proc buildRouter(): Router =
|
||||
result.get("/healthz", healthz)
|
||||
result.post("/join", join)
|
||||
result.get("/tiles/@scene/@version/@file", tileGate)
|
||||
result.get("/ws", wsUpgrade)
|
||||
|
||||
proc cliUsage(): string =
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
## Map-tile gate (DESIGN 3.3, 6.6, 10.2; M3 slice 9, issue #24). The server never reads tile bytes:
|
||||
## it decides whether the requesting player may have a tile and answers `200` with
|
||||
## `X-Accel-Redirect: /_tiles/<scene>/v<art_version>/<x>_<y>.png`, which only nginx can serve (its
|
||||
## `/_tiles/` location is `internal`, so a direct hit is a 404).
|
||||
##
|
||||
## URL grammar [FIXED (owner-delegated), #24]: `GET /tiles/<scene>/v<art_version>/<x>_<y>.png`.
|
||||
## Every numeric component is canonical decimal: digits only, length-bounded, no sign, no space and
|
||||
## **no leading zero** (`0` itself is the only number that starts with `0`). The canonical form gives
|
||||
## one URL per tile, so a cache or a test cannot see two spellings of the same resource.
|
||||
## - scene: 1..9 digits, must equal the one v1 scene id.
|
||||
## - art version: `v` + 1..9 digits, must equal the scene's `art_version` (`v1` in M3, 3.3).
|
||||
## - coordinates: 1..5 digits each (`x_y`), then exactly the lowercase suffix `.png`;
|
||||
## `x` in `[0, tileCols)`, `y` in `[0, tileRows)` where `tileCols = ceil(w / tile_size)`.
|
||||
## Malformed, out-of-range, another scene and a stale art version all answer **404** (the tile does
|
||||
## not exist). The route is parsed before the session is looked at, so an unauthenticated request
|
||||
## gets the same 404 for a tile that does not exist.
|
||||
##
|
||||
## Access rule [FIXED, Q4/3.3]: the GM is always allowed; a player is allowed iff at least one cell
|
||||
## of that player's explored grid overlaps the tile rectangle (in v1 `tile_size == cell`, so one
|
||||
## cell). Nothing here reads the world or a lock: main.nim hands in the scene and the player's
|
||||
## explored set. A player with no sight state has explored nothing, so every tile is refused.
|
||||
##
|
||||
## Status split [FIXED (owner-delegated), #24]: a nonexistent tile is 404; an existing tile that the
|
||||
## session may not have (no session, unknown session, or unexplored) is 403. The 403 is the same for
|
||||
## "no session" and "unexplored" so the route never says whether a tile exists for an anonymous
|
||||
## requester beyond the non-secret scene geometry (3.1: world size and cell size are not secret).
|
||||
import std/[math, sets, strutils]
|
||||
import vision, world
|
||||
|
||||
type
|
||||
TileOutcome* = enum
|
||||
toTileOk
|
||||
toTileMalformed ## a component that is not canonical or a suffix that is not `.png` -> 404
|
||||
toTileOutOfRange ## a canonical coordinate outside the scene's tile grid -> 404
|
||||
toTileWrongScene ## a canonical scene id that is not the one v1 scene -> 404
|
||||
toTileWrongVersion ## a canonical art version that is not the scene's -> 404
|
||||
|
||||
TileRequest* = object
|
||||
## A parsed, in-range tile URL.
|
||||
scene*: int
|
||||
artVersion*: int
|
||||
x*, y*: int
|
||||
|
||||
const
|
||||
MaxSceneDigits* = 9
|
||||
MaxVersionDigits* = 9
|
||||
MaxCoordDigits* = 5
|
||||
## 99999 tiles is far beyond any v1 scene (128 tiles per side at 4096 px); a longer component
|
||||
## is malformed rather than parsed.
|
||||
|
||||
proc canonicalNumber*(raw: string, maxDigits: int, dest: var int): bool =
|
||||
## The URL's number grammar (this module's header): digits only, 1..maxDigits, no leading zero.
|
||||
## Nothing is parsed unless every rule holds, so an overflow cannot reach `parseInt`.
|
||||
if raw.len == 0 or raw.len > maxDigits: return false
|
||||
if raw[0] == '0' and raw.len > 1: return false
|
||||
for ch in raw:
|
||||
if ch notin Digits: return false
|
||||
try:
|
||||
dest = parseInt(raw)
|
||||
except ValueError:
|
||||
return false
|
||||
true
|
||||
|
||||
proc parseVersion*(raw: string, dest: var int): bool =
|
||||
## `v<canonical number>` exactly.
|
||||
if raw.len < 2 or raw[0] != 'v': return false
|
||||
canonicalNumber(raw[1 .. ^1], MaxVersionDigits, dest)
|
||||
|
||||
proc tileCols*(sc: SceneRec): int =
|
||||
## Tiles across the scene (DESIGN 3.3: the tile grid's origin is the world origin).
|
||||
max(1, int(ceil(sc.w / float(sc.tileSize))))
|
||||
|
||||
proc tileRows*(sc: SceneRec): int =
|
||||
max(1, int(ceil(sc.h / float(sc.tileSize))))
|
||||
|
||||
proc tileInRange*(sc: SceneRec, x, y: int): bool =
|
||||
x >= 0 and y >= 0 and x < tileCols(sc) and y < tileRows(sc)
|
||||
|
||||
proc parseTileRequest*(sceneRaw, versionRaw, fileRaw: string,
|
||||
sc: SceneRec): tuple[outcome: TileOutcome, req: TileRequest] =
|
||||
## Strict parse of the three route components (this module's header). `req` is only meaningful
|
||||
## when `outcome == toTileOk`.
|
||||
var sceneId, artVersion: int
|
||||
if not canonicalNumber(sceneRaw, MaxSceneDigits, sceneId):
|
||||
return (toTileMalformed, TileRequest())
|
||||
if sceneId != sc.id:
|
||||
return (toTileWrongScene, TileRequest())
|
||||
if not parseVersion(versionRaw, artVersion):
|
||||
return (toTileMalformed, TileRequest())
|
||||
if artVersion != sc.artVersion:
|
||||
return (toTileWrongVersion, TileRequest())
|
||||
|
||||
if not fileRaw.endsWith(".png") or fileRaw.len <= 4:
|
||||
return (toTileMalformed, TileRequest())
|
||||
let base = fileRaw[0 ..< fileRaw.len - 4]
|
||||
let sep = base.find('_')
|
||||
if sep <= 0 or sep != base.rfind('_') or sep == base.len - 1:
|
||||
return (toTileMalformed, TileRequest()) # exactly one separator, both sides non-empty
|
||||
var x, y: int
|
||||
if not canonicalNumber(base[0 ..< sep], MaxCoordDigits, x):
|
||||
return (toTileMalformed, TileRequest())
|
||||
if not canonicalNumber(base[sep + 1 .. ^1], MaxCoordDigits, y):
|
||||
return (toTileMalformed, TileRequest())
|
||||
if not tileInRange(sc, x, y):
|
||||
return (toTileOutOfRange, TileRequest())
|
||||
|
||||
(toTileOk, TileRequest(scene: sceneId, artVersion: artVersion, x: x, y: y))
|
||||
|
||||
proc tileCoveredByExplored*(sc: SceneRec, explored: HashSet[int], tileX, tileY: int): bool =
|
||||
## DESIGN 3.3: a tile is allowed iff at least one explored cell overlaps it. The tile rectangle is
|
||||
## `[tileX*tile_size, (tileX+1)*tile_size) x ...`; a cell overlaps when its rectangle shares any
|
||||
## point with it. General over `tile_size` and `cell` (v1 pins them equal, Q4, but a 64 px
|
||||
## fallback changes only the scene row, 3.3).
|
||||
let x0 = tileX * sc.tileSize
|
||||
let y0 = tileY * sc.tileSize
|
||||
let cx0 = x0 div sc.cell
|
||||
let cy0 = y0 div sc.cell
|
||||
let cx1 = (x0 + sc.tileSize - 1) div sc.cell
|
||||
let cy1 = (y0 + sc.tileSize - 1) div sc.cell
|
||||
for cy in cy0 .. cy1:
|
||||
for cx in cx0 .. cx1:
|
||||
if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue
|
||||
if sc.cellIndex(cx, cy) in explored: return true
|
||||
false
|
||||
|
||||
proc tileAllowed*(sc: SceneRec, explored: HashSet[int], tileX, tileY: int,
|
||||
isGm: bool): bool =
|
||||
## The whole gate rule (3.3): the GM is always allowed; a player only through its explored grid.
|
||||
if isGm: return true
|
||||
tileCoveredByExplored(sc, explored, tileX, tileY)
|
||||
|
||||
proc tilePath*(sc: SceneRec, x, y: int): string =
|
||||
## The internal nginx path of a tile (3.3, 11.1): `/_tiles/<scene>/v<art_version>/<x>_<y>.png`.
|
||||
## Built only from integers, never from request text, so no request can steer it.
|
||||
"/_tiles/" & $sc.id & "/v" & $sc.artVersion & "/" & $x & "_" & $y & ".png"
|
||||
@@ -0,0 +1,117 @@
|
||||
## Map-tile gate, in-process (DESIGN 3.3, 10.2; M3 slice 9, issue #24). Pins the URL grammar
|
||||
## (canonical decimal, no leading zero, bounded), the tile grid and the access rule ("a tile is
|
||||
## allowed iff at least one explored cell overlaps it"), without a server, a lock or a file. The
|
||||
## black-box proof through the real binary and the test nginx is tools/tiles.test.mjs.
|
||||
import std/[sets, unittest]
|
||||
import tiles, vision, world
|
||||
|
||||
proc testScene(tile = 32, cell = 32, w = 4096.0, h = 4096.0): SceneRec =
|
||||
## The v1 scene (migration step 3), or the 64 px fallback of Q4.
|
||||
SceneRec(id: 1, name: "Scene", w: w, h: h, tileSize: tile, cell: cell, gridSize: 0,
|
||||
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1, nextWallId: 1)
|
||||
|
||||
proc cells(sc: SceneRec, coords: openArray[(int, int)]): HashSet[int] =
|
||||
for (cx, cy) in coords: result.incl sc.cellIndex(cx, cy)
|
||||
|
||||
proc parseOk(sc: SceneRec, scene, version, file: string): TileRequest =
|
||||
let r = parseTileRequest(scene, version, file, sc)
|
||||
check r.outcome == toTileOk
|
||||
r.req
|
||||
|
||||
suite "tile URL grammar":
|
||||
test "canonical numbers: digits only, bounded, no leading zero":
|
||||
var n = -1
|
||||
check canonicalNumber("0", MaxCoordDigits, n) and n == 0
|
||||
check canonicalNumber("127", MaxCoordDigits, n) and n == 127
|
||||
check canonicalNumber("99999", MaxCoordDigits, n) and n == 99999
|
||||
for bad in ["", "00", "01", "007", "-1", "+1", " 1", "1 ", "1.0", "1e2", "0x1", "١",
|
||||
"100000", "1_0"]:
|
||||
check not canonicalNumber(bad, MaxCoordDigits, n)
|
||||
|
||||
test "a canonical URL parses to its three integers":
|
||||
let sc = testScene()
|
||||
let r = parseOk(sc, "1", "v1", "127_0.png")
|
||||
check r.scene == 1 and r.artVersion == 1 and r.x == 127 and r.y == 0
|
||||
check parseOk(sc, "1", "v1", "0_0.png").x == 0
|
||||
|
||||
test "leading zero tile coordinates are malformed":
|
||||
let sc = testScene()
|
||||
for file in ["00_0.png", "0_01.png", "000_000.png"]:
|
||||
check parseTileRequest("1", "v1", file, sc).outcome == toTileMalformed
|
||||
|
||||
test "suffix, separator and character rules are strict":
|
||||
let sc = testScene()
|
||||
for file in ["1_1", "1_1.PNG", "1_1.png.png", "1.png", ".png", "1_1_.png", "_1_1.png",
|
||||
"1__1.png", "1_1_.png", "1-1.png", "1_1.png ", "1_1.png%00", "1,1.png"]:
|
||||
check parseTileRequest("1", "v1", file, sc).outcome == toTileMalformed
|
||||
# one separator only, both sides non-empty
|
||||
check parseTileRequest("1", "v1", "1_2_3.png", sc).outcome == toTileMalformed
|
||||
|
||||
test "a tile coordinate outside the grid is out of range":
|
||||
let sc = testScene()
|
||||
check parseTileRequest("1", "v1", "127_127.png", sc).outcome == toTileOk
|
||||
for file in ["128_0.png", "0_128.png", "128_128.png", "99999_0.png"]:
|
||||
check parseTileRequest("1", "v1", file, sc).outcome == toTileOutOfRange
|
||||
# a 64 px tile grid has half as many tiles per side (the Q4 fallback changes no code)
|
||||
let big = testScene(tile = 64)
|
||||
check tileCols(big) == 64 and tileRows(big) == 64
|
||||
check parseTileRequest("1", "v1", "63_63.png", big).outcome == toTileOk
|
||||
check parseTileRequest("1", "v1", "64_0.png", big).outcome == toTileOutOfRange
|
||||
# a map whose size is not a multiple of the tile size keeps the partial border tile
|
||||
let odd = testScene(tile = 32, w = 4100.0)
|
||||
check tileCols(odd) == 129
|
||||
check parseTileRequest("1", "v1", "128_0.png", odd).outcome == toTileOk
|
||||
|
||||
test "another scene and a stale art version are their own 404 classes":
|
||||
let sc = testScene()
|
||||
check parseTileRequest("2", "v1", "0_0.png", sc).outcome == toTileWrongScene
|
||||
check parseTileRequest("0", "v1", "0_0.png", sc).outcome == toTileWrongScene
|
||||
check parseTileRequest("01", "v1", "0_0.png", sc).outcome == toTileMalformed
|
||||
check parseTileRequest("1", "v2", "0_0.png", sc).outcome == toTileWrongVersion
|
||||
check parseTileRequest("1", "1", "0_0.png", sc).outcome == toTileMalformed
|
||||
check parseTileRequest("1", "v01", "0_0.png", sc).outcome == toTileMalformed
|
||||
check parseTileRequest("1", "V1", "0_0.png", sc).outcome == toTileMalformed
|
||||
check parseTileRequest("1234567890", "v1", "0_0.png", sc).outcome == toTileMalformed
|
||||
|
||||
test "the internal path is built from integers only":
|
||||
check tilePath(testScene(), 3, 4) == "/_tiles/1/v1/3_4.png"
|
||||
|
||||
suite "tile access rule":
|
||||
test "an unexplored tile is refused":
|
||||
let sc = testScene()
|
||||
var empty = initHashSet[int]()
|
||||
check not tileAllowed(sc, empty, 3, 4, false)
|
||||
# exploring a different cell does not help
|
||||
empty = cells(sc, [(5, 4)])
|
||||
check not tileAllowed(sc, empty, 3, 4, false)
|
||||
check tileAllowed(sc, empty, 5, 4, false)
|
||||
|
||||
test "the GM is always allowed":
|
||||
let sc = testScene()
|
||||
check tileAllowed(sc, initHashSet[int](), 3, 4, true)
|
||||
check tileAllowed(sc, initHashSet[int](), 127, 127, true)
|
||||
|
||||
test "a tile is allowed when any overlapping cell is explored":
|
||||
# A 64 px tile over 32 px cells covers four cells: one is enough (3.3 "at least one").
|
||||
let sc = testScene(tile = 64)
|
||||
let all = [(2, 2), (3, 2), (2, 3), (3, 3)]
|
||||
for i in 0 ..< all.len:
|
||||
var ex = initHashSet[int]()
|
||||
ex.incl sc.cellIndex(all[i][0], all[i][1])
|
||||
check tileAllowed(sc, ex, 1, 1, false)
|
||||
# a cell just outside the tile rectangle does not allow it
|
||||
var outside = initHashSet[int]()
|
||||
outside.incl sc.cellIndex(4, 2)
|
||||
check not tileAllowed(sc, outside, 1, 1, false)
|
||||
outside = initHashSet[int]()
|
||||
outside.incl sc.cellIndex(2, 4)
|
||||
check not tileAllowed(sc, outside, 1, 1, false)
|
||||
# and the whole rectangle explored allows it too
|
||||
check tileAllowed(sc, cells(sc, all), 1, 1, false)
|
||||
|
||||
test "the explored overlap respects the scene border":
|
||||
# 4100 px wide, 32 px cells: cell 128 is partial; the border tile 128 must still be gated.
|
||||
let sc = testScene(tile = 32, w = 4100.0)
|
||||
check tileAllowed(sc, cells(sc, [(128, 0)]), 128, 0, false)
|
||||
# a cell beyond the scene is never consulted even if a stray index says so
|
||||
check not tileAllowed(sc, cells(sc, [(129, 0)]), 128, 0, false)
|
||||
Reference in New Issue
Block a user