deslop 0.2.0

A static analyzer that spots low-context and AI-assisted code patterns across naming, concurrency, security, performance, and test quality.
Documentation
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use super::*;

pub(crate) fn flask_handler_findings(file: &ParsedFile, function: &ParsedFunction) -> Vec<Finding> {
    if function.is_test_function || !has_import(file, "flask") {
        return Vec::new();
    }
    let body = &function.body_text;
    let sig = &function.signature_text;
    let is_view = sig.contains("@app.route") || sig.contains("@bp.route");
    let mut findings = Vec::new();

    if is_view {
        let get_json_count =
            body.matches("request.get_json()").count() + body.matches("request.json").count();
        if get_json_count >= 2
            && let Some(line) = find_line(body, "request.get_json", function.fingerprint.start_line)
                .or_else(|| find_line(body, "request.json", function.fingerprint.start_line))
        {
            findings.push(make_finding(
                "flask_request_body_parsed_multiple_times",
                Severity::Info,
                file,
                function,
                line,
                "parses request body multiple times; cache in a local variable",
            ));
        }
    }

    if is_view {
        for pattern in &[
            "sqlite3.connect(",
            "pymongo.MongoClient(",
            "psycopg2.connect(",
            "mysql.connector.connect(",
        ] {
            if body.contains(pattern)
                && let Some(line) = find_line(body, pattern, function.fingerprint.start_line)
            {
                findings.push(make_finding(
                    "flask_global_db_connection_per_request",
                    Severity::Warning,
                    file,
                    function,
                    line,
                    "creates a database connection per request; use app-scoped connection pooling",
                ));
            }
        }
    }

    if is_view && body.contains("app.config[") {
        let config_count = body.matches("app.config[").count();
        if config_count >= 2
            && let Some(line) = find_line(body, "app.config[", function.fingerprint.start_line)
        {
            findings.push(make_finding(
                "flask_app_config_read_per_request",
                Severity::Info,
                file,
                function,
                line,
                "reads app.config multiple times per request; read once at startup",
            ));
        }
    }

    if is_view
        && body.contains("render_template_string(")
        && let Some(line) = find_line(
            body,
            "render_template_string(",
            function.fingerprint.start_line,
        )
    {
        findings.push(make_finding(
            "flask_template_rendered_from_string_in_view",
            Severity::Info,
            file,
            function,
            line,
            "renders template from string in view; use render_template() with a file instead",
        ));
    }

    if is_view
        && (body.contains("open(") || body.contains(".read_text()"))
        && let Some(line) = find_line(body, "open(", function.fingerprint.start_line)
            .or_else(|| find_line(body, ".read_text()", function.fingerprint.start_line))
    {
        findings.push(make_finding(
            "flask_file_read_per_request",
            Severity::Info,
            file,
            function,
            line,
            "reads a file per request; consider caching static content at startup",
        ));
    }

    if body.contains("app.run(")
        && body.contains("debug=True")
        && let Some(line) = find_line(body, "debug=True", function.fingerprint.start_line)
    {
        findings.push(make_finding(
            "flask_debug_mode_in_production_code",
            Severity::Warning,
            file,
            function,
            line,
            "runs app with debug=True which exposes the debugger in production",
        ));
    }

    if is_view
        && body.contains("JSONEncoder(")
        && let Some(line) = find_line(body, "JSONEncoder(", function.fingerprint.start_line)
    {
        findings.push(make_finding(
            "flask_json_encoder_per_request",
            Severity::Info,
            file,
            function,
            line,
            "creates JSONEncoder per request; configure app-level encoder instead",
        ));
    }

    if is_view && (body.contains("jsonify(") || body.contains("json.dumps(")) {
        let has_large_build = body.contains("for ")
            && (body.contains(".append(") || body.contains("results.extend("));
        if has_large_build
            && let Some(line) = find_line(body, "jsonify(", function.fingerprint.start_line)
                .or_else(|| find_line(body, "json.dumps(", function.fingerprint.start_line))
        {
            findings.push(make_finding(
                "flask_no_streaming_for_large_response",
                Severity::Info,
                file,
                function,
                line,
                "builds a large list then serializes; consider Response(generate(), ...) for streaming",
            ));
        }
    }

    findings
}

