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 &
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
INTRODUCTION
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.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22

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 &

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

INTRODUCTION

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 static analysis tool reports a potential SQL injection vulnerability in a

Python function that constructs a query using string formatting. Which

remediation strategy best addresses the root cause while maintaining

functionality?

A. Replace string formatting with parameterized queries using the database driver's placeholder syntax. B. Sanitize all user inputs by escaping single quotes and semicolons before concatenation. C. Implement a web application firewall (WAF) rule to block SQL injection patterns. D. Use an ORM exclusively for all database interactions without reviewing generated SQL.

Correct Answer: A - Replace string formatting with

parameterized queries using the database driver's placeholder

syntax.

RATIONALE Parameterized queries separate SQL logic from data, preventing injection by design. Escaping is error-prone and bypassable; WAFs are defense-in-depth but not a fix; ORMs can still be misused and may not cover all cases.

Question 2

In Python's logging module, which configuration ensures that log records are

written to a file only when an exception occurs, while still capturing full stack

traces?

A. Set the logging level to ERROR and use a FileHandler with a formatter that includes %(exc_info)s. B. Use a try-except block that calls logging.exception() within the except clause, with a FileHandler configured.

RATIONALE Assertions can be disabled in optimized mode, making them unreliable for security checks. Raising explicit exceptions ensures validation always occurs. Type hints are not runtime enforced; relying on assertions is risky.

Question 4

A developer catches a broad Exception in Python and logs it with

logging.error(e). What is the primary security concern with this approach?

A. It may log sensitive information from the exception message, such as credentials or PII. B. It fails to capture the stack trace, hindering debugging. C. It suppresses the exception, allowing the program to continue in an inconsistent state. D. It logs at ERROR level, which may be filtered out in production.

Correct Answer: A - It may log sensitive information from the

exception message, such as credentials or PII.

RATIONALE Exception messages can contain sensitive data; logging them may expose secrets. Option B is also true but less security-critical; C is about suppression; D is a logging level issue, not primary security concern.

Question 5

In the context of static analysis, what distinguishes a false positive from a false

negative, and which is more dangerous from a security perspective?

A. False positive: flagging a non-issue; false negative: missing a real issue. False negatives are more dangerous as they leave vulnerabilities undetected. B. False positive: missing a real issue; false negative: flagging a

non-issue. False positives are more dangerous as they cause alert fatigue. C. False positive: flagging a non-issue; false negative: missing a real issue. False positives are more dangerous as they waste developer time. D. False positive: incorrect severity rating; false negative: incorrect location. Both are equally dangerous.

Correct Answer: A - False positive: flagging a non-issue; false

negative: missing a real issue. False negatives are more dangerous

as they leave vulnerabilities undetected.

RATIONALE False positives are incorrect warnings; false negatives are missed vulnerabilities. False negatives are more dangerous because they allow exploits to remain. The other options misdefine the terms or prioritize incorrectly.

Question 6

When using Python's logging module, which handler and formatter

combination best supports forensic analysis after a security incident?

A. StreamHandler with a simple message format to console for real-time monitoring. B. RotatingFileHandler with a detailed format including timestamp, log level, module, and process ID. C. SysLogHandler sending logs to a remote syslog server with default formatting. D. MemoryHandler buffering logs and flushing only on critical errors.

Correct Answer: B - RotatingFileHandler with a detailed format

including timestamp, log level, module, and process ID.

RATIONALE RotatingFileHandler preserves logs with rotation, and detailed formatting aids forensics. Console logging is ephemeral; syslog may lack detail; MemoryHandler may lose logs on crash.

RATIONALE realpath() canonicalizes the path, preventing traversal outside the base directory. basename() may not handle all cases; whitelisting is good but less general; URL encoding does not prevent traversal.

Question 9

In Python, which logging level is most appropriate for recording

security-relevant events such as failed login attempts, and why?

A. DEBUG, because it provides detailed information for troubleshooting. B. INFO, because it indicates normal but significant events. C. WARNING, because it indicates a potential issue that should be investigated. D. ERROR, because it indicates a failure that requires immediate attention.

Correct Answer: C - WARNING, because it indicates a potential

issue that should be investigated.

RATIONALE Failed logins are potential security issues, so WARNING is appropriate. DEBUG is too verbose, INFO is for normal events, ERROR is for actual errors, not just attempts.

Question 10

Which of the following best describes the principle of remediation in the

context of software security testing?

A. Remediation involves only patching the identified vulnerability without addressing root causes. B. Remediation is the process of mitigating or eliminating vulnerabilities, including root cause analysis and preventive measures. C. Remediation is solely the responsibility of the security team, not developers.

D. Remediation focuses on adding runtime protections like WAFs rather than code fixes.

Correct Answer: B - Remediation is the process of mitigating or

eliminating vulnerabilities, including root cause analysis and

preventive measures.

RATIONALE Remediation includes fixing the vulnerability and preventing recurrence. Option A is incomplete; C is incorrect as developers play a key role; D is a partial measure, not full remediation.

Question 11

A security engineer runs Bandit on a Python module and receives a B

