|
| 1 | +/** |
| 2 | + * @name Missing await |
| 3 | + * @description Using a promise without awaiting its result can lead to unexpected behavior. |
| 4 | + * @kind problem |
| 5 | + * @problem.severity warning |
| 6 | + * @id js/missing-await |
| 7 | + * @tags correctness |
| 8 | + * @precision high |
| 9 | + */ |
| 10 | + |
| 11 | +import javascript |
| 12 | + |
| 13 | +/** |
| 14 | + * Holds if `call` is a call to an `async` function. |
| 15 | + */ |
| 16 | +predicate isAsyncCall(DataFlow::CallNode call) { |
| 17 | + // If a callee is known, and all known callees are async, assume all |
| 18 | + // possible callees are async. |
| 19 | + forex(Function callee | call.getACallee() = callee | callee.isAsync()) |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Holds if `node` is always a promise. |
| 24 | + */ |
| 25 | +predicate isPromise(DataFlow::SourceNode node, boolean nullable) { |
| 26 | + isAsyncCall(node) and |
| 27 | + nullable = false |
| 28 | + or |
| 29 | + not isAsyncCall(node) and |
| 30 | + node.asExpr().getType() instanceof PromiseType and |
| 31 | + nullable = true |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Holds the result of `e` is used in a way that doesn't make sense for Promise objects. |
| 36 | + */ |
| 37 | +predicate isBadPromiseContext(Expr expr) { |
| 38 | + exists(BinaryExpr binary | |
| 39 | + expr = binary.getAnOperand() and |
| 40 | + not binary instanceof LogicalExpr and |
| 41 | + not binary instanceof InstanceofExpr |
| 42 | + ) |
| 43 | + or |
| 44 | + expr = any(LogicalBinaryExpr e).getLeftOperand() |
| 45 | + or |
| 46 | + expr = any(UnaryExpr e).getOperand() |
| 47 | + or |
| 48 | + expr = any(UpdateExpr e).getOperand() |
| 49 | + or |
| 50 | + expr = any(ConditionalExpr e).getCondition() |
| 51 | + or |
| 52 | + expr = any(IfStmt stmt).getCondition() |
| 53 | + or |
| 54 | + expr = any(ForInStmt stmt).getIterationDomain() |
| 55 | + or |
| 56 | + expr = any(IndexExpr e).getIndex() |
| 57 | +} |
| 58 | + |
| 59 | +string tryGetPromiseExplanation(Expr e) { |
| 60 | + result = "The value '" + e.(VarAccess).getName() + "' is always a promise." |
| 61 | + or |
| 62 | + result = "The call to '" + e.(CallExpr).getCalleeName() + "' always returns a promise." |
| 63 | +} |
| 64 | + |
| 65 | +string getPromiseExplanation(Expr e) { |
| 66 | + result = tryGetPromiseExplanation(e) |
| 67 | + or |
| 68 | + not exists(tryGetPromiseExplanation(e)) and |
| 69 | + result = "This value is always a promise." |
| 70 | +} |
| 71 | + |
| 72 | +from Expr expr, boolean nullable |
| 73 | +where |
| 74 | + isBadPromiseContext(expr) and |
| 75 | + isPromise(expr.flow().getImmediatePredecessor*(), nullable) and |
| 76 | + ( |
| 77 | + nullable = false |
| 78 | + or |
| 79 | + expr.inNullSensitiveContext() |
| 80 | + ) |
| 81 | +select expr, "Missing await. " + getPromiseExplanation(expr) |
0 commit comments