pub(crate) fn fastapi_handler_findings(
    file: &ParsedFile,
    function: &ParsedFunction,
) -> Vec<Finding> {
    if function.is_test_function || !has_import(file, "fastapi") {
        return Vec::new();
    }
    let body = &function.body_text;
    let sig = &function.signature_text;
    let python = function.python_evidence();
    let mut findings = Vec::new();

    let is_route = sig.contains("@router.") || sig.contains("@app.");
    if is_route && !python.is_async {
        let has_blocking = body.contains("requests.get(")
            || body.contains("requests.post(")
            || body.contains("open(")
            || body.contains("time.sleep(")
            || body.contains("subprocess.");
        if has_blocking {
            findings.push(make_finding(
                "fastapi_sync_def_with_blocking_io",
                Severity::Warning,
                file,
                function,
                function.fingerprint.start_line,
                "sync def route handler contains blocking I/O; use async def or run_in_executor",
            ));
        }
    }

    if sig.contains("Depends") || function.fingerprint.name.starts_with("get_") {
        let creates_client = body.contains("httpx.Client(")
            || body.contains("httpx.AsyncClient(")
            || body.contains("requests.Session(")
            || body.contains("aiohttp.ClientSession(");
        if creates_client
            && let Some(line) = find_line(body, "Client(", function.fingerprint.start_line)
                .or_else(|| find_line(body, "Session(", function.fingerprint.start_line))
        {
            findings.push(make_finding(
                "fastapi_dependency_creates_client_per_request",
                Severity::Warning,
                file,
                function,
                line,
                "creates HTTP client per request in dependency; use app lifespan",
            ));
        }
    }

    if body.contains("add_task(")
        && body.contains("BackgroundTask")
        && let Some(line) = find_line(body, "add_task(", function.fingerprint.start_line)
    {
        findings.push(make_finding(
            "fastapi_background_task_exception_silent",
            Severity::Info,
            file,
            function,
            line,
            "background task may silently swallow exceptions; add error handling",
        ));
    }

    findings
}

pub(crate) fn middleware_findings(file: &ParsedFile, function: &ParsedFunction) -> Vec<Finding> {
    if function.is_test_function || !is_middleware(function) {
        return Vec::new();
    }
    let body = &function.body_text;
    let mut findings = Vec::new();

    for pattern in &[
        "requests.Session(",
        "httpx.Client(",
        "aiohttp.ClientSession(",
    ] {
        if body.contains(pattern)
            && let Some(line) = find_line(body, pattern, function.fingerprint.start_line)
        {
            findings.push(make_finding(
                "middleware_creates_http_client_per_request",
                Severity::Warning,
                file,
                function,
                line,
                "creates HTTP client per request in middleware; use app-scoped client",
            ));
        }
    }

    for pattern in &[
        "yaml.safe_load(",
        "json.load(",
        "toml.load(",
        "configparser.",
    ] {
        if body.contains(pattern)
            && let Some(line) = find_line(body, pattern, function.fingerprint.start_line)
        {
            findings.push(make_finding(
                "middleware_loads_config_file_per_request",
                Severity::Info,
                file,
                function,
                line,
                "loads config per request in middleware; read once at startup",
            ));
        }
    }

    if body.contains("re.compile(")
        && let Some(line) = find_line(body, "re.compile(", function.fingerprint.start_line)
    {
        findings.push(make_finding(
            "middleware_compiles_regex_per_request",
            Severity::Info,
            file,
            function,
            line,
            "compiles regex per request in middleware; precompile at module level",
        ));
    }

    findings
}

pub(crate) fn handler_fanout_findings(
    file: &ParsedFile,
    function: &ParsedFunction,
) -> Vec<Finding> {
    if function.is_test_function || !is_handler_or_view(function, file) {
        return Vec::new();
    }
    let body = &function.body_text;
    let mut findings = Vec::new();

    let lines: Vec<&str> = body.lines().collect();
    let mut loop_indent: Option<usize> = None;
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("for ") && trimmed.ends_with(':') {
            loop_indent = Some(indent_level(line));
            continue;
        }
        if let Some(li) = loop_indent
            && !trimmed.is_empty()
            && indent_level(line) <= li
            && !trimmed.starts_with('#')
        {
            loop_indent = None;
        }
        if loop_indent.is_some()
            && !trimmed.is_empty()
            && (trimmed.contains("requests.get(")
                || trimmed.contains("requests.post(")
                || trimmed.contains("httpx.get(")
                || trimmed.contains("httpx.post(")
                || trimmed.contains("aiohttp"))
        {
            findings.push(make_finding(
                "upstream_http_call_per_item_in_handler",
                Severity::Warning,
                file,
                function,
                function.fingerprint.start_line + i,
                "makes sequential HTTP calls inside a loop in handler; batch or parallelize",
            ));
        }
    }

    for call in &function.calls {
        if (call.name == "get"
            || call.name == "post"
            || call.name == "put"
            || call.name == "delete"
            || call.name == "request")
            && call.receiver.as_deref() == Some("requests")
        {
            let call_line_text = body
                .lines()
                .nth(call.line.saturating_sub(function.fingerprint.start_line));
            if let Some(lt) = call_line_text
                && !lt.contains("timeout")
            {
                findings.push(make_finding(
                    "upstream_call_without_timeout_in_handler",
                    Severity::Warning,
                    file,
                    function,
                    call.line,
                    "HTTP call without timeout in handler; add timeout= to prevent unbounded latency",
                ));
            }
        }
    }

    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if trimmed.contains(".json()") || trimmed.contains("json.loads(response") {
            let has_check = (i.saturating_sub(3)..i).any(|j| {
                let prev = lines.get(j).unwrap_or(&"").trim();
                prev.contains("status_code")
                    || prev.contains(".ok")
                    || prev.contains("raise_for_status")
            });
            if !has_check {
                findings.push(make_finding(
                    "upstream_response_not_checked_before_decode",
                    Severity::Info,
                    file,
                    function,
                    function.fingerprint.start_line + i,
                    "decodes response without checking status; check response.ok or status_code first",
                ));
            }
        }
    }

    findings
}

