


























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 Task 1 Complete Practice Guide | Comprehensive Examination WGU D385 Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Python Logging, Assertions, Exception Handling & Remediation 2026 actual
This document is an important and very helpful preparation resource for WGU D385 Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Python Logging, Assertions, Exception Handling & 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 security engineer runs Bandit on a Python module and receives a B
warning for a SQL query constructed with string concatenation. Which
remediation most effectively eliminates the vulnerability while preserving
functionality?
A. Replace concatenation with an f-string using input validation. B. Use parameterized queries with a database driver that supports placeholders. C. Escape all single quotes in the user input before concatenation. D. Apply a web application firewall (WAF) rule to block SQL injection patterns.
RATIONALE Parameterized queries separate SQL logic from data, preventing injection regardless of input content. Escaping quotes or using f-strings with validation can be bypassed and do not address the root cause. A WAF is a defense-in-depth measure, not a remediation.
Question 2
In Python, which logging configuration best supports post-incident forensic
analysis while minimizing performance overhead in a high-throughput service?
A. Logging to a file with DEBUG level and immediate flush after each record. B. Using a RotatingFileHandler with a size limit and a WARNING level. C. Logging to syslog with a custom formatter that includes thread ID and timestamp. D. Asynchronous logging with a QueueHandler and a dedicated listener thread.
Question 4
A developer writes a custom exception class that inherits from Exception but
does not call super().init(). What is the most likely consequence when this
exception is raised and logged?
A. The exception message will be empty when str() is called on the instance. B. The exception will not be caught by except Exception clauses. C. The traceback will not include the original exception context. D. The exception will be automatically converted to a SystemExit.
RATIONALE Without calling super().init(), the base Exception class does not receive the message argument, so str(exception) returns an empty string. The exception is still catchable and traceback behavior is unaffected. It is not converted to SystemExit.
Question 5
During a static analysis review, a tool flags a potential path traversal in a file
upload handler. Which remediation strategy most directly addresses the
vulnerability at the source?
A. Sanitize the filename by removing all non-alphanumeric characters. B. Use a whitelist of allowed file extensions and store files outside the web root. C. Implement a Web Application Firewall (WAF) rule to block '../' sequences. D. Encode the filename using URL encoding before saving.
RATIONALE Storing files outside the web root and restricting extensions prevents traversal by design. Sanitizing by removing characters can break legitimate filenames and may still allow traversal. WAF and encoding are bypassable and do not fix the root cause.
Question 6
Which Python logging practice best supports the principle of least privilege
when handling sensitive data?
A. Log all user input at DEBUG level for troubleshooting. B. Use a filter to redact credit card numbers and passwords before logging. C. Store logs in a world-readable directory for easy access. D. Include full stack traces with local variables in error logs.
RATIONALE Redacting sensitive data via a logging filter prevents exposure while maintaining useful logs. Logging all input or including local variables can leak secrets. World-readable logs violate confidentiality.
Question 7
A team uses a static analysis tool that reports a high number of false positives.
What is the most effective approach to improve the signal-to-noise ratio
without missing critical vulnerabilities?
A. Disable all rules that produce false positives. B. Tune rule thresholds and add suppressions with justifications for known false positives. C. Only run the tool on changed files in pull requests. D. Replace the tool with a dynamic analysis tool.
the schema. C. Encrypt the pickled data before transmission. D. Add a digital signature to the pickled data and verify it before deserialization.
RATIONALE Pickle is inherently unsafe for untrusted data; using JSON with schema validation eliminates the risk. Restricted unpicklers are complex and error-prone. Encryption and signatures do not prevent malicious payloads if the key is compromised or the signature is not verified properly.
Question 10
Which of the following best describes the role of assertions in a secure
software development lifecycle?
A. Assertions should be used to enforce security invariants in production code. B. Assertions are primarily for internal consistency checks during development and testing. C. Assertions should replace exception handling for critical errors. D. Assertions are the preferred method for input validation in public APIs.
RATIONALE Assertions are designed for debugging and internal sanity checks, not for enforcing security in production because they can be disabled. They should not replace exception handling or input validation, which must always be active.
Question 11
A team runs Bandit on a module where `subprocess.Popen(user_input,
shell=False)` is flagged as B602. The developer insists there is no injection risk
because shell=False. Which analysis is most accurate?
A. Correct - shell=False fully neutralizes command injection regardless of input. B. Incorrect - with shell=False, a string command still executes via the shell on POSIX. C. Partially correct - shell=False prevents shell metacharacter injection but a single string is treated as an executable path, so an attacker-controlled string can still invoke an arbitrary binary if it resolves. D. Bandit B602 is a false positive by definition; shell=False is always safe.
RATIONALE With shell=False, Python does not invoke /bin/sh, so metacharacters like ; are not interpreted; however, passing a single string is treated as the program name, and attacker-controlled tokens can still select an unintended binary or argument. Bandit flags this as a latent risk. Option A overstates safety, B misstates shell behavior, and D is a blanket false claim.
Question 12
A logging configuration uses logging.basicConfig(level=logging.INFO) and
later a module calls logging.getLogger(__name__).debug('x'). Why does the
debug message not appear even though the module logger inherits from root?
A. Child loggers do not inherit level from root; they default to
Correct Answer: B - Replace with assert response.json().get('user', {}).get('id') == expected so a missing key yields a clean assertion diff.
RATIONALE Using .get chains converts a missing-key crash into a boolean assertion whose diff shows actual vs expected, preserving intent and diagnostics. Option A discards the value diff, C is unrelated to exceptions, and D weakens the assertion so it no longer verifies the id value.
Question 14
A service catches Exception at the top of main() and logs
logger.exception('failure'), then exits 0. Which security-relevant defect does
this introduce in a CI/CD pipeline?
A. None - logging the exception satisfies observability requirements. B. It masks failures as success, allowing a broken or partially compromised build to pass gates and deploy. C. It causes the exception traceback to be written to stdout instead of stderr, breaking log parsers. D. It prevents the exception from being logged because logger.exception requires an active handler.
RATIONALE Swallowing exceptions and exiting 0 hides failures from CI gates, which can promote insecure or broken artifacts. Option A ignores the exit-code regression, C misstates logger.exception output routing, and D is false since handlers are normally configured.
Question 15
A SAST tool reports a taint path from request.args['q'] to
cursor.execute('SELECT ... WHERE name = ' + q). The team argues
parameterization is unnecessary because they escape single quotes. Which
reasoning is correct?
A. Escaping single quotes is sufficient because SQL injection requires quote termination. B. Parameterization is required because escaping is dialect- and encoding-dependent and fails against numeric contexts, LIKE clauses, and second-order injection. C. Parameterization is only needed for INSERT/UPDATE, not SELECT. D. Escaping is equivalent to parameterization when using an ORM.
RATIONALE Manual escaping is fragile across dialects, character sets, and contexts (numeric, LIKE, ORDER BY), and does not prevent second-order injection; parameterization binds values out-of-band. Options A, C, and D each misstate the threat model or the equivalence claim.
Question 16
Which combination of Python assert misuse creates a security vulnerability in
production?
A. Using assert for type narrowing inside a function body. B. Using assert user.is_admin as an authorization gate, because assert statements are stripped when Python runs with -O. C. Using assert inside unit tests to validate outputs. D. Using assert to validate constant invariants at import time.
A. They are identical; both include the traceback. B. logger.exception() automatically includes the active exception traceback, while logger.error() includes it only if exc_info=True is passed. C. logger.error() includes the traceback; logger.exception() does not. D. Neither includes the traceback; traceback.print_exc() is required.
RATIONALE logger.exception is shorthand for logger.error(..., exc_info=True), capturing the traceback for forensic reconstruction. Options A, C, and D misstate this behavior and would degrade incident analysis.
Question 19
A SAST baseline is introduced mid-project. The team wants to prevent new
high-severity findings without blocking on legacy debt. Which approach best
matches modern secure-SDLC practice?
A. Suppress all high-severity findings with # nosec comments. B. Fail the build only on findings not present in the committed baseline, while tracking baseline burn-down separately. C. Disable the SAST tool in CI and run it only quarterly. D. Set the severity threshold to LOW so everything is visible and blocking.
RATIONALE Baseline gating prevents regression while allowing incremental remediation of legacy debt, a standard secure-SDLC pattern. Option A hides issues, C removes continuous feedback, and D blocks all progress with pre-existing noise.
Question 20
A custom exception hierarchy defines class AuthError(Exception) and `class
TokenExpired(AuthError). A caller writesexcept AuthError:beforeexcept
TokenExpired:`. What is the runtime consequence?
A. Both handlers run in declaration order. B. The TokenExpired handler is unreachable because AuthError matches first, so expired-token logic never executes. C. Python raises a SyntaxError at import time for overlapping handlers. D. The more specific handler runs first regardless of order.
RATIONALE Python evaluates except clauses top-down, so the broader AuthError catches TokenExpired first, making the later handler dead code. Options A, C, and D misstate exception matching semantics.
Question 21
A CI pipeline runs Bandit and reports B608 (hardcoded SQL expression) only
when the query string is built with an f-string, but not when it is built with '%s'
placeholders and a tuple. What is the most accurate explanation for this
differential behavior?
A. Bandit's B608 plugin only matches AST JoinedStr nodes, so
formatter serializes it. B. Omitting structlog.stdlib.add_log_level from the processor chain, causing the formatter to fall back to repr() of the event dict. C. Using structlog.stdlib.ProcessorFormatter.wrap_for_formatter without setting the foreign_pre_chain, which forces the stdlib formatter to escape the dict. D. Configuring the root logger with a plain logging.Formatter instead of ProcessorFormatter, so structlog's event dict is rendered by str() rather than serialized as JSON.
RATIONALE ProcessorFormatter is required to convert structlog's event dict into a serializable payload; if the root handler uses a plain logging.Formatter, the dict is coerced via str() and appears as an opaque Python dict literal. Option A is wrong because KeyValueRenderer still produces structured (though non-JSON) output and does not cause a single opaque string. Option B is incorrect because add_log_level affects the level field, not dict serialization. Option C misstates the role of foreign_pre_chain, which only affects records originating from stdlib loggers.
Question 23
A test suite uses pytest with assert statements under -O optimization. Which
statement best characterizes the risk of relying on bare assert for
security-critical input validation in production code?
A. Bare asserts are always executed in production, so the risk is limited to performance overhead rather than correctness. B. Under -O, the interpreter strips assert statements, so validation that depends on them silently disappears, potentially allowing invalid input to proceed.
C. Bare asserts raise AssertionError, which is a subclass of Exception and will be caught by a broad except Exception handler, masking the failure. D. Bare asserts are compiled to bytecode that cannot be optimized away, but they are unsuitable because they cannot include custom messages.
RATIONALE CPython removes assert statements when run with -O (and -OO), so any validation implemented solely with assert is not enforced in optimized builds, a classic security anti-pattern. Option A is the opposite of the truth. Option C is true about AssertionError's hierarchy but does not address the -O stripping risk. Option D is incorrect because asserts can include messages and are indeed optimized away.
Question 24
Which exception-handling pattern best avoids both swallowing
security-relevant failures and leaking sensitive data in logs when calling an
external authentication API?
A. except Exception as e: logging.error(f"auth failed: {e}"); return False B. except Exception: pass followed by a generic failure response to the caller C. except (requests.Timeout, requests.ConnectionError) as e: logging.warning("auth transport error", exc_info=True); raise AuthUnavailable from e D. except BaseException as e: logging.critical(str(e)); sys.exit(1)
Question 26
A developer adds logging.basicConfig(level=logging.DEBUG) inside a
library module's init.py. What is the most significant architectural
problem this introduces?
A. It forces DEBUG-level output for the entire application and may leak sensitive data, while also preventing the host application from configuring handlers. B. It has no effect because basicConfig is idempotent and only the first call in a process takes effect. C. It causes a circular import because basicConfig imports the root logger, which imports the library. D. It disables propagation to the root logger, so library logs never reach application handlers.
RATIONALE Library code should never call basicConfig because it mutates global logging state, sets a verbose level, and may add a handler before the application configures logging, causing duplicate or leaked output. Option B is misleading: basicConfig is a no-op only if the root logger already has handlers, but the side effect of setting level still occurs in some Python versions and the call is still an anti-pattern. Option C is false; there is no such circular import. Option D is incorrect because basicConfig does not disable propagation.
Question 27
Consider a custom exception hierarchy where class AuthError(Exception)
and class TokenExpired(AuthError). A handler is written as `except
AuthError: ... except TokenExpired: ...`. What is the behavioral consequence?
A. TokenExpired is caught by the first clause, so the second clause is
unreachable; the order must be reversed to handle the subclass specifically. B. Python matches the most specific exception first regardless of clause order, so both clauses work as intended. C. A SyntaxError is raised at import time because subclass clauses must precede superclass clauses. D. Both clauses execute in sequence, allowing layered handling of the same exception.
RATIONALE Python evaluates except clauses top to bottom and selects the first matching class, so the AuthError clause captures TokenExpired and makes the second clause dead code. Option B is false; Python does not reorder clauses. Option C is false; this is a logic error, not a syntax error. Option D is false; only one except clause runs per exception.
Question 28
A team adopts python -X dev and PYTHONDEVMODE=1 in CI. Which
combination of effects most accurately describes what this enables for security
and testing?
A. It enables assertions, disables bytecode caching, and turns DeprecationWarnings into errors, but it does not affect exception chaining. B. It enables the default warning filter to show DeprecationWarning, activates the debug allocator, and enables faulthandler, improving detection of resource and memory issues. C. It disables the GIL for concurrency testing and enables audit hooks for all syscalls. D. It runs the interpreter in a sandboxed mode that blocks network access