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
50 QUESTIONS
TABLE OF CONTENTS
# TOPIC
1 Configure and interpret Flake8 plugins for security-relevant linting (bandit, flake8-bugbear,
flake8-annotations)
2 Identify and remediate Python vulnerabilities such as injection, insecure deserialization, and weak
cryptography
3 Design structured logging and error handling that avoids sensitive data leakage while preserving
auditability
4 Apply testing strategies (unit, integration, property-based, fuzz) to validate security controls and
remediations
5 Integrate static analysis into CI/CD pipelines with policy-as-code and risk-based triage
6 WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python Security
7 Logging
8 Testing & Remediation 2026
9 Foundations of Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging,
Testing & Remediation
10 Applied Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing &
Remediation
11 Advanced Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing
& Remediation
12 Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing &
Remediation Review
ABSTRACT
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b

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

50 QUESTIONS

TABLE OF CONTENTS

# TOPIC 1 Configure and interpret Flake8 plugins for security-relevant linting (bandit, flake8-bugbear, flake8-annotations) 2 Identify and remediate Python vulnerabilities such as injection, insecure deserialization, and weak cryptography 3 Design structured logging and error handling that avoids sensitive data leakage while preserving auditability 4 Apply testing strategies (unit, integration, property-based, fuzz) to validate security controls and remediations 5 Integrate static analysis into CI/CD pipelines with policy-as-code and risk-based triage 6 WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python Security 7 Logging 8 Testing & Remediation 2026 9 Foundations of Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing & Remediation 10 Applied Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing & Remediation 11 Advanced Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing & Remediation 12 Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing & Remediation Review

ABSTRACT

This study document brings together 50 carefully worded exam questions drawn from WGU D Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python Security, Logging, Testing & Remediation 2026, with the strongest emphasis placed on Configure and interpret Flake8 plugins for security-relevant linting (bandit, flake8-bugbear, flake8-annotations), Identify and remediate Python vulnerabilities such as injection, insecure deserialization, and weak cryptography and Design structured logging and error handling that avoids sensitive data leakage while preserving auditability. Every item follows the wording style and level of reasoning you meet in the real paper, and each one is paired with a clear rationale so the correct choice is never a guess. Work through the set at your own pace, mark the questions that slow you down, then come back to them until the reasoning feels automatic. Learners who revise this way walk into the exam room recognising the pattern behind the questions instead of meeting them for the first time. Keep going - steady, honest practice is what turns a difficult paper into a comfortable pass.

Q1 CONFIGURE AND INTERPRET FLAKE8 PLUGINS FOR SECURITY-RELEVANT LINTING

(BANDIT, FLAKE8-BUGBEAR, FLAKE8-ANNOTATIONS)

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. CORRECT 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.

Q4 CONFIGURE AND INTERPRET FLAKE8 PLUGINS FOR SECURITY-RELEVANT LINTING

(BANDIT, FLAKE8-BUGBEAR, FLAKE8-ANNOTATIONS)

A developer uses logging.info(f"User {user} logged in with password

{password}"). What is the most critical security flaw?

A. Using f-strings instead of %-formatting causes performance overhead. B. Logging at INFO level may be disabled in production. C. Sensitive credentials are written to logs, risking exposure. CORRECT D. The log message lacks a timestamp and correlation ID. 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.

Q5 CONFIGURE AND INTERPRET FLAKE8 PLUGINS FOR SECURITY-RELEVANT LINTING

(BANDIT, FLAKE8-BUGBEAR, FLAKE8-ANNOTATIONS)

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 CORRECT 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.

Q6 IDENTIFY AND REMEDIATE PYTHON VULNERABILITIES SUCH AS INJECTION, INSECURE

DESERIALIZATION, AND WEAK CRYPTOGRAPHY

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. CORRECT 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.

Q7 IDENTIFY AND REMEDIATE PYTHON VULNERABILITIES SUCH AS INJECTION, INSECURE

DESERIALIZATION, AND WEAK CRYPTOGRAPHY

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()) CORRECT 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.

Q10 IDENTIFY AND REMEDIATE PYTHON VULNERABILITIES SUCH AS INJECTION,

INSECURE DESERIALIZATION, AND WEAK CRYPTOGRAPHY

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. CORRECT D. Add # nosec to suppress the warning. 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.

Q11 DESIGN STRUCTURED LOGGING AND ERROR HANDLING THAT AVOIDS SENSITIVE

DATA LEAKAGE WHILE PRESERVING AUDITABILITY

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. CORRECT 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.

Q12 DESIGN STRUCTURED LOGGING AND ERROR HANDLING THAT AVOIDS SENSITIVE

DATA LEAKAGE WHILE PRESERVING AUDITABILITY

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. CORRECT 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.

Q13 DESIGN STRUCTURED LOGGING AND ERROR HANDLING THAT AVOIDS SENSITIVE

DATA LEAKAGE WHILE PRESERVING AUDITABILITY

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) CORRECT C. assert fn(-1) is None D. monkeypatch.setattr(sys, 'exit', lambda code: None) then call fn(-1) RATIONALE: The intended contract is ValueError, so pytest.raises(ValueError) encodes that expectation and will fail until the code is remediated. pytest.raises(SystemExit) merely asserts the buggy behavior, and monkeypatching sys.exit hides the defect rather than testing the contract.

