-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathIntrospectionSkipCondition.cs
More file actions
59 lines (50 loc) · 2.29 KB
/
IntrospectionSkipCondition.cs
File metadata and controls
59 lines (50 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System.Linq;
using System.Threading.Tasks;
using GraphQL.Language.AST;
using GraphQL.Validation;
namespace GraphQL.Authorization
{
/// <summary>
/// Skips authorization checks for introspection queries, namely all queries
/// that contain only __schema, __type and __typename top-level fields.
/// </summary>
public class IntrospectionSkipCondition : IAuthorizationSkipCondition
{
/// <inheritdoc />
public ValueTask<bool> ShouldSkip(ValidationContext context)
{
static bool IsIntrospectionField(Field f) => f.Name == "__schema" || f.Name == "__type" || f.Name == "__typename";
bool ContainsOnlyIntrospectionFields(IHaveSelectionSet node)
{
if (node.SelectionSet?.Selections?.Count == 0)
return false; // invalid document, better to return false
foreach (var selection in node.SelectionSet!.Selections)
{
switch (selection)
{
case Field field:
if (!IsIntrospectionField(field))
return false;
break;
case InlineFragment inlineFragment:
if (!ContainsOnlyIntrospectionFields(inlineFragment))
return false;
break;
case FragmentSpread fragmentSpread:
var fragmentDef = context.Document.Fragments.FindDefinition(fragmentSpread.Name);
if (fragmentDef == null || !ContainsOnlyIntrospectionFields(fragmentDef))
return false;
break;
default:
return false;
}
}
return true;
}
var actualOperation = context.Document.Operations.FirstOrDefault(x => x.Name == context.OperationName) ?? context.Document.Operations.FirstOrDefault();
return new ValueTask<bool>(actualOperation?.OperationType == OperationType.Query
? ContainsOnlyIntrospectionFields(actualOperation)
: false); // not an executable document
}
}
}