Locale dependent error in addRangeCheck() function

Open Beginner friendly
#95 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
68/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
lua
Domain
backend

Research direction

Start at lib/jsonschema.lua around line 577 and inspect addRangeCheck(...), especially how string.format renders numeric range limits. Verify the generated validator under a locale that uses a comma decimal separator, then confirm the generated Lua remains valid and numeric range checks still work.

Written by the indexing model from the issue text.

Description

The generate validator function generates lua code as string object which is then used to validate JSON data.
If the given JSON schema contains a numeric value with range limitation, the function addRangeCheck(...) is called.
As this function uses string.format to generate if statements, the range limit which is given as type number will convert the number to a string. Depending on he active locale, the number is represented with either a comma or a full stop as a decimal separator. If a comma is used as decimal separator, the generated lua code is invalid.

See: https://github.com/api7/jsonschema/blob/a55072d6f4ae65a1caafea41cffd5464e971234c/lib/jsonschema.lua#L577

A possible fix would be to set a different locale temporarily to make sure a full stop is used as decimal separator, e.g.:

local function addRangeCheck(ctx, op, reference, msg)
  active_locale = os.setlocale(nil)
  os.setlocale("C")
  ctx:stmt(sformat('  if %s %s %s then', ctx:param(1), op, reference))
  ctx:stmt(sformat('    return false, %s("expected %%s to be %s %s", %s)',
                    ctx:libfunc('string.format'), msg, reference, ctx:param(1)))
  ctx:stmt(        '  end')
  os.setlocale(active_locale)
end
Dominant language
Lua
Stars
136
Forks
29
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from api7/jsonschema

All issues in api7/jsonschema

Similar issues

More Lua issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.