Q16 APPLY TESTING STRATEGIES (UNIT, INTEGRATION, PROPERTY-BASED, FUZZ) TO

VALIDATE SECURITY CONTROLS AND REMEDIATIONS

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. CORRECT 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.

Q17 APPLY TESTING STRATEGIES (UNIT, INTEGRATION, PROPERTY-BASED, FUZZ) TO

VALIDATE SECURITY CONTROLS AND REMEDIATIONS

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. CORRECT 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.

Q18 APPLY TESTING STRATEGIES (UNIT, INTEGRATION, PROPERTY-BASED, FUZZ) TO

VALIDATE SECURITY CONTROLS AND REMEDIATIONS

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 CORRECT C. patch('requests') D. patch.object(requests, 'get', autospec=True) RATIONALE: 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.

Q19 INTEGRATE STATIC ANALYSIS INTO CI/CD PIPELINES WITH POLICY-AS-CODE AND

RISK-BASED TRIAGE

A CI pipeline runs pip-audit and reports a vulnerable transitive dependency. The

team cannot upgrade it directly. Which remediation best reduces risk while

preserving functionality?

A. Pin the vulnerable version and add it to an allowlist. B. Add a constraints file overriding the transitive version to a patched release and re-run tests. CORRECT C. Vendor the vulnerable package source into the repo unchanged. D. Disable pip-audit for transitive dependencies. RATIONALE: A constraints file forces a patched transitive version without altering direct dependencies, and re-running tests verifies compatibility. Pinning or allowlisting the vulnerable version, vendoring unchanged code, or disabling the audit all preserve the vulnerability.

Q22 INTEGRATE STATIC ANALYSIS INTO CI/CD PIPELINES WITH POLICY-AS-CODE AND

RISK-BASED TRIAGE

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,)). CORRECT 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.

Q23 WGU D385 SOFTWARE SECURITY AND TESTING STATIC CODE ANALYSIS & FLAKE

PRACTICE LAB PYTHON SECURITY

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. CORRECT 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. RATIONALE: 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.

Q24 WGU D385 SOFTWARE SECURITY AND TESTING STATIC CODE ANALYSIS & FLAKE

PRACTICE LAB PYTHON SECURITY

A logging configuration sets logging.basicConfig(level=logging.INFO) and a

module calls logging.getLogger(__name__).debug("token=%s", token). What is

the most significant security concern, and what is the correct remediation?

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. CORRECT 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.

Q25 WGU D385 SOFTWARE SECURITY AND TESTING STATIC CODE ANALYSIS & FLAKE

PRACTICE LAB PYTHON SECURITY

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. CORRECT 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.

Q28 LOGGING

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. CORRECT 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.

Q29 LOGGING

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. CORRECT 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.

Q30 LOGGING

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. CORRECT 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.

Q31 TESTING & REMEDIATION 2026

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. CORRECT C. Enable E722; it flags bare except clauses, which is a pycodestyle error and therefore security-critical. D. Enable B110; it flags try-except-pass blocks, which is the only pattern that hides exceptions. RATIONALE: flake8-bugbear's B001 flags bare except: clauses; catching everything can hide security-relevant exceptions and suppress logging. B902 is about blind except in certain contexts, E722 is pycodestyle (style, not security-critical), and B110 targets try-except-pass specifically, not all bare excepts.

Q34 TESTING & REMEDIATION 2026

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. CORRECT 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. RATIONALE: 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.

Q35 FOUNDATIONS OF SOFTWARE SECURITY AND TESTING: STATIC CODE ANALYSIS,

FLAKE8, PYTHON SECURITY, LOGGING, TESTING & REMEDIATION

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. CORRECT D. Log the password only when DEBUG=True and disable logging in production. RATIONALE: 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.

Q36 FOUNDATIONS OF SOFTWARE SECURITY AND TESTING: STATIC CODE ANALYSIS,

FLAKE8, PYTHON SECURITY, LOGGING, TESTING & REMEDIATION

A requirements.txt pins requests==2.19.0, which has CVE-2018-

(credential leak on redirect). Which command best identifies this and similar

vulnerable dependencies in CI?

A. pip install safety && safety check CORRECT B. flake8 --select=S C. bandit -r . D. pytest --cov RATIONALE: Safety checks installed dependencies against a vulnerability database and would flag requests 2.19.0. Flake8 and Bandit analyze source code, not dependency CVEs, and pytest--cov measures test coverage, not vulnerabilities.

Q37 FOUNDATIONS OF SOFTWARE SECURITY AND TESTING: STATIC CODE ANALYSIS,

FLAKE8, PYTHON SECURITY, LOGGING, TESTING & REMEDIATION

When remediating a pickle.loads call flagged by Bandit (B301), which

replacement best maintains functionality for untrusted data while eliminating

arbitrary code execution?

A. Use pickle.loads(data, fix_imports=False). B. Use json.loads(data) if the data structure is JSON-compatible; otherwise use a safe serializer like defusedxml for XML. CORRECT C. Use yaml.load(data, Loader=yaml.FullLoader). D. Use pickle.Unpickler with a restricted find_class. RATIONALE: JSON parsing is safe for JSON-compatible data; defusedxml handles XML securely. pickle.loads with fix_imports still executes arbitrary code, yaml.FullLoader is unsafe, and a restricted Unpickler is complex and error-prone.