Skip to content

Commit fc580a5

Browse files
committed
JS: Add TypeResolution.qll
1 parent d61f576 commit fc580a5

File tree

1 file changed

+384
-0
lines changed

1 file changed

+384
-0
lines changed
Lines changed: 384 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,384 @@
1+
private import javascript
2+
private import semmle.javascript.internal.NameResolution::NameResolution
3+
private import semmle.javascript.internal.UnderlyingTypes
4+
private import semmle.javascript.dataflow.internal.sharedlib.SummaryTypeTracker as SummaryTypeTracker
5+
6+
module TypeResolution {
7+
predicate trackClassValue = ValueFlow::TrackNode<ClassDefinition>::track/1;
8+
9+
predicate trackType = TypeFlow::TrackNode<TypeDefinition>::track/1;
10+
11+
Node trackFunctionType(Function fun) {
12+
result = fun
13+
or
14+
exists(Node mid | mid = trackFunctionType(fun) |
15+
TypeFlow::step(mid, result)
16+
or
17+
UnderlyingTypes::underlyingTypeStep(mid, result)
18+
)
19+
}
20+
21+
predicate trackFunctionValue = ValueFlow::TrackNode<Function>::track/1;
22+
23+
/**
24+
* Gets the representative for the type containing the given member.
25+
*
26+
* For non-static members this is simply the enclosing type declaration.
27+
*
28+
* For static members we use the class's `Variable` as representative for the type of the class object.
29+
*/
30+
private Node getMemberBase(MemberDeclaration member) {
31+
if member.isStatic()
32+
then result = member.getDeclaringClass().getVariable()
33+
else result = member.getDeclaringType()
34+
}
35+
36+
/**
37+
* Holds if `host` is a type with a `content` of type `memberType`.
38+
*/
39+
private predicate typeMember(Node host, DataFlow::Content content, Node memberType) {
40+
exists(MemberDeclaration decl | host = getMemberBase(decl) |
41+
exists(FieldDeclaration field |
42+
decl = field and
43+
content.asPropertyName() = field.getName() and
44+
memberType = field.getTypeAnnotation()
45+
)
46+
or
47+
exists(MethodDeclaration method |
48+
decl = method and
49+
content.asPropertyName() = method.getName() and
50+
memberType = method.getBody() // use the Function as representative for the function type
51+
)
52+
or
53+
decl instanceof IndexSignature and
54+
memberType = decl.(IndexSignature).getBody().getReturnTypeAnnotation() and
55+
content.isUnknownArrayElement()
56+
)
57+
or
58+
// Ad-hoc support for array types. We don't support generics in general currently, we just special-case arrays.
59+
content.isUnknownArrayElement() and
60+
(
61+
memberType = host.(ArrayTypeExpr).getElementType()
62+
or
63+
exists(GenericTypeExpr type |
64+
host = type and
65+
type.getTypeAccess().(LocalTypeAccess).getName() = ["Array", "ReadonlyArray"] and
66+
memberType = type.getTypeArgument(0)
67+
)
68+
or
69+
exists(JSDocAppliedTypeExpr type |
70+
host = type and
71+
type.getHead().(JSDocLocalTypeAccess).getName() = "Array" and
72+
memberType = type.getArgument(0)
73+
)
74+
)
75+
or
76+
// Inherit members from base types
77+
exists(ClassOrInterface baseType | typeMember(baseType, content, memberType) |
78+
host.(ClassDefinition).getSuperClass() = trackClassValue(baseType)
79+
or
80+
host.(ClassOrInterface).getASuperInterface() = trackType(baseType)
81+
)
82+
}
83+
84+
/**
85+
* Holds `use` refers to `host`, and `host` has type members.
86+
*
87+
* Currently steps through unions and intersections, which acts as a basic
88+
* approximation to the unions/intersection of objects.
89+
*/
90+
private predicate typeMemberHostReaches(Node host, Node use) {
91+
typeMember(host, _, _) and
92+
use = host
93+
or
94+
exists(Node mid | typeMemberHostReaches(host, mid) |
95+
TypeFlow::step(mid, use)
96+
or
97+
UnderlyingTypes::underlyingTypeStep(mid, use)
98+
)
99+
}
100+
101+
/**
102+
* Holds if there is a read from from `object` to `member` that reads `contents`.
103+
*/
104+
private predicate valueReadStep(Node object, DataFlow::ContentSet contents, Node member) {
105+
member.(PropAccess).accesses(object, contents.asPropertyName())
106+
or
107+
object.(ObjectPattern).getPropertyPatternByName(contents.asPropertyName()).getValuePattern() =
108+
member
109+
or
110+
SummaryTypeTracker::basicLoadStep(object.(AST::ValueNode).flow(),
111+
member.(AST::ValueNode).flow(), contents)
112+
}
113+
114+
private predicate callTarget(InvokeExpr call, Function target) {
115+
exists(ClassDefinition cls |
116+
valueHasType(call.(NewExpr).getCallee(), trackClassValue(cls)) and
117+
target = cls.getConstructor().getBody()
118+
)
119+
or
120+
valueHasType(call.(InvokeExpr).getCallee(), trackFunctionValue(target))
121+
or
122+
valueHasType(call.(InvokeExpr).getCallee(), trackFunctionType(target)) and
123+
(
124+
call instanceof NewExpr and
125+
target = any(ConstructorTypeExpr t).getFunction()
126+
or
127+
call instanceof CallExpr and
128+
target = any(PlainFunctionTypeExpr t).getFunction()
129+
)
130+
or
131+
exists(InterfaceDefinition interface, CallSignature sig |
132+
valueHasType(call.(InvokeExpr).getCallee(), trackType(interface)) and
133+
sig = interface.getACallSignature() and
134+
target = sig.getBody()
135+
|
136+
call instanceof NewExpr and
137+
sig instanceof ConstructorCallSignature
138+
or
139+
call instanceof CallExpr and
140+
sig instanceof FunctionCallSignature
141+
)
142+
}
143+
144+
private predicate functionReturnType(Function func, Node returnType) {
145+
returnType = func.getReturnTypeAnnotation()
146+
or
147+
not exists(func.getReturnTypeAnnotation()) and
148+
exists(Function functionType |
149+
contextualType(func, trackFunctionType(functionType)) and
150+
returnType = functionType.getReturnTypeAnnotation()
151+
)
152+
}
153+
154+
bindingset[name]
155+
private predicate isPromiseTypeName(string name) {
156+
name.regexpMatch(".?(Promise|Thenable)(Like)?")
157+
}
158+
159+
private Node unwrapPromiseType(Node promiseType) {
160+
exists(GenericTypeExpr type |
161+
promiseType = type and
162+
isPromiseTypeName(type.getTypeAccess().(LocalTypeAccess).getName()) and
163+
result = type.getTypeArgument(0)
164+
)
165+
or
166+
exists(JSDocAppliedTypeExpr type |
167+
promiseType = type and
168+
isPromiseTypeName(type.getHead().(JSDocLocalTypeAccess).getName()) and
169+
result = type.getArgument(0)
170+
)
171+
}
172+
173+
private predicate contextualType(Node value, Node type) {
174+
exists(InvokeExpr call, Function target, int i |
175+
callTarget(call, target) and
176+
value = call.getArgument(i) and
177+
type = target.getParameter(i).getTypeAnnotation()
178+
)
179+
or
180+
exists(Function lambda, Node returnType |
181+
value = lambda.getAReturnedExpr() and
182+
functionReturnType(lambda, returnType)
183+
|
184+
not lambda.isAsyncOrGenerator() and
185+
type = returnType
186+
or
187+
lambda.isAsync() and
188+
type = unwrapPromiseType(returnType)
189+
)
190+
or
191+
exists(ObjectExpr object, Node objectType, Node host, string name |
192+
contextualType(object, objectType) and
193+
typeMemberHostReaches(host, objectType) and
194+
typeMember(host, any(DataFlow::Content c | c.asPropertyName() = name), type) and
195+
value = object.getPropertyByName(name).getInit()
196+
)
197+
or
198+
exists(ArrayExpr array, Node arrayType, Node host |
199+
contextualType(array, arrayType) and
200+
typeMemberHostReaches(host, arrayType) and
201+
typeMember(host, any(DataFlow::Content c | c.isUnknownArrayElement()), type) and
202+
value = array.getAnElement()
203+
)
204+
}
205+
206+
/**
207+
* Holds if `value` has the given `type`.
208+
*/
209+
predicate valueHasType(Node value, Node type) {
210+
value.(BindingPattern).getTypeAnnotation() = type
211+
or
212+
exists(VarDecl decl |
213+
// ValueFlow::step is restricted to variables with at most one assignment. Allow the type annotation
214+
// of a variable to propagate to its uses, even if the variable has multiple assignments.
215+
type = decl.getTypeAnnotation() and
216+
value = decl.getVariable().(LocalVariable).getAnAccess()
217+
)
218+
or
219+
exists(MemberDeclaration member |
220+
value.(ThisExpr).getBindingContainer() = member.getInit() and
221+
type = getMemberBase(member)
222+
)
223+
or
224+
exists(ClassDefinition cls |
225+
value = cls and
226+
type = cls.getVariable()
227+
)
228+
or
229+
exists(FunctionDeclStmt fun |
230+
value = fun and
231+
type = fun.getVariable()
232+
)
233+
or
234+
exists(Function target | callTarget(value, target) |
235+
type = target.getReturnTypeAnnotation()
236+
or
237+
exists(ClassDefinition cls |
238+
target = cls.getConstructor().getBody() and
239+
type = cls
240+
)
241+
)
242+
or
243+
// Contextual typing for parameters
244+
exists(Function lambda, Function functionType, int i |
245+
contextualType(lambda, trackFunctionType(functionType))
246+
or
247+
exists(InterfaceDefinition interface |
248+
contextualType(lambda, trackType(interface)) and
249+
functionType = interface.getACallSignature().getBody()
250+
)
251+
|
252+
value = lambda.getParameter(i) and
253+
not exists(value.(Parameter).getTypeAnnotation()) and
254+
type = functionType.getParameter(i).getTypeAnnotation()
255+
)
256+
or
257+
exists(Node mid | valueHasType(mid, type) | ValueFlow::step(mid, value))
258+
or
259+
exists(Node mid, Node midType, DataFlow::ContentSet contents, Node host |
260+
valueReadStep(mid, contents, value) and
261+
valueHasType(mid, midType) and
262+
typeMemberHostReaches(host, midType) and
263+
typeMember(host, contents.getAReadContent(), type)
264+
)
265+
}
266+
267+
signature predicate nodeSig(Node node);
268+
269+
/**
270+
* Tracks types that have a certain property, in the sense that:
271+
* - an intersection type has the property if any member has the property
272+
* - a union type has the property if all its members have the property
273+
*/
274+
module TrackMustProp<nodeSig/1 directlyHasProperty> {
275+
predicate hasProperty(Node node) {
276+
directlyHasProperty(node)
277+
or
278+
exists(Node mid |
279+
hasProperty(mid) and
280+
TypeFlow::step(mid, node)
281+
)
282+
or
283+
unionHasProp(node)
284+
or
285+
hasProperty(node.(IntersectionTypeExpr).getAnElementType())
286+
or
287+
exists(ConditionalTypeExpr cond |
288+
node = cond and
289+
hasProperty(cond.getTrueType()) and
290+
hasProperty(cond.getFalseType())
291+
)
292+
}
293+
294+
private predicate unionHasProp(UnionTypeExpr node, int n) {
295+
hasProperty(node.getElementType(0)) and n = 1
296+
or
297+
unionHasProp(node, n - 1) and
298+
hasProperty(node.getElementType(n - 1))
299+
}
300+
301+
private predicate unionHasProp(UnionTypeExpr node) {
302+
unionHasProp(node, node.getNumElementType())
303+
}
304+
}
305+
306+
module ValueHasProperty<nodeSig/1 typeHasProperty> {
307+
predicate valueHasProperty(Node value) {
308+
exists(Node type |
309+
valueHasType(value, type) and
310+
typeHasProperty(type)
311+
)
312+
}
313+
}
314+
315+
private predicate isSanitizingPrimitiveTypeBase(Node node) {
316+
node.(TypeExpr).isNumbery()
317+
or
318+
node.(TypeExpr).isBooleany()
319+
or
320+
node.(TypeExpr).isNull()
321+
or
322+
node.(TypeExpr).isUndefined()
323+
or
324+
node.(TypeExpr).isVoid()
325+
or
326+
node.(TypeExpr).isNever()
327+
or
328+
node instanceof LiteralTypeExpr
329+
or
330+
node = any(EnumMember m).getIdentifier() // enum members are constant
331+
or
332+
node instanceof EnumDeclaration // enums are unions of constants
333+
}
334+
335+
/**
336+
* Holds if `node` refers to a type that is considered untaintable (if actually enforced at runtime).
337+
*
338+
* Specifically, the types `number`, `boolean`, `null`, `undefined`, `void`, `never`, as well as literal types (`"foo"`)
339+
* and enums and enum members have this property.
340+
*/
341+
predicate isSanitizingPrimitiveType =
342+
TrackMustProp<isSanitizingPrimitiveTypeBase/1>::hasProperty/1;
343+
344+
/**
345+
* Holds if `value` has a type that is considered untaintable (if actually enforced at runtime).
346+
*
347+
* See `isSanitizingPrimitiveType`.
348+
*/
349+
predicate valueHasSanitizingPrimitiveType =
350+
ValueHasProperty<isSanitizingPrimitiveType/1>::valueHasProperty/1;
351+
352+
private predicate isPromiseBase(Node node) { exists(unwrapPromiseType(node)) }
353+
354+
/**
355+
* Holds if the given type is a Promise object. Does not hold for unions unless all parts of the union are promises.
356+
*/
357+
predicate isPromiseType = TrackMustProp<isPromiseBase/1>::hasProperty/1;
358+
359+
/**
360+
* Holds if the given value has a type that implied it is a Promise object. Does not hold for unions unless all parts of the union are promises.
361+
*/
362+
predicate valueHasPromiseType = ValueHasProperty<isPromiseType/1>::valueHasProperty/1;
363+
364+
/**
365+
* Holds if `type` contains `string` or `any`, possibly wrapped in a promise.
366+
*/
367+
predicate hasUnderlyingStringOrAnyType(Node type) {
368+
type.(TypeAnnotation).isStringy()
369+
or
370+
type.(TypeAnnotation).isAny()
371+
or
372+
type instanceof StringLiteralTypeExpr
373+
or
374+
type instanceof TemplateLiteralTypeExpr
375+
or
376+
exists(Node mid | hasUnderlyingStringOrAnyType(mid) |
377+
TypeFlow::step(mid, type)
378+
or
379+
UnderlyingTypes::underlyingTypeStep(mid, type)
380+
or
381+
type = unwrapPromiseType(mid)
382+
)
383+
}
384+
}

0 commit comments

Comments
 (0)