Skip to content

S308 (mark_safe) doesn't detects decorator usage and imports from another place #9780

@ashrub-holvi

Description

@ashrub-holvi

Hi, thank you for the cool project!

I am looking to suspicious-mark-safe-usage (S308) check. Here I see it's implemented, but something named "S703: django_mark_safe" is not, not sure what does it means, but looks like S308 works only if mark_safe is imported from django.utils.safestring and used as a function:

  1. With mark_safe used as a function:
from django.utils.safestring import SafeString
from django.utils.safestring import mark_safe

def some_func():
    return mark_safe('<script>alert("evil!")</script>')  # oh no

print(type(some_func()) is SafeString)

it works fine:

ruff --select S308 test.py 
test.py:7:12: S308 Use of `mark_safe` may expose cross-site scripting vulnerabilities
Found 1 error.
  1. With mark_safe used as a decorator:
from django.utils.safestring import SafeString
from django.utils.safestring import mark_safe

@mark_safe
def some_func():
    return '<script>alert("evil!")</script>'  # oh no

print(type(some_func()) is SafeString)

it doesn't raise the error:

ruff --select S308 test.py
  1. With function imported from django.utils.html, might be it's wrong way to import it, but it works and we have a lot of such usages in old code.
from django.utils.safestring import SafeString
from django.utils.html import mark_safe

def some_func():
    return mark_safe('<script>alert("evil!")</script>')  # oh no

print(type(some_func()) is SafeString)

there is no errors:

ruff --select S308 test.py
  1. With decorator imported from django.utils.html
from django.utils.safestring import SafeString
from django.utils.html import mark_safe

@mark_safe
def some_func():
    return '<script>alert("evil!")</script>'  # oh no

print(type(some_func()) is SafeString)

also no errors:

ruff --select S308 test.py

So, perhaps this check can be improved, I tried to looks to code, but for the first look I understand nothing ) Rust is only in far away future plan for me.

ruff --version
ruff 0.1.15

Metadata

Metadata

Assignees

Labels

ruleImplementing or modifying a lint rule

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions