Docsity

WGU D385 Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Pyth, Exams of Computer Security

Toggle sidebar
bg1
Page 1
WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE
SECURITY & TESTING STATIC ANALYSIS, PYTHON LOGGING,
ASSERTIONS, EXCEPTION HANDLING & REMEDIATION 2026
50 QUESTIONS
TABLE OF CONTENTS
# TOPIC
1 Apply static analysis tools to identify security vulnerabilities in Python code
2 Design and implement robust logging and exception handling mechanisms for security monitoring
3 Evaluate and remediate security flaws using secure coding best practices and testing methodologies
4 WGU D385 Task 1 Complete Practice Guide Software Security & Testing Static Analysis
5 Python Logging
6 Assertions
7 Exception Handling & Remediation 2026
8 Foundations of Software Security & Testing
9 Applied Software Security & Testing
10 Advanced Software Security & Testing
11 Software Security & Testing Review
ABSTRACT
This study document brings together 50 carefully worded exam questions drawn from WGU D385
Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Python Logging,
Assertions, Exception Handling & Remediation 2026, with the strongest emphasis placed on Apply
static analysis tools to identify security vulnerabilities in Python code, Design and implement robust
logging and exception handling mechanisms for security monitoring and Evaluate and remediate
security flaws using secure coding best practices and testing methodologies. 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.
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 Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Pyth and more Exams Computer Security in PDF only on Docsity!

WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE

SECURITY & TESTING STATIC ANALYSIS, PYTHON LOGGING,

ASSERTIONS, EXCEPTION HANDLING & REMEDIATION 2026

50 QUESTIONS

TABLE OF CONTENTS

# TOPIC

1 Apply static analysis tools to identify security vulnerabilities in Python code

2 Design and implement robust logging and exception handling mechanisms for security monitoring

3 Evaluate and remediate security flaws using secure coding best practices and testing methodologies

4 WGU D385 Task 1 Complete Practice Guide Software Security & Testing Static Analysis

5 Python Logging

6 Assertions

7 Exception Handling & Remediation 2026

8 Foundations of Software Security & Testing

9 Applied Software Security & Testing

10 Advanced Software Security & Testing

11 Software Security & Testing Review

ABSTRACT

This study document brings together 50 carefully worded exam questions drawn from WGU D Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Python Logging, Assertions, Exception Handling & Remediation 2026, with the strongest emphasis placed on Apply static analysis tools to identify security vulnerabilities in Python code, Design and implement robust logging and exception handling mechanisms for security monitoring and Evaluate and remediate security flaws using secure coding best practices and testing methodologies. 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 APPLY STATIC ANALYSIS TOOLS TO IDENTIFY SECURITY VULNERABILITIES IN PYTHON

CODE

A security engineer runs Bandit on a Python module and receives a B608 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. CORRECT

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.

Q2 APPLY STATIC ANALYSIS TOOLS TO IDENTIFY SECURITY VULNERABILITIES IN PYTHON

CODE

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

RATIONALE: Asynchronous logging decouples I/O from application threads, reducing latency while still capturing detailed records for forensics. Immediate flush in option A introduces significant overhead. Options B and C may lose granularity or lack asynchronous benefits.

Q5 APPLY STATIC ANALYSIS TOOLS TO IDENTIFY SECURITY VULNERABILITIES IN PYTHON

CODE

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

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.

Q6 DESIGN AND IMPLEMENT ROBUST LOGGING AND EXCEPTION HANDLING

MECHANISMS FOR SECURITY MONITORING

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

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.

Q7 DESIGN AND IMPLEMENT ROBUST LOGGING AND EXCEPTION HANDLING

MECHANISMS FOR SECURITY MONITORING

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

C. Only run the tool on changed files in pull requests.

D. Replace the tool with a dynamic analysis tool.

RATIONALE: Tuning rules and documenting suppressions reduces noise while preserving detection of real issues. Disabling rules outright may miss vulnerabilities. Running only on changed files may miss context. Dynamic analysis complements but does not replace static analysis.

Q8 DESIGN AND IMPLEMENT ROBUST LOGGING AND EXCEPTION HANDLING

MECHANISMS FOR SECURITY MONITORING

In exception handling, which pattern best prevents resource leaks when working

with files or network connections?

A. Using a try/except block and closing the resource in the except clause.

B. Using a try/finally block to ensure the resource is closed. CORRECT

C. Relying on the garbage collector to close the resource.

D. Using a global variable to track open resources and closing them at program exit.

RATIONALE: The try/finally block guarantees cleanup regardless of whether an exception occurs. Closing only in except misses the no-exception path. Garbage collection is non-deterministic. Global tracking is error-prone.