pub(crate) fn template_response_findings(
    file: &ParsedFile,
    function: &ParsedFunction,
) -> Vec<Finding> {
    if function.is_test_function {
        return Vec::new();
    }
    let body = &function.body_text;
    let mut findings = Vec::new();

    let lines: Vec<&str> = body.lines().collect();
    let mut loop_indent: Option<usize> = None;
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("for ") && trimmed.ends_with(':') {
            loop_indent = Some(indent_level(line));
            continue;
        }
        if let Some(li) = loop_indent
            && !trimmed.is_empty()
            && indent_level(line) <= li
            && !trimmed.starts_with('#')
        {
            loop_indent = None;
        }
        if loop_indent.is_some() && !trimmed.is_empty() {
            if trimmed.contains("Template(") && trimmed.contains(".render(") {
                findings.push(make_finding(
                    "template_render_in_loop",
                    Severity::Info,
                    file,
                    function,
                    function.fingerprint.start_line + i,
                    "renders a template inside a loop; render once with loop data",
                ));
            }
            if trimmed.contains("render_template_string(") {
                findings.push(make_finding(
                    "template_render_in_loop",
                    Severity::Info,
                    file,
                    function,
                    function.fingerprint.start_line + i,
                    "renders template string inside a loop; use a single template",
                ));
            }
        }
    }

    if body.contains("json.dumps(")
        && body.contains("Response(")
        && (has_import(file, "flask") || has_import(file, "fastapi"))
        && let Some(line) = find_line(body, "json.dumps(", function.fingerprint.start_line)
    {
        findings.push(make_finding(
            "response_json_dumps_then_response_object",
            Severity::Info,
            file,
            function,
            line,
            "manually dumps JSON then wraps in Response; use jsonify() or JSONResponse()",
        ));
    }

    findings
}

pub(crate) fn response_extra_findings(
    file: &ParsedFile,
    function: &ParsedFunction,
) -> Vec<Finding> {
    if function.is_test_function {
        return Vec::new();
    }
    let body = &function.body_text;
    let mut findings = Vec::new();

    if is_handler_or_view(function, file)
        && (body.contains("jsonify(")
            || body.contains("JSONResponse(")
            || body.contains("json.dumps("))
    {
        let dict_key_count = body
            .lines()
            .filter(|l| {
                let t = l.trim();
                (t.contains("\": ") || t.contains("': ")) && !t.starts_with('#')
            })
            .count();
        if dict_key_count >= 8
            && let Some(line) = find_line(body, "jsonify(", function.fingerprint.start_line)
                .or_else(|| find_line(body, "JSONResponse(", function.fingerprint.start_line))
                .or_else(|| find_line(body, "json.dumps(", function.fingerprint.start_line))
        {
            findings.push(make_finding(
                "large_dict_literal_response_in_handler",
                Severity::Info,
                file,
                function,
                line,
                "builds a large inline dict for response; consider a Pydantic model or typed response",
            ));
        }
    }

    if has_import(file, "fastapi")
        && body.contains("response_model")
        && body.contains(".from_orm(")
        && !body.contains("model_config")
        && !body.contains("orm_mode")
        && let Some(line) = find_line(body, ".from_orm(", function.fingerprint.start_line)
    {
        findings.push(make_finding(
            "fastapi_response_model_without_orm_mode",
            Severity::Info,
            file,
            function,
            line,
            "uses .from_orm() without orm_mode; configure model_config for ORM compatibility",
        ));
    }

    findings
}