Docsity

WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python, Exams of Computer Security

Toggle sidebar
bg1
Page 1
WGU D385 Software Security and Testing Static Code Analysis
& Flake8 Practice Lab Python Security, Logging, Testing &
Remediation 2026 - Questions and Answers Already Graded A+
Premium Exam Tested And Verified
GRADED A+
ABSTRACT
This exam assesses advanced competency in static code analysis with Flake8, secure
Python coding, vulnerability remediation, structured logging, and rigorous software
testing practices aligned with modern DevSecOps and OWASP standards.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python and more Exams Computer Security in PDF only on Docsity!

WGU D385 Software Security and Testing Static Code Analysis

& Flake8 Practice Lab Python Security, Logging, Testing &

Remediation 2026 - Questions and Answers Already Graded A+

Premium Exam Tested And Verified

GRADED A+

ABSTRACT

This exam assesses advanced competency in static code analysis with Flake8, secure

Python coding, vulnerability remediation, structured logging, and rigorous software

testing practices aligned with modern DevSecOps and OWASP standards.

1. A flake8 run with the bandit plugin reports B301: pickle.loads() on untrusted data.

Which remediation best preserves functionality while eliminating the vulnerability?

A. Replace pickle with json and validate the schema with pydantic before use. B. Wrap pickle.loads in a try/except and log the exception. C. Use pickle.Unpickler with find_class restricted to a whitelist of safe classes. D. Enable Python's -X dev mode to catch deserialization errors.

Answer: C. Use pickle.Unpickler with find_class restricted to a whitelist of safe

classes.

Restricting find_class to a whitelist maintains pickle compatibility while blocking arbitrary code execution. JSON (A) may not support all types; try/except (B) does not prevent exploitation; -X dev (D) only adds runtime checks, not security.

2. In a CI pipeline, flake8 reports E501 line too long on a line containing a hardcoded

AWS secret. Which action best aligns with secure remediation and linting policy?

A. Add # noqa: E501 to suppress the warning and commit. B. Refactor the line and move the secret to an environment variable, then rotate the exposed key. C. Increase max-line-length in setup.cfg to 120. D. Use a pre-commit hook to auto-format with black.

Answer: B. Refactor the line and move the secret to an environment variable, then

rotate the exposed key.

The secret must be removed from source and rotated; refactoring addresses the lint issue. Suppression (A) or config change (C) hides the problem; auto-formatting (D) does not remove the secret.

3. Which flake8 plugin combination best detects both style and security issues in

Python code?

A. flake8-docstrings and flake8-import-order B. flake8-bugbear and flake8-comprehensions C. flake8-bandit and flake8-bugbear D. flake8-annotations and flake8-quotes

Answer: C. flake8-bandit and flake8-bugbear

flake8-bandit integrates Bandit security checks; flake8-bugbear catches likely bugs. The others focus on style, documentation, or import ordering, not security.

7. Which of the following is a secure way to handle password hashing in Python?

A. hashlib.md5(password.encode()).hexdigest() B. hashlib.sha256(password.encode()).hexdigest() C. bcrypt.hashpw(password.encode(), bcrypt.gensalt()) D. base64.b64encode(password.encode())

Answer: C. bcrypt.hashpw(password.encode(), bcrypt.gensalt())

bcrypt is designed for password hashing with salt and work factor. MD5 (A) and SHA-256 (B) are fast and unsuitable; base64 (D) is encoding, not hashing.

8. In a CI/CD pipeline, which strategy best balances security and developer

productivity when integrating static analysis?

A. Block all merges on any flake8 warning. B. Run flake8 only on changed files and fail on high-severity security issues. C. Run flake8 nightly and email reports. D. Disable flake8 and rely on code reviews.

Answer: B. Run flake8 only on changed files and fail on high-severity security

issues.

Incremental scanning with severity-based gating reduces noise while catching critical issues. Blocking all warnings (A) causes friction; nightly (C) delays feedback; disabling (D) removes automation.

9. Which Python logging practice best prevents log injection attacks?

A. Using f-strings to embed user input directly. B. Sanitizing user input before logging and using structured logging. C. Logging only at ERROR level. D. Storing logs in a database instead of files.

Answer: B. Sanitizing user input before logging and using structured logging.

Sanitization and structured logging prevent newline injection. F-strings (A) allow injection; log level (C) doesn't sanitize; database storage (D) doesn't prevent injection.