Q11 EVALUATE AND REMEDIATE SECURITY FLAWS USING SECURE CODING BEST

PRACTICES AND TESTING METHODOLOGIES

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

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.

Q12 EVALUATE AND REMEDIATE SECURITY FLAWS USING SECURE CODING BEST

PRACTICES AND TESTING METHODOLOGIES

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

B. The effective level of the child logger is computed from its own level (NOTSET) walking up to root's INFO, so DEBUG is below the effective threshold and the record is dropped at the logger before reaching handlers. CORRECT

C. basicConfig only configures the root handler, not the logger hierarchy, so child loggers are silently disabled.

D. DEBUG records are always filtered by the logging.lastResort handler regardless of configuration.

RATIONALE: Effective level is resolved by walking the hierarchy when a logger's level is NOTSET; root is INFO, so the child's DEBUG call is filtered at the logger. Handlers also have levels, but the drop here occurs at the logger. Options A and C misstate inheritance; D confuses lastResort, which only applies when no handlers exist.

Q13 EVALUATE AND REMEDIATE SECURITY FLAWS USING SECURE CODING BEST

PRACTICES AND TESTING METHODOLOGIES

In a pytest suite, assert response.json()['user']['id'] == expected fails with a

KeyError rather than an assertion failure. Which remediation best preserves test

intent and diagnosability?

A. Wrap the call in try/except KeyError: pytest.fail() with no message.

B. Replace with assert response.json().get('user', {}).get('id') == expected so a missing key yields a clean assertion diff. CORRECT

C. Add pytestmark = pytest.mark.filterwarnings('ignore') to suppress the error.

D. Convert to assert expected in response.json() to avoid indexing.

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.

Q14 EVALUATE AND REMEDIATE SECURITY FLAWS USING SECURE CODING BEST

PRACTICES AND TESTING METHODOLOGIES

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

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.

Q17 WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING

STATIC ANALYSIS

A remediation ticket requires converting a try/except Exception: pass block

around a crypto verification call. Which refactor best aligns with secure

remediation principles?

A. Catch Exception, log at DEBUG, and continue.

B. Catch the specific crypto exception, log at ERROR with context, and fail closed by raising or returning an error to the caller. CORRECT

C. Remove the try/except entirely so the process crashes on any error.

D. Catch BaseException to also handle KeyboardInterrupt and SystemExit.

RATIONALE: Fail-closed behavior with specific exception handling preserves security guarantees while providing diagnostics. Option A silently continues on verification failure (fail-open), C removes control over error signaling, and D improperly catches system-level exceptions.

Q18 WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING

STATIC ANALYSIS

Which statement about logger.exception() versus logger.error() inside an

except block is most accurate for security incident forensics?

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

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.

Q19 WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING

STATIC ANALYSIS

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

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.

Q20 WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING

STATIC ANALYSIS

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

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.

Q22 PYTHON LOGGING

In a structlog-based service, a developer configures structlog.configure with a

ProcessorFormatter that wraps the stdlib logging root handler. Which

configuration error most likely causes structured key-value pairs to appear as a

single opaque string in downstream JSON logs?

A. Setting structlog.processors.KeyValueRenderer as the final processor instead of JSONRenderer, so the event dict is stringified before the stdlib 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. CORRECT

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.

Q23 PYTHON LOGGING

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

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.

Q24 PYTHON LOGGING

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 CORRECT

D. except BaseException as e: logging.critical(str(e)); sys.exit(1)

RATIONALE: Catching specific transport exceptions, logging with structured context (without embedding secrets), and re-raising a domain-specific exception preserves the failure signal and avoids leaking credentials. Option A logs the raw exception string, which may include request details or tokens, and returns a boolean that hides the cause. Option B swallows all exceptions, including programming errors. Option D catches BaseException (including KeyboardInterrupt/SystemExit) and terminates the process, which is inappropriate for a library call.

Q27 ASSERTIONS

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

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.

Q28 ASSERTIONS

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

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 unless explicitly allowed.

RATIONALE: Python's development mode (-X dev / PYTHONDEVMODE) enables the default warning filter (showing DeprecationWarning), the debug memory allocator, and faulthandler, which together surface latent defects. Option A overstates the effect on assertions and bytecode caching (dev mode does not strip or enable asserts in that sense). Option C is false; the GIL is not disabled by dev mode, and audit hooks are separate. Option D is false; dev mode is not a sandbox.

Q29 ASSERTIONS

A remediation ticket requires eliminating a eval() call used to parse configuration.

Which replacement best preserves the intended expressiveness while eliminating

arbitrary code execution?

A. ast.literal_eval on the raw string, which parses only Python literals. CORRECT

