|
| 1 | +use std::ops::Deref; |
| 2 | + |
| 3 | +use oxc_diagnostics::{LabeledSpan, OxcDiagnostic}; |
| 4 | +use oxc_macros::declare_oxc_lint; |
| 5 | +use oxc_span::{CompactStr, Span}; |
| 6 | +use serde_json::Value; |
| 7 | + |
| 8 | +use crate::{context::LintContext, rule::Rule, utils, AstNode}; |
| 9 | +use oxc_ast::{ |
| 10 | + ast::{Argument, ArrowFunctionExpression, Expression, Function}, |
| 11 | + AstKind, |
| 12 | +}; |
| 13 | + |
| 14 | +#[derive(Debug, Default, Clone)] |
| 15 | +pub struct NoAsyncEndpointHandlers(Box<NoAsyncEndpointHandlersConfig>); |
| 16 | +impl Deref for NoAsyncEndpointHandlers { |
| 17 | + type Target = NoAsyncEndpointHandlersConfig; |
| 18 | + |
| 19 | + fn deref(&self) -> &Self::Target { |
| 20 | + &self.0 |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +#[derive(Debug, Default, Clone)] |
| 25 | +pub struct NoAsyncEndpointHandlersConfig { |
| 26 | + allowed_names: Vec<CompactStr>, |
| 27 | +} |
| 28 | + |
| 29 | +pub fn no_async_handlers( |
| 30 | + function_span: Span, |
| 31 | + registered_span: Option<Span>, |
| 32 | + name: Option<&str>, |
| 33 | +) -> OxcDiagnostic { |
| 34 | + #[allow(clippy::cast_possible_truncation)] |
| 35 | + const ASYNC_LEN: u32 = "async".len() as u32; |
| 36 | + |
| 37 | + // Only cover "async" in "async function (req, res) {}" or "async (req, res) => {}" |
| 38 | + let async_span = Span::sized(function_span.start, ASYNC_LEN); |
| 39 | + |
| 40 | + let labels: &[LabeledSpan] = match (registered_span, name) { |
| 41 | + // handler is declared separately from registration |
| 42 | + // `async function foo(req, res) {}; app.get('/foo', foo);` |
| 43 | + (Some(span), Some(name)) => &[ |
| 44 | + async_span.label(format!("Async handler '{name}' is declared here")), |
| 45 | + span.primary_label("and is registered here"), |
| 46 | + ], |
| 47 | + // Shouldn't happen, since separate declaration/registration requires an |
| 48 | + // identifier to be bound |
| 49 | + (Some(span), None) => &[ |
| 50 | + async_span.label("Async handler is declared here"), |
| 51 | + span.primary_label("and is registered here"), |
| 52 | + ], |
| 53 | + // `app.get('/foo', async function foo(req, res) {});` |
| 54 | + (None, Some(name)) => &[async_span.label(format!("Async handler '{name}' is used here"))], |
| 55 | + |
| 56 | + // `app.get('/foo', async (req, res) => {});` |
| 57 | + (None, None) => &[async_span.label("Async handler is used here")], |
| 58 | + }; |
| 59 | + |
| 60 | + OxcDiagnostic::warn("Express endpoint handlers should not be async.") |
| 61 | + .with_labels(labels.iter().cloned()) |
| 62 | + .with_help("Express <= 4.x does not handle Promise rejections. Use `new Promise((resolve, reject) => { ... }).catch(next)` instead.") |
| 63 | +} |
| 64 | + |
| 65 | +declare_oxc_lint!( |
| 66 | + /// ### What it does |
| 67 | + /// |
| 68 | + /// Disallows the use of `async` functions as Express endpoint handlers. |
| 69 | + /// |
| 70 | + /// ### Why is this bad? |
| 71 | + /// |
| 72 | + /// Before v5, Express will not automatically handle Promise rejections from |
| 73 | + /// handler functions with your application's error handler. You must |
| 74 | + /// instead explicitly pass the rejected promise to `next()`. |
| 75 | + /// ```js |
| 76 | + /// const app = express() |
| 77 | + /// app.get('/', (req, res, next) => { |
| 78 | + /// new Promise((resolve, reject) => { |
| 79 | + /// return User.findById(req.params.id) |
| 80 | + /// }) |
| 81 | + /// .then(user => res.json(user)) |
| 82 | + /// .catch(next) |
| 83 | + /// }) |
| 84 | + /// ``` |
| 85 | + /// |
| 86 | + /// If this is not done, your server will crash with an unhandled promise |
| 87 | + /// rejection. |
| 88 | + /// ```js |
| 89 | + /// const app = express() |
| 90 | + /// app.get('/', async (req, res) => { |
| 91 | + /// // Server will crash if User.findById rejects |
| 92 | + /// const user = await User.findById(req.params.id) |
| 93 | + /// res.json(user) |
| 94 | + /// }) |
| 95 | + /// ``` |
| 96 | + /// |
| 97 | + /// See [Express' Error Handling |
| 98 | + /// Guide](https://expressjs.com/en/guide/error-handling.html) for more |
| 99 | + /// information. |
| 100 | + /// |
| 101 | + /// ### Examples |
| 102 | + /// |
| 103 | + /// Examples of **incorrect** code for this rule: |
| 104 | + /// ```js |
| 105 | + /// const app = express(); |
| 106 | + /// app.get('/', async (req, res) => { |
| 107 | + /// const user = await User.findById(req.params.id); |
| 108 | + /// res.json(user); |
| 109 | + /// }); |
| 110 | + /// |
| 111 | + /// const router = express.Router(); |
| 112 | + /// router.use(async (req, res, next) => { |
| 113 | + /// const user = await User.findById(req.params.id); |
| 114 | + /// req.user = user; |
| 115 | + /// next(); |
| 116 | + /// }); |
| 117 | + /// |
| 118 | + /// const createUser = async (req, res) => { |
| 119 | + /// const user = await User.create(req.body); |
| 120 | + /// res.json(user); |
| 121 | + /// } |
| 122 | + /// app.post('/user', createUser); |
| 123 | + /// |
| 124 | + /// // Async handlers that are imported will not be detected because each |
| 125 | + /// // file is checked in isolation. This does not trigger the rule, but still |
| 126 | + /// // violates it and _will_ result in server crashes. |
| 127 | + /// const asyncHandler = require('./asyncHandler'); |
| 128 | + /// app.get('/async', asyncHandler); |
| 129 | + /// ``` |
| 130 | + /// |
| 131 | + /// Examples of **correct** code for this rule: |
| 132 | + /// ```js |
| 133 | + /// const app = express(); |
| 134 | + /// // not async |
| 135 | + /// app.use((req, res, next) => { |
| 136 | + /// req.receivedAt = Date.now(); |
| 137 | + /// }) |
| 138 | + /// |
| 139 | + /// app.get('/', (req, res, next) => { |
| 140 | + /// fs.readFile('/file-does-not-exist', (err, data) => { |
| 141 | + /// if (err) { |
| 142 | + /// next(err) // Pass errors to Express. |
| 143 | + /// } else { |
| 144 | + /// res.send(data) |
| 145 | + /// } |
| 146 | + /// }) |
| 147 | + /// }) |
| 148 | + /// |
| 149 | + /// const asyncHandler = async (req, res) => { |
| 150 | + /// const user = await User.findById(req.params.id); |
| 151 | + /// res.json(user); |
| 152 | + /// } |
| 153 | + /// app.get('/user', (req, res, next) => asyncHandler(req, res).catch(next)) |
| 154 | + /// ``` |
| 155 | + /// |
| 156 | + /// ## Configuration |
| 157 | + /// |
| 158 | + /// This rule takes the following configuration: |
| 159 | + /// ```ts |
| 160 | + /// type NoAsyncEndpointHandlersConfig = { |
| 161 | + /// /** |
| 162 | + /// * An array of names that are allowed to be async. |
| 163 | + /// */ |
| 164 | + /// allowedNames?: string[]; |
| 165 | + /// } |
| 166 | + /// ``` |
| 167 | + NoAsyncEndpointHandlers, |
| 168 | + suspicious |
| 169 | +); |
| 170 | + |
| 171 | +impl Rule for NoAsyncEndpointHandlers { |
| 172 | + fn from_configuration(value: Value) -> Self { |
| 173 | + let mut allowed_names: Vec<CompactStr> = value |
| 174 | + .get(0) |
| 175 | + .and_then(Value::as_object) |
| 176 | + .and_then(|config| config.get("allowedNames")) |
| 177 | + .and_then(Value::as_array) |
| 178 | + .map(|names| names.iter().filter_map(Value::as_str).map(CompactStr::from).collect()) |
| 179 | + .unwrap_or_default(); |
| 180 | + allowed_names.sort_unstable(); |
| 181 | + allowed_names.dedup(); |
| 182 | + |
| 183 | + Self(Box::new(NoAsyncEndpointHandlersConfig { allowed_names })) |
| 184 | + } |
| 185 | + |
| 186 | + fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { |
| 187 | + let kind = node.kind(); |
| 188 | + let Some((_endpoint, args)) = utils::as_endpoint_registration(&kind) else { |
| 189 | + return; |
| 190 | + }; |
| 191 | + for arg in |
| 192 | + args.iter().filter_map(Argument::as_expression).map(Expression::get_inner_expression) |
| 193 | + { |
| 194 | + self.check_endpoint_arg(ctx, arg); |
| 195 | + } |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +impl NoAsyncEndpointHandlers { |
| 200 | + fn check_endpoint_arg<'a>(&self, ctx: &LintContext<'a>, arg: &Expression<'a>) { |
| 201 | + self.check_endpoint_expr(ctx, None, None, arg); |
| 202 | + } |
| 203 | + |
| 204 | + fn check_endpoint_expr<'a>( |
| 205 | + &self, |
| 206 | + ctx: &LintContext<'a>, |
| 207 | + id_name: Option<&str>, |
| 208 | + registered_at: Option<Span>, |
| 209 | + arg: &Expression<'a>, |
| 210 | + ) { |
| 211 | + match arg { |
| 212 | + Expression::Identifier(handler) => { |
| 213 | + // Unresolved reference? Nothing we can do. |
| 214 | + let Some(symbol_id) = handler |
| 215 | + .reference_id() |
| 216 | + .and_then(|id| ctx.symbols().get_reference(id).symbol_id()) |
| 217 | + else { |
| 218 | + return; |
| 219 | + }; |
| 220 | + |
| 221 | + // Cannot check imported handlers without cross-file analysis. |
| 222 | + let flags = ctx.symbols().get_flags(symbol_id); |
| 223 | + if flags.is_import() { |
| 224 | + return; |
| 225 | + } |
| 226 | + |
| 227 | + let decl_id = ctx.symbols().get_declaration(symbol_id); |
| 228 | + let decl_node = ctx.nodes().get_node(decl_id); |
| 229 | + let registered_at = registered_at.or(Some(handler.span)); |
| 230 | + match decl_node.kind() { |
| 231 | + AstKind::Function(f) => self.check_function(ctx, registered_at, id_name, f), |
| 232 | + AstKind::VariableDeclarator(decl) => { |
| 233 | + if let Some(init) = &decl.init { |
| 234 | + self.check_endpoint_expr(ctx, id_name, registered_at, init); |
| 235 | + } |
| 236 | + } |
| 237 | + _ => {} |
| 238 | + } |
| 239 | + } |
| 240 | + func if utils::is_endpoint_handler(func) => { |
| 241 | + match func { |
| 242 | + // `app.get('/', (async?) function (req, res) {}` |
| 243 | + Expression::FunctionExpression(f) => { |
| 244 | + self.check_function(ctx, registered_at, id_name, f); |
| 245 | + } |
| 246 | + Expression::ArrowFunctionExpression(f) => { |
| 247 | + self.check_arrow(ctx, registered_at, id_name, f); |
| 248 | + } |
| 249 | + _ => unreachable!(), |
| 250 | + } |
| 251 | + } |
| 252 | + _ => {} |
| 253 | + } |
| 254 | + } |
| 255 | + |
| 256 | + fn check_function<'a>( |
| 257 | + &self, |
| 258 | + ctx: &LintContext<'a>, |
| 259 | + registered_at: Option<Span>, |
| 260 | + id_name: Option<&str>, |
| 261 | + f: &Function<'a>, |
| 262 | + ) { |
| 263 | + if !f.r#async { |
| 264 | + return; |
| 265 | + } |
| 266 | + |
| 267 | + let name = f.name().map(|n| n.as_str()).or(id_name); |
| 268 | + if name.is_some_and(|name| self.is_allowed_name(name)) { |
| 269 | + return; |
| 270 | + } |
| 271 | + |
| 272 | + ctx.diagnostic(no_async_handlers(f.span, registered_at, name)); |
| 273 | + } |
| 274 | + |
| 275 | + fn check_arrow<'a>( |
| 276 | + &self, |
| 277 | + ctx: &LintContext<'a>, |
| 278 | + registered_at: Option<Span>, |
| 279 | + id_name: Option<&str>, |
| 280 | + f: &ArrowFunctionExpression<'a>, |
| 281 | + ) { |
| 282 | + if !f.r#async { |
| 283 | + return; |
| 284 | + } |
| 285 | + if id_name.is_some_and(|name| self.is_allowed_name(name)) { |
| 286 | + return; |
| 287 | + } |
| 288 | + |
| 289 | + ctx.diagnostic(no_async_handlers(f.span, registered_at, id_name)); |
| 290 | + } |
| 291 | + |
| 292 | + fn is_allowed_name(&self, name: &str) -> bool { |
| 293 | + self.allowed_names.binary_search_by(|allowed| allowed.as_str().cmp(name)).is_ok() |
| 294 | + } |
| 295 | +} |
| 296 | + |
| 297 | +#[test] |
| 298 | +fn test() { |
| 299 | + use crate::tester::Tester; |
| 300 | + use serde_json::json; |
| 301 | + |
| 302 | + let pass = vec![ |
| 303 | + ("app.get('/', fooController)", None), |
| 304 | + ("app.get('/', (req, res) => {})", None), |
| 305 | + ("app.get('/', (req, res) => {})", None), |
| 306 | + ("app.get('/', function (req, res) {})", None), |
| 307 | + ("app.get('/', middleware, function (req, res) {})", None), |
| 308 | + ("app.get('/', (req, res, next) => {})", None), |
| 309 | + ("app.get('/', (err, req, res, next) => {})", None), |
| 310 | + ("app.get('/', (err, req, res) => {})", None), |
| 311 | + ("app.get('/', (err, req, res) => {})", None), |
| 312 | + ("app.get('/', (req, res) => Promise.resolve())", None), |
| 313 | + ("app.get('/', (req, res) => new Promise((resolve, reject) => resolve()))", None), |
| 314 | + ("app.use(middleware)", None), |
| 315 | + ("app.get(middleware)", None), |
| 316 | + ( |
| 317 | + "function ctl(req, res) {} |
| 318 | + app.get(ctl)", |
| 319 | + None, |
| 320 | + ), |
| 321 | + ("weirdName.get('/', async () => {})", None), |
| 322 | + ("weirdName.get('/', async (notARequestObject) => {})", None), |
| 323 | + // allowed names |
| 324 | + ( |
| 325 | + "async function ctl(req, res) {} |
| 326 | + app.get(ctl)", |
| 327 | + Some(json!([ { "allowedNames": ["ctl"] } ])), |
| 328 | + ), |
| 329 | + ( |
| 330 | + " |
| 331 | + async function middleware(req, res, next) {} |
| 332 | + app.use(middleware) |
| 333 | + ", |
| 334 | + Some(json!([ { "allowedNames": ["middleware"] } ])), |
| 335 | + ), |
| 336 | + ]; |
| 337 | + |
| 338 | + let fail = vec![ |
| 339 | + ("app.get('/', async function (req, res) {})", None), |
| 340 | + ("app.get('/', async (req, res) => {})", None), |
| 341 | + ("app.get('/', async (req, res, next) => {})", None), |
| 342 | + ("weirdName.get('/', async (req, res) => {})", None), |
| 343 | + ("weirdName.get('/', async (req, res) => {})", None), |
| 344 | + ( |
| 345 | + " |
| 346 | + async function foo(req, res) {} |
| 347 | + app.post('/', foo) |
| 348 | + ", |
| 349 | + None, |
| 350 | + ), |
| 351 | + ( |
| 352 | + " |
| 353 | + const foo = async (req, res) => {} |
| 354 | + app.post('/', foo) |
| 355 | + ", |
| 356 | + None, |
| 357 | + ), |
| 358 | + ( |
| 359 | + " |
| 360 | + async function middleware(req, res, next) {} |
| 361 | + app.use(middleware) |
| 362 | + ", |
| 363 | + None, |
| 364 | + ), |
| 365 | + ( |
| 366 | + " |
| 367 | + async function foo(req, res) {} |
| 368 | + const bar = foo; |
| 369 | + app.post('/', bar) |
| 370 | + ", |
| 371 | + None, |
| 372 | + ), |
| 373 | + ]; |
| 374 | + |
| 375 | + Tester::new(NoAsyncEndpointHandlers::NAME, pass, fail).test_and_snapshot(); |
| 376 | +} |
0 commit comments