(hardcoded_sql_expressions) finding for a query built with an f-string that

interpolates a variable validated by a strict regex allowlist. Which remediation

best preserves functionality while eliminating the finding?

A. Add '# nosec' with a comment documenting the allowlist validation. B. Convert the f-string to a parameterized query using the DB-API placeholder style. C. Replace the f-string with str.format() and pass the variable as a format argument. D. Wrap the query execution in a try/except and log the SQLException on failure.

Correct Answer: B - Convert the f-string to a parameterized

query using the DB-API placeholder style.

Question 13

A team configures Python logging with dictConfig using a

RotatingFileHandler and a StreamHandler sharing one logger. During a burst

of warnings, duplicate lines appear in the file but not on the console. Which

configuration error most likely explains this?

A. The logger's propagate flag is True and a parent logger also has a RotatingFileHandler attached. B. The StreamHandler level is set to WARNING while the RotatingFileHandler level is DEBUG. C. The formatter uses %(message)s without a timestamp, causing apparent duplicates. D. The RotatingFileHandler maxBytes is smaller than the burst size, triggering rotation mid-write.

Correct Answer: A - The logger's propagate flag is True and a

parent logger also has a RotatingFileHandler attached.

RATIONALE Duplicate records typically arise when a record propagates to an ancestor logger that also has a handler writing to the same destination; setting propagate=False or attaching handlers only at the root fixes it. Level mismatches (B) change filtering, not duplication, formatting (C) cannot duplicate lines, and rotation (D) does not duplicate records.

Question 14

Consider this assertion: assert validate(payload), f'invalid: {payload}'. A

production deployment runs with python -O. Which statement about behavior

is correct?

A. The assertion still executes and raises AssertionError with the message. B. The assertion is stripped entirely, and payload is never validated. C. The assertion executes but the message expression is skipped for

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

Correct Answer: B - The assertion is stripped entirely, and

payload is never validated.

RATIONALE Under -O (and PYTHONOPTIMIZE), the compiler removes assert statements and their message expressions entirely, so validation silently disappears - a classic rationale for never using asserts for runtime input validation. The other options misstate the optimizer's effect on asserts.

Question 15

A SAST tool reports a taint flow from request.args['q'] to

cursor.execute(query). The developer adds html.escape(q) before the query.

Which statement best characterizes the residual risk?

A. The flow is fully mitigated because escaping neutralizes all metacharacters. B. The flow remains exploitable because HTML escaping does not address SQL context. C. The flow is mitigated only if the database uses a UTF-8 collation. D. The flow is mitigated because taint analyzers recognize html.escape as a sanitizer.

Correct Answer: B - The flow remains exploitable because HTML

escaping does not address SQL context.

Question 17

A CI pipeline fails because pylint emits W0703 (broad-except) on a handler

that intentionally catches all exceptions to log and re-raise. Which action best

aligns with secure-coding best practice?

A. Add '# pylint: disable=broad-except' on the line and document the rationale. B. Change to 'except BaseException' to avoid the warning. C. Remove the handler and rely on the default excepthook for logging. D. Refactor to catch (Exception,) as a tuple to satisfy the checker.

Correct Answer: A - Add '# pylint: disable=broad-except' on the

line and document the rationale.

RATIONALE Targeted suppression with a documented justification is the accepted way to handle intentional broad catches at process boundaries. BaseException (B) is broader and worse, removing the handler (C) loses context, and (Exception,) (D) is functionally identical and still triggers W0703.

Question 18

A module defines class AuditError(Exception) with init(self, code, msg)

that calls super().init(msg) and sets self.code. A caller does 'raise

AuditError(42, "bad") from KeyError("k")'. Which statement about the

resulting exception is correct?

A. str(exc) returns 'bad' and exc.cause is the KeyError instance. B. str(exc) returns '(42, "bad")' because init overrides the message. C. exc.context is None because 'from' clears the implicit context. D. The KeyError is discarded because AuditError is not a subclass of it.

Correct Answer: A - str(exc) returns 'bad' and exc.cause is

the KeyError instance.

RATIONALE super().init(msg) sets the args so str(exc) yields 'bad', and 'raise ... from ...' explicitly sets cause to the KeyError. Option B misstates args handling, C confuses context (still set) with cause, and D ignores chaining semantics.

Question 19

A reviewer sees: 'assert isinstance(user, Admin)'. The code then calls

user.delete_all(). Which statement best explains why this pattern is a security

weakness?

A. isinstance is too slow for security checks and should use type() instead. B. Asserts can be disabled with -O, so the authorization check may vanish in production. C. Admin is a subclass of User, so isinstance returns False and blocks access. D. The assert raises AssertionError, which is not a subclass of Exception.

Correct Answer: B - Asserts can be disabled with -O, so the

authorization check may vanish in production.

RATIONALE Using assert for authorization is unsafe because the -O flag strips asserts, silently removing the check; explicit if/raise is required. Speed (A), subclass direction (C), and AssertionError's hierarchy (D, it is a subclass of Exception) are all incorrect.

Question 20

A team must remediate a SAST finding on a subprocess call built from user

