Marco Borgeaud 8209548e54
Diff blocks: fix incorrect use for python (#2795)
Improvement identified in #2790.

Add a prefix to the diff-id when it is used multiple times in different
"how to fix it in XYZ" sections to avoid ambiguity and pedantically
follow the spec:

> A single and unique diff-id should be used only once for each type of
code example as shown in the description of a rule.

Obvious typos around `diff-type` were fixed.

An obvious extra use of diff blocks was removed.
2023-08-21 15:22:49 +02:00

50 lines
1.5 KiB
Plaintext

== How to fix it in Python Standard Library
=== Code examples
include::../../common/fix/code-rationale.adoc[]
Especially, in this example, if the *host* request parameter contains system
shell control characters, the expected `ping` command behavior will be changed.
==== Noncompliant code example
[source,python,diff-id=11,diff-type=noncompliant]
----
def ping():
cmd = "ping -c 1 %s" % request.args.get("host", "www.google.com")
status = os.system(cmd) # Noncompliant
return str(status == 0)
----
==== Compliant solution
[source,python,diff-id=11,diff-type=compliant]
----
def safe_ping():
host = request.args.get("host", "www.google.com")
status = subprocess.run(["ping", "-c", "1", "--", host]).returncode
return str(status == 0)
----
=== How does this work?
include::../../common/fix/introduction.adoc[]
include::../../common/fix/pre-approved-list.adoc[]
:sanitizationLib: subprocess
include::../../common/fix/sanitize-meta-characters.adoc[]
In the example compliant code, using the `subprocess.run` function helps to
escape the passed arguments. It accepts a list of command arguments that will
be properly escaped and concatenated to form the command line to execute.
include::../../common/fix/shell_integration.adoc[]
In the example compliant code, using the `subprocess` module's functions is
preferred over older alternative as the `os` or `popen` modules. Indeed,
`subprocess`, while still a dangerous library, disables the system shell's
syntax interpretation by default.