10. A flake8-bandit report flags B303: use of insecure MD5. Which remediation is

most appropriate?

A. Replace MD5 with SHA-1. B. Replace MD5 with SHA-256 for non-security checksums. C. Replace MD5 with SHA-256 or better for security-sensitive hashing. D. Add # nosec to suppress the warning.

Answer: C. Replace MD5 with SHA-256 or better for security-sensitive hashing.

For security, use SHA-256 or stronger. SHA-1 (A) is also broken; SHA-256 for non-security (B) is acceptable but not for security; suppression (D) ignores the risk.

11. In a Flake8 plugin, a developer implements a check that flags any call to eval()

as a security violation. Which AST traversal strategy most correctly ensures the

check fires for eval() invoked indirectly through an alias such as `from builtins

import eval as e`?

A. Match only ast.Call nodes whose func is an ast.Name with id 'eval'. B. Resolve the Name id through the module's import bindings before comparing it to the canonical builtin name. C. Use a regex over the raw source lines to detect the token 'eval('. D. Flag any ast.Call whose func is an ast.Attribute regardless of the attribute name.

Answer: B. Resolve the Name id through the module's import bindings before

comparing it to the canonical builtin name.

Aliasing rebinds the name, so matching only the literal id 'eval' misses aliased calls; resolving import bindings to the canonical builtin is required. Regex over source is brittle and ignores AST semantics, and flagging all Attribute calls produces massive false positives unrelated to eval.

14. Bandit reports B608 (possible SQL injection) for a query built with an f-string,

but the same query built with a parameterized placeholder is not flagged. Which

remediation most directly eliminates the vulnerability class rather than suppressing

the finding?

A. Add '# nosec' to the flagged line. B. Replace the f-string with cursor.execute('... WHERE id = %s', (user_id,)). C. Wrap the user_id in str() before interpolation. D. Configure Bandit to skip the B608 test.

Answer: B. Replace the f-string with cursor.execute('... WHERE id = %s',

(user_id,)).

Parameterized execution separates code from data, structurally preventing injection, which is the true remediation. Suppression via nosec or config, and string coercion, leave the injection vector intact.

15. A project's CI runs flake8 --max-line-length=79 and passes, yet black --check

fails. Which change most likely reconciles both tools without weakening linting?

A. Lower flake8's max-line-length to 88. B. Configure both tools to a shared line length and disable flake8's E203/W503 conflicts. C. Disable black's line-length check in CI. D. Add '# noqa' to every line black reformats.

Answer: B. Configure both tools to a shared line length and disable flake8's

E203/W503 conflicts.

Black and flake8 disagree on slice and whitespace conventions, so aligning line length and ignoring E203/W503 resolves the conflict without suppressing real issues. Lowering the limit or disabling black's check does not reconcile the tools and weakens enforcement.

16. A security review finds that a Flask app logs full request bodies, including

passwords. Which logging change best follows current OWASP guidance while

preserving useful diagnostics?

A. Log the body only when the log level is DEBUG. B. Redact or omit sensitive fields before logging, and log structured, non-sensitive metadata. C. Encrypt the log file at rest and continue logging the body. D. Log only the HTTP status code and drop all request context.

Answer: B. Redact or omit sensitive fields before logging, and log structured,

non-sensitive metadata.

OWASP recommends minimizing and redacting sensitive data at the point of logging; structured metadata preserves diagnostics without exposing secrets. Logging at DEBUG still persists secrets, encryption at rest does not prevent exposure to log readers, and dropping all context harms operability.

17. A developer uses assert to validate an authentication token in production code.

Under which condition does this create a security vulnerability?

A. When the token is a bytes object rather than a str. B. When Python is run with -O, which strips assert statements. C. When the assert uses '==' instead of 'is'. D. When the assert is inside a try/except block.

Answer: B. When Python is run with -O, which strips assert statements.

The -O flag removes assert statements, so authentication checks silently disappear in optimized builds, a classic vulnerability. The other options describe type or style issues that do not disable the check.

18. A test suite uses unittest.mock.patch on requests.get at the module level. A

new test imports the function directly (from requests import get) and the patch no

longer takes effect. Which patching target is correct?

A. patch('requests.get') B. patch('mymodule.get') where mymodule imported it C. patch('requests') D. patch.object(requests, 'get', autospec=True)

Answer: B. patch('mymodule.get') where mymodule imported it

Mock patches the name where it is looked up, so the module that imported get must be patched. Patching requests.get affects the original binding, not the local reference, and patching the module object is too broad.

21. A developer runs flake8 --select=E722 on a codebase and receives no warnings,

yet a subsequent Bandit scan reports a high-severity finding in the same file. Which

explanation best accounts for this discrepancy?

A. Flake8's E722 only fires when a bare except is followed by a raise statement, whereas Bandit flags all bare excepts. B. Bandit detects bare except: clauses as a security weakness (B110/B112 patterns), while Flake8's E722 requires a specific pycodestyle configuration and may be disabled by default in some setups or suppressed via noqa. C. Bandit only inspects compiled bytecode, so it detects exceptions that Flake8's AST-based parser cannot see. D. E722 applies exclusively to Python 2 syntax, so Python 3 code will never trigger it regardless of configuration.

Answer: B. Bandit detects bare except: clauses as a security weakness (B110/B

patterns), while Flake8's E722 requires a specific pycodestyle configuration and

may be disabled by default in some setups or suppressed via noqa.

Bandit's B110/B112 checks flag bare or overly broad exception handling as a security-relevant weakness, whereas pycodestyle's E722 is a style rule that can be disabled, overridden, or suppressed via # noqa, so a clean Flake8 run does not guarantee Bandit silence. Options A, C, and D misstate the semantics of each tool: E does not require a raise, both tools parse source/AST rather than bytecode, and E applies to Python 3 as well.

22. A Flask endpoint builds a SQL query with `cursor.execute("SELECT * FROM

users WHERE name = '%s'" % name)`. Which remediation most directly eliminates

the injection vector while preserving behavior?

A. Escape single quotes in name using name.replace("'", "''") before interpolation. B. Wrap the call in a try/except and log the exception. C. Replace string interpolation with a parameterized query: cursor.execute("SELECT * FROM users WHERE name = %s", (name,)). D. Switch the database driver to one that auto-sanitizes all string inputs.

Answer: C. Replace string interpolation with a parameterized query:

cursor.execute("SELECT * FROM users WHERE name = %s", (name,)).

Parameterized queries send the SQL structure and the data separately, so user input cannot alter the query's parse tree regardless of content. Manual escaping (A) is error-prone and driver-dependent, exception handling (B) does not prevent injection, and no mainstream driver (D) auto-sanitizes interpolated strings.

23. A team writes a pytest fixture that patches requests.get with

unittest.mock.patch to test a function that retries on HTTP 500. Which design most

rigorously verifies the retry behavior without coupling the test to implementation

details?

A. Assert that requests.get was called exactly three times using assert_called_with on the final call. B. Configure the mock's side_effect to return a 500 response twice and a 200 response once, then assert the function returns the parsed payload and that requests.get.call_count == 3. C. Patch time.sleep to a no-op and assert the function completes within a fixed wall-clock budget. D. Use pytest.mark.integration and hit a real endpoint that returns 500 to observe retries.

Answer: B. Configure the mock's side_effect to return a 500 response twice and a

200 response once, then assert the function returns the parsed payload and that

requests.get.call_count == 3.

Driving the mock with a side_effect sequence exercises the retry logic deterministically and asserts both the observable outcome (parsed payload) and the interaction (call count), which is the strongest contract-level check. Option A checks only the last call, C tests timing rather than retry semantics, and D introduces nondeterminism and external dependency.

26. A code review flags hashlib.md5(password.encode()).hexdigest() used for

storing credentials. Which replacement most correctly reflects current

password-storage guidance?

A. hashlib.sha256(password.encode()).hexdigest() with a fixed application salt. B. hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 600000) with a per-user random salt. C. base64.b64encode(password.encode()) to obfuscate the credential. D. hmac.new(secret_key, password.encode(), hashlib.md5).hexdigest().

