Skip to content

Commit 6b906d2

Browse files
committed
Forbid NaN and Infinity as a value Float type
The GraphQL specification explicitly forbids it: | Non-finite floating-point internal values (NaN and Infinity) cannot | be coerced to Float and must raise a field error. http://spec.graphql.org/October2021/#sec-Float Follows up #47
1 parent ff34a37 commit 6b906d2

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

graphql/types.lua

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -317,9 +317,20 @@ types.long = types.scalar({
317317
isValueOfTheType = isLong,
318318
})
319319

320+
-- Return `false` for NaN, Negative Infinity or Positive Infinity.
321+
-- Return `true` otherwise.
322+
local function isfinite(n)
323+
local d = n - n
324+
return n == n and d == d
325+
end
326+
320327
local function isFloat(value)
328+
-- http://spec.graphql.org/October2021/#sec-Float
329+
--
330+
-- > Non-finite floating-point internal values (NaN and Infinity) cannot be
331+
-- > coerced to Float and must raise a field error.
321332
if type(value) == 'number' then
322-
return true
333+
return isfinite(value)
323334
end
324335

325336
if type(value) == 'cdata' then

test/integration/graphql_test.lua

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2078,3 +2078,38 @@ function g.test_cdata_number_as_float()
20782078
t.assert_type(res, 'table')
20792079
t.assert_almost_equals(res.test, 18446744073709551615)
20802080
end
2081+
2082+
-- http://spec.graphql.org/October2021/#sec-Float
2083+
--
2084+
-- > Non-finite floating-point internal values (NaN and Infinity) cannot be
2085+
-- > coerced to Float and must raise a field error.
2086+
function g.test_non_finite_float()
2087+
local query = [[
2088+
query ($x: Float!) { test(arg: $x) }
2089+
]]
2090+
2091+
local function callback(_, args)
2092+
return args[1].value
2093+
end
2094+
2095+
local query_schema = {
2096+
['test'] = {
2097+
kind = types.float.nonNull,
2098+
arguments = {
2099+
arg = types.float.nonNull,
2100+
},
2101+
resolve = callback,
2102+
}
2103+
}
2104+
2105+
local nan = 0 / 0
2106+
local inf = 1 / 0
2107+
local ninf = -inf
2108+
2109+
for _, x in pairs({nan, inf, ninf}) do
2110+
local variables = {x = x}
2111+
t.assert_error_msg_content_equals(
2112+
'Wrong variable "x" for the Scalar "Float"', check_request, query,
2113+
query_schema, nil, nil, {variables = variables})
2114+
end
2115+
end

0 commit comments

Comments
 (0)