Skip to content

Commit 8327c4d

Browse files
authored
Merge pull request #231 from wravery/limit-depth
Add a configurable depth limit to the parser
2 parents 0e61a3c + 884acbc commit 8327c4d

File tree

5 files changed

+237
-97
lines changed

5 files changed

+237
-97
lines changed

include/graphqlservice/GraphQLParse.h

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,17 @@ struct ast
3434
bool validated = false;
3535
};
3636

37-
GRAPHQLPEG_EXPORT ast parseSchemaString(std::string_view input);
38-
GRAPHQLPEG_EXPORT ast parseSchemaFile(std::string_view filename);
37+
// By default, we want to limit the depth of nested nodes. You can override this with
38+
// another value for the depthLimit parameter in these parse functions.
39+
constexpr size_t c_defaultDepthLimit = 25;
3940

40-
GRAPHQLPEG_EXPORT ast parseString(std::string_view input);
41-
GRAPHQLPEG_EXPORT ast parseFile(std::string_view filename);
41+
GRAPHQLPEG_EXPORT ast parseSchemaString(
42+
std::string_view input, size_t depthLimit = c_defaultDepthLimit);
43+
GRAPHQLPEG_EXPORT ast parseSchemaFile(
44+
std::string_view filename, size_t depthLimit = c_defaultDepthLimit);
45+
46+
GRAPHQLPEG_EXPORT ast parseString(std::string_view input, size_t depthLimit = c_defaultDepthLimit);
47+
GRAPHQLPEG_EXPORT ast parseFile(std::string_view filename, size_t depthLimit = c_defaultDepthLimit);
4248

4349
} // namespace peg
4450

include/graphqlservice/internal/SyntaxTree.h

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,34 @@ class ast_node
146146
std::unique_ptr<unescaped_t> _unescaped;
147147
};
148148

149+
template <class ParseInput>
150+
class depth_limit_input : public ParseInput
151+
{
152+
public:
153+
template <typename... Args>
154+
explicit depth_limit_input(size_t depthLimit, Args&&... args) noexcept
155+
: ParseInput(std::forward<Args>(args)...)
156+
, _depthLimit(depthLimit)
157+
{
158+
}
159+
160+
size_t depthLimit() const noexcept
161+
{
162+
return _depthLimit;
163+
}
164+
165+
size_t selectionSetDepth = 0;
166+
167+
private:
168+
const size_t _depthLimit;
169+
};
170+
171+
using ast_file = depth_limit_input<file_input<>>;
172+
using ast_memory = depth_limit_input<memory_input<>>;
173+
149174
struct ast_input
150175
{
151-
std::variant<std::vector<char>, std::unique_ptr<file_input<>>, std::string_view> data;
176+
std::variant<std::vector<char>, std::unique_ptr<ast_file>, std::string_view> data;
152177
};
153178

154179
} // namespace graphql::peg

0 commit comments

Comments
 (0)