Answer: B. hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 600000) with

a per-user random salt.

Current guidance (OWASP/NIST) requires a memory-hard or iterated KDF with a per-user random salt; PBKDF2-HMAC-SHA256 with a high iteration count satisfies this. SHA-256 alone (A) is fast and unsuitable for passwords, base64 (C) is encoding not hashing, and HMAC-MD5 (D) retains a broken hash primitive.

27. A test suite achieves 95% line coverage but misses a branch where an

authorization check returns False. Which testing technique most directly exposes

this gap?

A. Increasing the number of integration tests against a live database. B. Measuring branch/decision coverage and adding a test that forces the authorization check to evaluate False. C. Adding property-based tests that only generate valid inputs. D. Running mutation testing on unrelated modules to raise the overall score.

Answer: B. Measuring branch/decision coverage and adding a test that forces the

authorization check to evaluate False.

Line coverage can be satisfied while a branch outcome is never exercised; branch/decision coverage explicitly requires each outcome, and adding a False-path test closes the gap. Options A, C, and D do not guarantee the specific untested branch is executed.

28. A Python service loads YAML configuration with yaml.load(stream) from a

user-uploadable file. Which change most effectively prevents arbitrary code

execution?

A. Wrap the load in try/except to catch parse errors. B. Replace yaml.load with yaml.safe_load, which restricts construction to basic Python types. C. Validate the file extension is .yaml before loading. D. Run the loader in a thread pool to isolate failures.

