


























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



























WGU D385 Software Security and Testing Static | Comprehensive Examination WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python Security, Logging, Testing & Remediation 2026 actual exam preparation
This document is an important and very helpful preparation resource for WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python Security, Logging, Testing & Remediation 2026. Every item uses a focused exam stem, four response options, a keyed response, and a clear rationale, making it easier to understand the subject, spot distractors, and build real exam confidence.
Question 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.
RATIONALE 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.
Question 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.
RATIONALE Logging passwords is a severe data leakage vulnerability. Performance (A) and log level (B) are secondary; missing metadata (D) is an audit concern, not the primary flaw.
Question 5
Which testing approach is most effective for uncovering edge cases in a
function that parses untrusted input?
A. Unit tests with mocked inputs B. Property-based testing with Hypothesis C. Integration tests with a real database D. Manual exploratory testing
RATIONALE Property-based testing generates diverse inputs to find edge cases. Unit tests (A) may miss unexpected inputs; integration tests (C) focus on system interaction; manual testing (D) is not systematic.
Question 6
A flake8 report shows F401 'module imported but unused' for the
'cryptography' module. What is the best remediation?
A. Remove the import if truly unused. B. Add # noqa: F401 to suppress the warning. C. Use the module in a dummy function to avoid the warning. D. Move the import inside a function.
RATIONALE Unused imports should be removed to reduce attack surface and improve clarity. Suppression (B) or dummy usage (C) hides the issue; moving the import (D) doesn't resolve unused status.
Question 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())
RATIONALE 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.
Question 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.
RATIONALE 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.
Question 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.
RATIONALE 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.
Question 12
A logging configuration sets a root logger at WARNING and a module logger
at DEBUG, but DEBUG records from that module never appear. Which
explanation is most consistent with Python's logging hierarchy?
A. The module logger's effective level is overridden by the root handler's level filter. B. The module logger lacks a handler and propagates to root, whose handler level is WARNING. C. DEBUG records are dropped at creation because the root logger is set to WARNING. D. The module logger must be set to NOTSET for DEBUG to be emitted.
RATIONALE A child logger with no handler propagates records to ancestor handlers; the root handler's level (WARNING) then filters DEBUG records. Logger levels and handler levels are independent, so the effective level alone does not explain the drop, and NOTSET is not required.
Question 13
A test asserts that a function raises ValueError for negative input, but the
function currently calls sys.exit(1). Which pytest construct most precisely
verifies the intended contract without allowing the process to terminate the test
runner?
A. with pytest.raises(SystemExit): fn(-1) B. with pytest.raises(ValueError): fn(-1) C. assert fn(-1) is None D. monkeypatch.setattr(sys, 'exit', lambda code: None) then call fn(-1)
E203/W503 conflicts. C. Disable black's line-length check in CI. D. Add '# noqa' to every line black reformats.
RATIONALE 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.
Question 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.
RATIONALE 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.
Question 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.
RATIONALE 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.
Question 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)
D. Run the command as a non-root user with shell=True.
RATIONALE Passing an argument list with shell=False avoids shell interpretation entirely, eliminating injection. Escaping or quoting is error-prone and incomplete, and dropping privileges reduces impact but not the vulnerability itself.
Question 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.
RATIONALE Bandit's B110/B112 checks flag bare or overly broad exception handling as a security-relevant weakness, whereas pycodestyle's E 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: E722 does not require a raise, both tools parse source/AST rather than bytecode, and E722 applies to Python 3 as well.
Question 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.
RATIONALE 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.
A. The debug call is silently dropped at INFO level, so no risk exists; no remediation needed. B. The token is formatted eagerly and may leak if the root level is later raised to DEBUG; the fix is to never log secrets and to use structured redaction or omit the token entirely. C. Using %s formatting is unsafe; the fix is to use f-strings so the token is evaluated lazily. D. The __name__ logger bypasses the root handler, so the message will always be emitted regardless of level.
RATIONALE The lazy %s argument is only formatted when the record is emitted, but if any environment raises the effective level to DEBUG the secret is written to logs; secrets should never be passed to logging at all, and redaction or omission is the correct fix. Option A ignores configuration drift, C inverts the laziness tradeoff (f-strings evaluate eagerly), and D misstates logger propagation.
Question 25
A CI pipeline runs bandit -r src/ -f json and fails the build on any HIGH
severity finding. A developer argues that a # nosec comment is the correct fix
for a flagged subprocess.Popen(..., shell=True). Which response is most
defensible from a secure-SDLC standpoint?
A. Accept the # nosec because Bandit false-positives on subprocess by default. B. Replace shell=True with a list-form invocation, validate inputs against an allowlist, and only use # nosec with a documented justification if the risk is unavoidable. C. Lower the CI threshold to MEDIUM so the finding no longer fails the
build. D. Move the call into a separate module excluded from the Bandit scan path.
RATIONALE shell=True enables shell metacharacter injection, so the correct remediation is to avoid the shell and constrain inputs; suppression is a last resort requiring documented justification. Options A, C, and D all mask the finding rather than remediate it, violating secure-SDLC principles.
Question 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().
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.
RATIONALE 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.
Question 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.
RATIONALE SCA tools like pip-audit and safety query vulnerability databases against the resolved dependency set, which is the correct control for third-party CVEs. Flake8 plugins (A) analyze source style/security patterns, mypy (C) checks types, and coverage (D) measures test execution, none of which detect dependency CVEs.
Question 30
A developer must remediate a Bandit finding for assert used to enforce an
authorization invariant in production code. Why is this a genuine security
issue, and what is the appropriate fix?
A. Asserts are slow; replace them with logging statements. B. Asserts are stripped when Python runs with -O, so security-critical checks may vanish; replace with explicit if not condition: raise logic. C. Asserts raise the wrong exception type; replace with sys.exit(1). D. Asserts leak stack traces; wrap them in try/except.
RATIONALE Running with optimization (python -O) removes assert statements entirely, so using them for authorization or input validation can silently disable security controls in production; explicit conditionals that raise appropriate exceptions are the correct remediation. The other options misidentify the risk (performance, exception type, or trace leakage) and do not address the stripping behavior.
Question 31
A developer wants Flake8 to flag every bare except: clause as a
security-relevant error. Which plugin configuration correctly achieves this with
the flake8-bugbear plugin, and why does this matter for security?
A. Enable B902; it detects bare excepts and flags them as security issues because they swallow KeyboardInterrupt. B. Enable B001; it flags bare except clauses, since silently catching all exceptions can mask security-relevant failures and hide tracebacks from logging. C. Enable E722; it flags bare except clauses, which is a pycodestyle error