Skip to content

Commit 4620410

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 af0ea41 commit 4620410

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
@@ -2112,3 +2112,38 @@ function g.test_large_float_argument()
21122112
t.assert_type(res, 'table')
21132113
t.assert_almost_equals(res.test, 18446744073709551615)
21142114
end
2115+
2116+
-- http://spec.graphql.org/October2021/#sec-Float
2117+
--
2118+
-- > Non-finite floating-point internal values (NaN and Infinity) cannot be
2119+
-- > coerced to Float and must raise a field error.
2120+
function g.test_non_finite_float()
2121+
local query = [[
2122+
query ($x: Float!) { test(arg: $x) }
2123+
]]
2124+
2125+
local function callback(_, args)
2126+
return args[1].value
2127+
end
2128+
2129+
local query_schema = {
2130+
['test'] = {
2131+
kind = types.float.nonNull,
2132+
arguments = {
2133+
arg = types.float.nonNull,
2134+
},
2135+
resolve = callback,
2136+
}
2137+
}
2138+
2139+
local nan = 0 / 0
2140+
local inf = 1 / 0
2141+
local ninf = -inf
2142+
2143+
for _, x in pairs({nan, inf, ninf}) do
2144+
local variables = {x = x}
2145+
t.assert_error_msg_content_equals(
2146+
'Wrong variable "x" for the Scalar "Float"', check_request, query,
2147+
query_schema, nil, nil, {variables = variables})
2148+
end
2149+
end

0 commit comments

Comments
 (0)