input. Which remediation most directly eliminates the injection class while

preserving functionality?

A. Pass shell=False and provide the command as a list of arguments.

RATIONALE Bandit's B608 flags the dangerous SQL-construction pattern and is largely path-insensitive, so an early guard does not make the pattern safe to retain. Suppressing with # nosec hides a genuine anti-pattern that could become reachable after refactoring. Parameterized queries eliminate the root cause, which is the correct remediation posture.

Question 22

A service uses logging.getLogger(name) and emits records at DEBUG

and ERROR. In production, only ERROR records appear, yet the handler is

attached to the root logger at DEBUG. Which configuration most plausibly

explains this?

A. The module logger's effective level is set to ERROR via the root logger, and propagate is True, so DEBUG records are filtered at the logger level before reaching the root handler. B. The root handler's level is DEBUG but the formatter drops lower-severity records. C. Python disables DEBUG logging whenever a non-root handler exists. D. The name logger inherits a NullHandler that discards DEBUG records.

Correct Answer: A - The module logger's effective level is set to

ERROR via the root logger, and propagate is True, so DEBUG

records are filtered at the logger level before reaching the root

handler.

RATIONALE A logger filters records against its effective level before propagation; if the effective level is ERROR, DEBUG records never reach the root handler. Handlers and formatters do not perform severity filtering by default, and NullHandler only suppresses 'no handler' warnings. DEBUG is not globally disabled by handler presence.

Question 23

Which assertion is appropriate for validating an internal invariant whose

violation indicates a programming error, and how should it behave under

python -O?

A. Use assert; it is stripped under -O, so it must not guard security-critical or user-input validation. B. Use assert; it remains active under -O and is the preferred runtime input validator. C. Use a custom exception; assert is always stripped in all CPython modes. D. Use assert with a message; -O converts failures to warnings instead of raising.

Correct Answer: A - Use assert; it is stripped under -O, so it must

not guard security-critical or user-input validation.

RATIONALE assert is intended for internal invariants and is removed when optimizations disable it (python -O), so it must never enforce security or input validation. It is not converted to warnings, and it is not stripped in normal execution. Custom exceptions are used for recoverable or externally triggered errors, not for invariants expected to hold.

Question 24

A function raises ValueError for malformed input and OSError for I/O failures.

A caller wraps it in try/except (ValueError, OSError) as e: log and re-raise.

Which refactor best preserves diagnostic fidelity while enabling targeted

recovery?

A. Catch Exception broadly and re-raise a new RuntimeError to unify error types. B. Separate except clauses: handle ValueError with user feedback and

RATIONALE Modern practice combines reachability/exploitability triage with compensating controls and time-boxed, documented exceptions to manage risk transparently. Permanent suppressions or ignoring based solely on claimed non-exploitability bypass governance. Silent forks create maintenance and disclosure burdens without addressing upstream risk.

Question 26

A test asserts that a function raises KeyError for a missing key. The

implementation was changed to raise a custom ConfigError(KeyError). Which

assertion most robustly encodes the intended contract?

A. with self.assertRaises(KeyError): B. with self.assertRaises(ConfigError): C. with self.assertRaises(Exception): D. with self.assertRaisesRegex(KeyError, 'missing'):

Correct Answer: B - with self.assertRaises(ConfigError):

RATIONALE Asserting the specific ConfigError type captures the refined contract and will fail if the type regresses to a bare KeyError. Asserting KeyError passes for the subclass, masking the intended specificity, while Exception is too broad. assertRaisesRegex on KeyError still under-specifies the type.

Question 27

A codebase logs sensitive tokens at INFO. Which change most effectively

prevents leakage while preserving operational visibility?

A. Raise the logger level to WARNING globally. B. Add a logging.Filter that redacts or drops records containing token patterns before they reach handlers. C. Switch to print() for non-sensitive messages and keep logging for

tokens. D. Disable propagation to the root logger.

Correct Answer: B - Add a logging.Filter that redacts or drops

records containing token patterns before they reach handlers.

RATIONALE A Filter can inspect and sanitize or drop records regardless of level, directly preventing sensitive data from reaching any handler. Raising the level may hide useful INFO diagnostics and still leaks if tokens are logged at WARNING. Disabling propagation and using print do not reliably prevent leakage and undermine structured logging.

Question 28

Which statement best distinguishes the roles of static application security

testing (SAST) and software composition analysis (SCA) in a secure SDLC?

A. SAST scans source/binaries for code-level flaws; SCA inventories third-party components and maps them to known vulnerabilities. B. SAST scans dependencies; SCA scans first-party code for injection flaws. C. Both are dynamic techniques requiring a running application. D. SAST detects license compliance issues; SCA detects logic errors.

Correct Answer: A - SAST scans source/binaries for code-level

flaws; SCA inventories third-party components and maps them to

known vulnerabilities.

RATIONALE SAST analyzes first-party source or binaries for code-level weaknesses, while SCA catalogs dependencies and correlates them with vulnerability databases. The reversed and dynamic-testing descriptions are incorrect, and license/logic attributions are swapped. Together they cover distinct but complementary risk surfaces.