Answer: B. Replace yaml.load with yaml.safe_load, which restricts construction

to basic Python types.

yaml.load with the default loader can instantiate arbitrary Python objects via tags like !!python/object, enabling code execution; yaml.safe_load disallows those constructors. Extension checks (C) are trivially bypassed, try/except (A) does not prevent execution, and thread isolation (D) does not sandbox code.

29. An audit requires that a Python package's dependencies be checked for known

CVEs as part of CI. Which tool and workflow best satisfies this requirement?

A. Run flake8 with the flake8-bandit plugin to detect vulnerable dependencies. B. Run pip-audit (or safety) against the locked requirements and fail the build on any reported CVE. C. Run mypy --strict to catch type errors that indicate vulnerabilities. D. Run pytest --cov and require 100% coverage before merging.

Answer: B. Run pip-audit (or safety) against the locked requirements and fail

the build on any reported CVE.

SCA tools like pip-audit and safety query vulnerability databases against the resolved dependency set, which is the correct control for third-party CVEs. Flake plugins (A) analyze source style/security patterns, mypy (C) checks types, and coverage (D) measures test execution, none of which detect dependency CVEs.

32. In a code review, you see subprocess.Popen(user_input, shell=True). Which

remediation preserves functionality while eliminating command injection, and what

does Bandit report?

A. Replace with subprocess.Popen(user_input.split(), shell=False); Bandit flags B (subprocess_popen_with_shell_equals_true). B. Escape user_input with shlex.quote and keep shell=True; Bandit flags B603. C. Replace with os.system(user_input); Bandit flags B605. D. Use subprocess.Popen([user_input], shell=False) without splitting; Bandit flags B (start_process_with_partial_path).

Answer: A. Replace with subprocess.Popen(user_input.split(), shell=False);

Bandit flags B602 (subprocess_popen_with_shell_equals_true).

Using shell=False with a list of arguments prevents shell interpretation; Bandit's B specifically flags subprocess calls with shell=True. Escaping still leaves shell=True (B602 remains), os.system is worse, and B607 concerns partial paths, not shell injection.

33. A test suite uses pytest with pytest-mock. The code under test calls

requests.get and then logs the response status. Which approach best isolates the test

from network while verifying logging behavior?

A. Use monkeypatch.setattr('requests.get', lambda url: Mock(status_code=200)) and assert on the logger's info call via caplog. B. Use mocker.patch('requests.get', return_value=Mock(status_code=200)) and assert caplog.records[0].status_code == 200. C. Use mocker.patch('requests.get', return_value=Mock(status_code=200)) and assert that the logger's info was called with the expected message using caplog.text. D. Use responses library to mock HTTP and assert that logging.getLogger().handlers contains a StreamHandler.

Answer: C. Use `mocker.patch('requests.get',

return_value=Mock(status_code=200))and assert that the logger'sinfo` was

called with the expected message using caplog.text.

mocker.patch cleanly replaces requests.get, and caplog.text captures emitted log messages for assertion; this verifies both isolation and logging. Option A uses monkeypatch but asserts on the wrong attribute; B incorrectly inspects record attributes not present; D tests handler configuration, not the log message.

34. Which statement accurately distinguishes static application security testing

(SAST) from dynamic application security testing (DAST) in a Python CI pipeline?