B. exec inside a restricted namespace with __builtins__ set to None.

C. pickle.loads on the string after base64-decoding it.

D. compile(source, '', 'eval') followed by eval(code, {}).

RATIONALE: ast.literal_eval safely evaluates only literal structures (strings, numbers, tuples, lists, dicts, booleans, None) and raises ValueError on other nodes, eliminating code execution. Option B is a known-unsafe pattern because restricted namespaces are bypassable. Option C introduces deserialization RCE. Option D still calls eval and offers no safety.

Q30 ASSERTIONS

A security review finds that a service logs `logger.info(f"user login: {username}

token={token}")`. Which remediation best aligns with OWASP logging guidance

and Python logging best practices?

A. Switch to lazy %-style formatting and exclude the token, logging only a hashed or truncated correlation identifier. CORRECT

B. Keep the f-string but set the logger level to WARNING so the message is not emitted in production.

C. Wrap the log call in if logger.isEnabledFor(logging.INFO) to avoid formatting cost.

D. Move the token into a custom LogRecord attribute so it is available to handlers but not in the message string.

RATIONALE: OWASP recommends never logging credentials or session tokens; replacing them with a non-reversible identifier and using lazy %-style formatting avoids both leakage and unnecessary string construction. Option B relies on level configuration that may change and still leaves the secret in code. Option C addresses performance, not confidentiality. Option D still places the secret in the log record, where handlers may serialize it.

Q33 EXCEPTION HANDLING & REMEDIATION 2026

A developer writes assert user.is_admin, 'denied' to gate a privileged operation,

and the code is deployed with python -O. Which statement about the resulting

security posture is most accurate?

A. The assertion still raises AssertionError but with a generic message.

B. The assertion is removed entirely, so the gate never executes and all users pass. CORRECT

C. The assertion is converted into a warning logged to stderr.

D. The assertion raises RuntimeError instead of AssertionError under -O.

RATIONALE: Under -O, the compiler strips assert statements, so the authorization check vanishes and the privileged path executes unconditionally - a classic reason assertions must never enforce security. Options A, C, and D misstate Python's documented optimization semantics.

Q34 EXCEPTION HANDLING & REMEDIATION 2026

A function calls int(user_input) inside a loop that also opens a file. Reviewers

want file handles always closed and only conversion errors surfaced to the caller.

Which construct best satisfies both requirements simultaneously?

A. try/except ValueError around the loop with a finally block that closes the file.

B. A bare except: inside the loop that logs and continues.

C. with open(...) as f: inside a try that catches ValueError and re-raises. CORRECT

D. try/except/else with else closing the file and finally converting input.

RATIONALE: A context manager guarantees deterministic file closure even on exceptions, and catching/re-raising ValueError preserves the intended error contract. Option A risks leaking the handle on non-ValueError paths, B swallows all errors including KeyboardInterrupt, and D inverts the semantics of else/finally.

Q35 FOUNDATIONS OF SOFTWARE SECURITY & TESTING

A SAST tool flags a taint path from request.args to cursor.execute(query). The

developer refactors to use parameterized queries but the finding persists. Which

explanation for the persistent finding is most technically sound?

A. Parameterization only prevents SQL injection in PostgreSQL, not SQLite.

B. The taint engine tracks data flow to the sink regardless of whether the sink is safe, so the rule must be refined or the sink annotated. CORRECT

C. Parameterized queries still concatenate strings internally, so the taint is genuine.

D. The scanner requires the parameter list to be a literal tuple to clear taint.

RATIONALE: Many taint analyses are flow-sensitive but not sanitizer-aware; without modeling parameterization as a sanitizer or annotating the sink, the flow remains flagged though the code is safe. A, C, and D mischaracterize how parameterization and taint engines actually behave.

Q36 FOUNDATIONS OF SOFTWARE SECURITY & TESTING

A remediation plan must prioritize three findings: (1) hardcoded AWS secret in

source, (2) reflected XSS in a search page, (3) verbose stack traces returned to

clients. Using CVSS-based risk and exploitability, which prioritization is most

defensible?

A. 3, then 1, then 2 - information disclosure always dominates.

B. 1, then 2, then 3 - credential exposure enables full compromise; XSS enables session theft; stack traces are lower severity. CORRECT

C. 2, then 3, then 1 - client-facing flaws always rank highest.

D. All three are equal severity and should be fixed in code-commit order.

RATIONALE: Hardcoded credentials grant persistent, high-impact access (often critical), reflected XSS enables session/credential theft (high), and verbose errors aid reconnaissance but are typically medium/low. The other orderings ignore impact and exploitability modeling.