




















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!





















47 QUESTIONS
1 Configure and interpret Flake8 static analysis to identify Python security and style violations
2 Apply secure coding principles to remediate common vulnerabilities in Python applications
3 Design and evaluate logging and testing strategies that support security monitoring and defect detection
4 WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python Security
5 Logging
6 Testing & Remediation 2026
7 Foundations of Software Security and Testing: Static Code Analysis, Flake8 Practice Lab, Python Security, Logging, Testing & Remediation
8 Applied Software Security and Testing: Static Code Analysis, Flake8 Practice Lab, Python Security, Logging, Testing & Remediation
9 Advanced Software Security and Testing: Static Code Analysis, Flake8 Practice Lab, Python Security, Logging, Testing & Remediation
10 Software Security and Testing: Static Code Analysis, Flake8 Practice Lab, Python Security, Logging, Testing & Remediation Review
This study document brings together 47 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 static analysis to identify Python security and style violations, Apply secure coding principles to remediate common vulnerabilities in Python applications and Design and evaluate logging and testing strategies that support security monitoring and defect detection. 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.
A. flake8-bandit (B602) CORRECT
B. flake8-bugbear (B008)
C. flake8-comprehensions (C400)
D. flake8-import-order (I100)
RATIONALE: flake8-bandit wraps Bandit checks, and B602 specifically flags subprocess calls with shell=True, which is a command injection risk. flake8-bugbear, flake8-comprehensions, and flake8-import-order target style, performance, and import ordering, not command injection.
A. The pickle data is received over TLS from a trusted internal service and integrity is verified with HMAC. CORRECT
B. The pickle data is base64-encoded before deserialization.
C. The code runs in a container with a read-only filesystem.
D. The pickle module is imported from the standard library.
RATIONALE: Pickle deserialization is dangerous when untrusted data is involved; a trusted source with TLS and HMAC integrity verification reduces the risk. Base64 encoding, read-only filesystems, and standard-library origin do not mitigate arbitrary code execution during deserialization.
A. After using the token once, a second request with the same token returns 400 and the token is absent from the datastore. CORRECT
B. The token is a UUID4 string and its length is 36 characters.
C. The token is generated using secrets.token_urlsafe and includes at least 32 bytes of entropy.
D. The token is stored in the database with a creation timestamp.
RATIONALE: The core security property is one-time use, so the test must confirm rejection on reuse and removal from storage. Entropy, format, and timestamp storage are relevant to generation and auditing but do not prove invalidation after use.
A. Log injection via unsanitized user input in log messages CORRECT
B. Log rotation causing file descriptor exhaustion
C. Syslog UDP packet loss under high load
D. FileHandler not flushing on process exit
RATIONALE: Unsanitized user input can forge log entries or inject control characters, leading to misleading audits or terminal exploits. Rotation, UDP loss, and flushing affect reliability, not confidentiality or integrity of log content.
A. Replace with render_template using a fixed template file and pass the parameter as a variable. CORRECT
B. Escape the parameter with markupsafe.escape before concatenation.
C. Restrict the endpoint to authenticated users only.
D. Validate the parameter against a whitelist of allowed characters.
RATIONALE: Using a fixed template and passing data as context prevents template injection because user input is never compiled as template code. Escaping, authentication, and whitelisting reduce but do not eliminate the risk of template evaluation.
A. Run flake8 with --select=S and the flake8-bandit plugin installed. CORRECT
B. Run flake8 with --ignore=E,W and rely on default plugins.
C. Run flake8 with --max-complexity=10 and --statistics.
D. Run flake8 with --exit-zero and parse the output for security codes.
RATIONALE: The S prefix is used by flake8-bandit security checks; selecting only S fails the build on security violations. Ignoring E/W still includes many non-security checks, max-complexity is not security-specific, and --exit-zero never fails the build.
A. Assertions are removed when Python runs with -O, so validation should use explicit if not condition: raise ValueError. CORRECT
B. Assertions are slower than if statements, so they should be replaced with try/except blocks.
C. Assertions cannot check complex conditions, so they should be replaced with regular expressions.
D. Assertions are not thread-safe, so they should be replaced with locks.
RATIONALE: The -O flag strips assertions, disabling validation and potentially allowing invalid input. Replacing with explicit exceptions ensures validation persists. Performance, complexity, and thread safety are not the primary security concerns here.
A. Wrap user_input in shlex.quote before concatenation and keep shell=True.
B. Replace shell=True with a list of arguments and set shell=False, passing user_input as a separate list element. CORRECT
C. Encode user_input with base64 before concatenation and decode it inside the subprocess.
D. Set the environment variable PYTHONWARNINGS=error and re-run the command through os.system.
RATIONALE: Passing arguments as a list with shell=False bypasses the shell parser entirely, so metacharacters in user_input cannot spawn additional commands. shlex.quote reduces but does not eliminate risk when shell=True and is easy to misuse. Base64 encoding is not a security control, and os.system with PYTHONWARNINGS does nothing to prevent injection.
A. Switch to yaml.safe_load, which restricts to a safe subset of tags and blocks python/object constructors. CORRECT
B. Keep FullLoader but wrap the call in try/except and log exceptions.
C. Replace yaml.load with json.loads, since JSON is a strict subset of YAML.
D. Pass Loader=yaml.UnsafeLoader and validate the parsed dict against a schema afterward.
RATIONALE: yaml.safe_load uses SafeLoader, which excludes python/object, python/module, and similar constructors that enable code execution. FullLoader still permits some risky tags, so it is not the safest choice. json.loads rejects valid YAML constructs, and UnsafeLoader is explicitly the most dangerous option.
A. Replace it with assert response.ok to cover all 2xx responses.
B. Add negative tests asserting that unauthenticated and under-privileged requests receive 401/403, and that responses do not leak sensitive headers. CORRECT
C. Increase the assertion timeout to 30 seconds to reduce flakiness.
D. Move the assertion into a fixture so it runs before the request is sent.
RATIONALE: Security testing requires verifying both that legitimate access succeeds and that unauthorized access fails without information leakage. Positive-only assertions miss broken access control. The other options alter assertion style or timing but do not add negative security coverage.
A. hashlib.sha256 with a static application-wide salt.
B. bcrypt with a per-user random salt and an appropriate work factor, or argon2id. CORRECT
C. A single SHA-512 pass with a pepper stored in the same database.
D. HMAC-SHA256 keyed with a secret embedded in the source code.
RATIONALE: Password storage requires a memory-hard or adaptive KDF such as bcrypt, scrypt, or argon2id with per-user salts to resist GPU and rainbow-table attacks. Plain SHA-256/512 and MD5 are fast and unsuitable. Static salts, embedded peppers, and HMAC with source-embedded keys do not provide adequate protection.
A. Wrap pickle.loads in a try/except and log failures.
B. Replace pickle with a safe format such as JSON or MessagePack with strict schema validation, or use a signed, HMAC-verified token. CORRECT
C. Restrict pickle to a whitelist of classes via a custom Unpickler that still allows reduce.
D. Compress the payload with zlib before unpickling to obscure the contents.
RATIONALE: Pickle is inherently unsafe for untrusted data because reduce can execute arbitrary code; the robust fix is a non-executable format with schema validation or authenticated serialization. Custom Unpicklers that still permit reduce remain exploitable. Logging or compression does not remove the vulnerability.
A. Raise the threshold to 30 so the build passes and document the change.
B. Add a # noqa: C901 comment to suppress the warning on that function.
C. Refactor the function into smaller, single-responsibility units and add targeted tests for each branch, including error paths. CORRECT
D. Move the function to a separate module so flake8 does not scan it.
RATIONALE: High cyclomatic complexity correlates with untested branches and latent bugs, including security-relevant error paths. Refactoring and adding branch-level tests addresses the root cause. Raising thresholds, noqa suppression, and module relocation hide the signal without improving code quality or security.
A. The cast is sufficient; bandit B608 is a false positive whenever any type coercion precedes the query.
B. String formatting into SQL is structurally unsafe regardless of casting, so the query should be rebuilt with a parameterized cursor (e.g., execute(sql, (user_id,))). CORRECT
C. B608 can be suppressed with # nosec because int casting eliminates injection.
D. The fix is to escape quotes with user_id.replace("'", "''") before formatting.
RATIONALE: Parameterized queries separate code from data at the driver layer, which is the only structural guarantee against SQL injection; a preceding cast is fragile because future refactors may remove it, and bandit's B608 correctly flags string-built SQL. Options A and C mistake a local coercion for a structural control, and D relies on brittle manual escaping that fails across DBMS dialects and encodings.
A. Using pytest.raises inside a parametrized test is unsupported and silently skips cases.
B. A single assertion context cannot distinguish which parameter set failed, so failures lose granularity. CORRECT
C. pytest.raises cannot be combined with parametrize without pytest-asyncio.
D. The test will always pass because pytest.raises swallows assertion errors from the validator.
RATIONALE: Parametrization is fully compatible with pytest.raises; the real weakness is that bundling many cases into one test reduces failure localization unless each case is its own parametrized invocation. A and C are false claims about pytest capabilities, and D misstates what pytest.raises catches.
A. Quote the filename with shlex.quote and keep shell=True.
B. Validate the filename against a regex allowlist before passing it to the shell.
C. Replace shell=True with an argument list (shell=False) so the OS execs the binary directly without shell interpretation. CORRECT
D. Set env={"PATH": "/usr/bin"} to limit which binaries can be invoked.
RATIONALE: Removing the shell eliminates metacharacter interpretation entirely, which is the structural fix for command injection. A and B are mitigations that can be bypassed by encoding or edge cases, and D restricts PATH but does not stop argument injection into the invoked program.
A. None; the mutable-default problem is fully resolved.
B. items or [] replaces any falsy caller value (e.g., an empty list) with a new list, silently discarding caller identity. CORRECT
C. None defaults are disallowed by bugbear and trigger B008 instead.
D. The function now raises TypeError when called without arguments.
RATIONALE: Using or conflates None with other falsy inputs, so a caller passing an empty list gets a different object, breaking identity or mutation expectations. The correct idiom is if items is None: items = []. A overstates the fix, C misattributes bugbear codes, and D is factually wrong.
A. Log the raw credential at WARNING and rely on log-file permissions for protection.
B. Log a salted HMAC of the credential keyed by a server-side secret, plus a request ID. CORRECT
C. Log the credential's length and first character to aid debugging.
D. Log the credential only when the environment variable DEBUG is set.
RATIONALE: A keyed HMAC yields a stable, non-reversible correlation token that cannot be brute-forced without the server key, enabling correlation without disclosure. A and D leak secrets under misconfiguration, and C leaks partial credential material that narrows brute-force search.
A. Environment variables cannot be read by Python's os.environ in containers.
B. The secret may be captured in image layers, process listings, or crash dumps, and lacks rotation and access auditing. CORRECT
C. Environment variables are encrypted at rest by the container runtime by default.
D. Reading env vars at import time guarantees the value is immutable and safe.
RATIONALE: Moving a secret to an env var removes it from source but exposes it via process inspection, image metadata, and dumps, and does not provide rotation or auditability; a secrets manager addresses those gaps. A is false, C is false (env vars are not encrypted at rest by default), and D confuses immutability with confidentiality.
A. Wrap the statement in a try/except and log the exception instead of executing it.
B. Replace the % formatting with a parameterized query: cur.execute("SELECT * FROM users WHERE id = %s", (user_id,)). CORRECT
C. Escape single quotes in user_id with user_id.replace("'", "''") before formatting.
D. Add # nosec to the line to suppress the Bandit rule.
RATIONALE: Bandit's B608 flags string-formatted SQL because it enables injection; parameterized queries let the DB driver handle quoting and binding, removing the taint path. Escaping quotes is incomplete (numeric/edge cases) and # nosec only hides the defect, not fixes it.
A. Flake8 ignores max-complexity when running under Python 3.11+.
B. The complexity check requires the mccabe plugin and the setting must be under [flake8], not [tool.flake8], unless using a plugin that reads it. CORRECT
C. Cyclomatic complexity is only computed for classes, not functions.
D. max-complexity must be expressed as a float, e.g., 8.0.
RATIONALE: Flake8 natively reads [flake8] in setup.cfg/tox.ini or .flake8; [tool.flake8] in pyproject.toml requires flake8-pyproject (or similar) to be installed. Without that adapter, the max-complexity setting is silently ignored.
A. Use caplog fixture with propagate=False to capture records.
B. Monkeypatch logging.basicConfig with a no-op before import, or refactor to configure logging in an entry point rather than at import. CORRECT
C. Set logging.disable(logging.CRITICAL) in conftest.py.
D. Assert on logging.root.level instead of handler count.
RATIONALE: Import-time logging configuration mutates global state; the robust fix is to defer configuration to the application entry point or patch the call during tests. caplog captures records but does not prevent handler mutation, and disabling logging masks rather than isolates the side effect.
A. Add a comment # do not log next to the variable.
B. Implement a __repr__/__str__ on a wrapper class that returns a redacted placeholder, and use that wrapper for sensitive values. CORRECT
C. Rely on flake8 to flag any logging call referencing the variable.
D. Set the logger level to WARNING so INFO logs are suppressed.
RATIONALE: Encapsulating secrets in a type whose repr/str is redacted prevents leakage regardless of where it is logged or formatted. Comments are non-enforcing, flake8 has no taint analysis for this, and raising the log level only suppresses some calls.
A. Move all assertions into a single test function without parametrize.
B. Mark the slow tests with @pytest.mark.slow and run them in a separate CI stage using pytest -m 'not slow' for fast feedback. CORRECT
C. Replace pytest with unittest to reduce collection overhead.
D. Set --maxfail=1 to stop after the first failure.
RATIONALE: Splitting slow tests into a marker-based stage preserves coverage while giving fast feedback on the critical path. Merging assertions reduces granularity, switching frameworks does not address runtime, and --maxfail changes failure reporting, not speed.
A. Assert that a valid token with alg=HS256 is accepted.
B. Craft a token with header {"alg":"none"} and empty signature, then assert the verifier raises an exception and does not return claims. CORRECT
C. Assert that the JWT library version is pinned in requirements.txt.
D. Assert that the token contains an exp claim.
RATIONALE: The alg=none attack requires explicitly testing an unsigned token to confirm rejection; this directly exercises the verifier's algorithm allowlist. Accepting a valid token, pinning versions, and checking claims do not demonstrate mitigation of the none-algorithm bypass.
A. Add # noqa: E501 to the offending line. CORRECT
B. Set max-line-length = 200 in the flake8 config.
C. Add E501 to the ignore list.
D. Convert the docstring to a comment.
RATIONALE: # noqa: E501 suppresses only that line's specific violation, preserving enforcement elsewhere. Raising max-line-length or ignoring E501 globally weakens the rule, and converting the docstring is a stylistic change that does not address the rule.