A. SAST analyzes running code and detects runtime injection; DAST scans source for insecure patterns like eval. B. SAST examines source or bytecode without execution and can catch insecure deserialization patterns; DAST probes a running application and can detect reflected XSS. C. SAST requires a deployed environment; DAST runs at commit time and is faster for Python. D. SAST and DAST are interchangeable for Python because both rely on Flake8 plugins.

Answer: B. SAST examines source or bytecode without execution and can catch

insecure deserialization patterns; DAST probes a running application and can

detect reflected XSS.

SAST inspects code without executing it (e.g., Bandit finding insecure deserialization), while DAST tests a live application (e.g., reflected XSS). A reverses the definitions, C misstates deployment needs, and D falsely equates them with Flake8 plugins.

35. A Python service logs `logger.info('User %s logged in with password %s',

username, password)`. Which remediation aligns with OWASP logging cheat sheet

and avoids sensitive data exposure?

A. Change level to debug and keep the password for troubleshooting. B. Hash the password with MD5 before logging to preserve traceability. C. Remove the password from the log message and log only the username and a success flag; ensure logs are not world-readable. D. Log the password only when DEBUG=True and disable logging in production.

Answer: C. Remove the password from the log message and log only the username

and a success flag; ensure logs are not world-readable.

OWASP advises never logging credentials; removing the password and restricting log permissions prevents exposure. Debug-level logging still leaks secrets, MD5 is insecure and unnecessary, and disabling logging entirely harms auditability.

38. A team wants to enforce that all new code passes Bandit with no HIGH severity

issues and Flake8 with max-complexity 10. Which CI configuration correctly

implements this gate?

A. Run bandit -r. -lll and flake8 --max-complexity=10; fail the build if either returns non-zero. B. Run bandit -r . and flake8; only warn on failures. C. Run bandit -r. -s B101 and flake8 --max-complexity=10; ignore HIGH issues. D. Run bandit -r. -ll and flake8; fail only on Bandit.

Answer: A. Run bandit -r. -lll and flake8 --max-complexity=10; fail the build if

either returns non-zero.

bandit -lll reports only HIGH severity issues, and --max-complexity=10 enforces the complexity limit; non-zero exit fails the build. Other options either warn instead of fail, ignore HIGH issues, or omit the complexity gate.

39. Which Python logging configuration correctly prevents log injection (CWE-117)

when logging user-supplied data?

A. Use logging.basicConfig(format='%(message)s') and log raw user input. B. Sanitize newline characters in user input before logging, and use structured logging (e.g., logger.info('user=%s', sanitized)). C. Set logging.raiseExceptions = False to suppress injection errors. D. Encode user input with base64 before logging.

Answer: B. Sanitize newline characters in user input before logging, and use

structured logging (e.g., logger.info('user=%s', sanitized)).

Sanitizing newlines and using parameterized structured logging prevents attackers from forging log entries. Raw logging enables injection, raiseExceptions=False hides errors, and base64 obscures but does not prevent injection.

40. In a Flask app, render_template_string('Hello ' + name) is flagged by Bandit

(B701). Which remediation eliminates SSTI while preserving dynamic content?

A. Use render_template_string('Hello {{ name }}', name=name). B. Escape name with html.escape and keep concatenation. C. Use render_template('hello.html', name=name) with a template file. D. Switch to string.Template('Hello $name').substitute(name=name).

Answer: C. Use render_template('hello.html', name=name) with a template file.

Using render_template with a static file separates code from data and prevents SSTI. Option A still uses render_template_string with user input, B only escapes HTML (SSTI persists), and D bypasses the template engine but may not fit Flask patterns.

41. A security engineer runs bandit -r src/ and receives B301 (pickle) findings on a

module that only ever deserializes data produced by the same process. Which

remediation best satisfies both Bandit and the principle of least privilege?

A. Add # nosec B301 to each flagged line and document the trust boundary in a code comment. B. Replace pickle with json.loads and validate the schema with a strict allow-list. C. Wrap the unpickling call in a try/except and log the exception at WARNING level. D. Move the unpickling into a separate process running as a low-privilege user.

Answer: B. Replace pickle with json.loads and validate the schema with a strict

allow-list.

Pickle deserialization is inherently unsafe because the byte stream can execute arbitrary code; the only robust fix is to avoid pickle for untrusted data and use a safe, schema-validated format such as JSON. Suppressing the finding with # nosec, catching exceptions, or sandboxing the process does not eliminate the code-execution primitive.