Docsity

WGU D385 Software Security and Testing | Static Code Analysis & Flake8 Practice Lab | Pyth, Exams of Software Engineering

Partial preview of the text

Download WGU D385 Software Security and Testing | Static Code Analysis & Flake8 Practice Lab | Pyth and more Exams Software Engineering in PDF only on Docsity!

WGU D385 Software Security and Testing |

Static Code Analysis & Flake8 Practice Lab |

Python Security, Logging, Testing &

Remediation | 2026 update.

SECTION 1: STATIC CODE ANALYSIS

FUNDAMENTALS (Questions 1-10)

Question 1: What is static code analysis in the context of software security? A. Testing code by executing it with various inputs B. Analyzing code without executing it to find potential security issues C. Monitoring code performance in production environments D. Documenting code functionality for user manuals Correct Answer: B. Analyzing code without executing it to find potential security issues Rationale: Static code analysis examines source code without executing it to identify potential security vulnerabilities, coding errors, and style violations. This contrasts with dynamic analysis, which requires running the code. Static analysis tools like Bandit and flake8 can quickly scan large codebases and are especially useful in continuous integration pipelines. Source: WGU D385 Static Code Analysis Practice Lab Question 2: Which tool is a Python linter that combines pyflakes and pycodestyle to flag general security issues?

A. Bandit B. flake C. pytest D. unittest Correct Answer: B. flake Rationale: flake8 is a Python linter combining pyflakes and pycodestyle that flags general security issues such as bare excepts and risky patterns. In the D385 course, its report flags the general security issues (part A) like bare excepts and risky patterns, each as file:line entries. Source: WGU D385 Task 1 Performance Assessment Question 3: What type of security issues does Bandit identify in Python code? A. Only syntax errors B. API security vulnerabilities and risky patterns C. Runtime performance bottlenecks D. Database connection issues Correct Answer: B. API security vulnerabilities and risky patterns Rationale: Bandit is a Python SAST tool that scans source code via AST (Abstract Syntax Tree) for security issues. Running bandit -r app_student.py produces output with issue ID (e.g., B hardcoded_password_string), severity, confidence, CWE link, and file:line information. In D385, Bandit identifies the API security vulnerabilities for Section B. Source: WGU D385 Task 2 Secure Coding and API Security Question 4: What is the educational scanner used in Task 1 to identify high- risk AST patterns? A. Bandit B. flake

Correct Answer: A. It does not account for runtime vulnerabilities Rationale: A limitation of static code analysis is that it does not account for runtime vulnerabilities, which only manifest during execution. Static analysis cannot detect issues that depend on specific runtime conditions, configurations, or data flows. Other limitations include requiring testers with both testing and software development skills, and needing language-specific tools. Source: WGU D385 Static Code Analysis Practice Lab Question 7: Which Python package is meant for internal use by Python for regression testing? A. unittest B. pytest C. test D. doctest Correct Answer: C. test Rationale: The test package is meant for internal use by Python for regression testing. While unittest and pytest are commonly used for application testing, the test package is specifically for Python's own internal regression testing. Source: WGU D385 V2 Software Security and Testing Master Study Guide Question 8: What does flake8 catch in the pristine starter code for D Task 1? A. SQL injection B. F401 - imported but unused module (os module) C. Missing authentication D. Broken authorization Correct Answer: B. F401 - imported but unused module (os module)

Rationale: flake8 catches F401 - the os module imported but unused in the pristine starter; a hygiene finding proving flake8 catches style as well as security. It becomes used once your env-var fix lands. This demonstrates that flake8 catches both security issues and code hygiene problems. Source: WGU D385 Task 2 Complete Practice Guide Question 9: What is the purpose of the -r flag in the bandit -r command? A. To run recursively on all files in a directory B. To generate a report only C. To reverse the scan order D. To restrict to specific files Correct Answer: A. To run recursively on all files in a directory Rationale: The -r flag in bandit -r app_student.py runs Bandit recursively on all files in the directory. This allows the tool to scan entire codebases rather than individual files. Bandit scans source code via AST for security issues and produces output with issue ID, severity, confidence, CWE link, and file:line information. Source: WGU D385 Task 2 Secure Coding and API Security Question 10: What is "shift-left" security in the context of the SDLC? A. Moving security testing to later stages B. Building security in during development (static analysis, unit tests, code review) instead of bolting it on after release C. Shifting all security to the operations team D. Eliminating all security testing Correct Answer: B. Building security in during development (static analysis, unit tests, code review) instead of bolting it on after release Rationale: Secure SDLC / shift-left involves building security in during development (static analysis, unit tests, code review) instead of bolting it on

Rationale: With a log injection attack, an attacker can inject commands that a parser can execute. This can forge severity text, insert newline characters to create fake log entries, or inject terminal escape sequences. The defense is to sanitize all outbound log messages. Source: WGU D385 V2 Software Security and Testing Master Study Guide Question 13: Which Python logging configuration ensures that log messages capture the correct timestamp, severity level, and message content? A. logging.basicConfig(level=logging.DEBUG) B. logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') C. logging.basicConfig(filename='app.log') D. logging.basicConfig(level=logging.INFO) Correct Answer: B. logging.basicConfig(format='%(asctime)s - %(levelname)s - % (message)s') Rationale: The format parameter in logging.basicConfig uses placeholders to define the structure of log messages. %(asctime)s captures the timestamp, % (levelname)s captures the severity level, and %(message)s captures the actual log message. This format ensures that all critical information is captured in each log entry. Source: WGU D385 Task 1 Performance Assessment Question 14: Which logging level should be used to record a runtime error that was successfully handled by exception handling? A. DEBUG B. INFO C. WARNING D. ERROR Correct Answer: D. ERROR Rationale: The ERROR level should be used to log runtime errors that were caught and handled. Task 1 requires B2 try/except handling of 2 runtime

errors, with 1 ERROR log entry and 1 WARNING log entry. The ERROR level indicates a serious problem that occurred but was handled, while WARNING indicates a potential issue. Source: WGU D385 Task 1 Performance Assessment Question 15: What logging level should be used for anticipated failures that were successfully recovered from? A. DEBUG B. INFO C. WARNING D. CRITICAL Correct Answer: C. WARNING Rationale: The WARNING level should be used for anticipated failures that were successfully recovered from. WARNING indicates a potential issue that was handled, while ERROR indicates a more serious failure. DEBUG and INFO are for diagnostic and informational messages, while CRITICAL is for critical system failures. Source: WGU D385 Task 1 Performance Assessment Question 16: In Task 1, why does equipment validation log ERROR but days validation log WARNING? A. Equipment is a fixed dropdown so an unknown value implies a crafted request (ERROR); days is free text so typos are expected user error (WARNING) B. Equipment is more important than days C. Days is always valid D. Equipment is never validated Correct Answer: A. Equipment is a fixed dropdown so an unknown value implies a crafted request (ERROR); days is free text so typos are expected user error (WARNING)

Source: WGU D385 Task 1 Performance Assessment Question 19: What is a log injection attack? A. Encrypting log files without authorization B. Inserting malicious characters or commands into log entries C. Deleting log files to hide evidence D. Accessing log files without permission Correct Answer: B. Inserting malicious characters or commands into log entries Rationale: A log injection attack involves inserting malicious characters or commands into log entries through user-controlled input. This can forge severity text, insert newline characters to create fake log entries, or inject terminal escape sequences. The defense is to sanitize all outbound log messages. Source: WGU D385 V2 Software Security and Testing Master Study Guide Question 20: How does logging contribute to security accountability? A. By encrypting sensitive data B. By providing an audit trail that cannot be repudiated C. By authenticating users D. By blocking attacks Correct Answer: B. By providing an audit trail that cannot be repudiated Rationale: Logging contributes to security accountability by providing an audit trail that cannot be repudiated. The remediation in Task 1 added timestamped structured INFO, WARNING, and ERROR events without raw input, ensuring that security events can be reconstructed consistently. Source: WGU D385 Task 1 Performance Assessment

SECTION 3: ASSERTIONS & DEFENSIVE

PROGRAMMING (Questions 21-30)

Question 21: What is the purpose of assertions in Python? A. To handle runtime errors B. To document and test internal invariants C. To validate user input at trust boundaries D. To encrypt sensitive data Correct Answer: B. To document and test internal invariants Rationale: Assertions document conditions the developer expects to be true after external data has been validated. The sample asserts that the caller supplied a username object and that a validated rental total is positive. Assertions are intentionally not used as the sole protection against hostile input. Source: WGU D385 Task 1 Performance Assessment Question 22: What happens to assert statements when Python runs with the -O optimization flag? A. They execute faster B. They are removed from the compiled bytecode C. They generate more detailed error messages D. They are converted to warnings Correct Answer: B. They are removed from the compiled bytecode Rationale: When Python runs with the -O (optimize) flag, assert statements are removed from the compiled bytecode. Assertions are stripped at optimize level 1, so they are documentation of developer assumptions, never

Source: WGU D385 Task 1 Performance Assessment Question 25: In Task 1, what assertions are used in the sample code? A. assert username is not None and assert total > 0 B. assert password == "secret" C. assert request.method == "GET" D. No assertions are used Correct Answer: A. assert username is not None and assert total > 0 Rationale: The sample code uses two assertions: assert username is not None, "username must be supplied by the caller" and total = daily_rate * rental_days; assert total > 0, "validated rental totals must be positive". These document conditions the developer expects to be true after external data has been validated. Source: WGU D385 Task 1 Performance Assessment Question 26: What does an assertion failure during a request indicate? A. A security breach B. An assumption violation that may be acceptable for 500 response C. A network error D. A user input error Correct Answer: B. An assumption violation that may be acceptable for 500 response Rationale: A failed assert during a request = 500, which is acceptable for assumption violations. Assertions are stripped at optimize level 1, so they are documentation of developer assumptions, never production input validation. A failed assertion indicates that an internal invariant was violated, which is a programming error rather than a user error. Source: WGU D385 Full Course Bank

Question 27: What is the purpose of an assertion in defensive programming? A. To verify that assumptions about the program state are correct B. To handle runtime errors C. To encrypt sensitive data D. To log user activity Correct Answer: A. To verify that assumptions about the program state are correct Rationale: Assertions document conditions the developer expects to be true after external data has been validated. They improve developer feedback by failing close to an invalid internal state. However, assertions are intentionally not used as the sole protection against hostile input. Source: WGU D385 Task 1 Performance Assessment Question 28: Why are assertions NOT used as the sole protection against hostile input? A. They are too slow for production use B. Python can remove assert statements when executed with optimization C. They only work with string data D. They cannot be logged Correct Answer: B. Python can remove assert statements when executed with optimization Rationale: Assertions are not used as the sole protection against hostile input because Python can remove assert statements when executed with optimization (using the -O flag). Boundary validation remains mandatory because Python can remove assert statements. The design therefore uses normal conditional checks for security decisions and assertions only after validation establishes the relevant preconditions. Source: WGU D385 Task 1 Performance Assessment Question 29: What is a "precondition" in defensive programming?

Question 31: What is a "bare exception handler" and why is it considered a security defect? A. An exception handler that catches all exceptions; it hides defects and prevents predictable recovery B. An exception handler that catches no exceptions; it causes crashes C. An exception handler that only catches specific exceptions; it is too narrow D. An exception handler that logs exceptions; it is redundant Correct Answer: A. An exception handler that catches all exceptions; it hides defects and prevents predictable recovery Rationale: A bare exception handler (using except: without specifying exception types) is a security defect because it can mask unexpected errors, hide attack indicators, and allow the program to continue in an invalid state. The remediation is to use specific exception types such as KeyError, TypeError, ValueError, and AssertionError. Source: WGU D385 Task 1 Performance Assessment Question 32: Which exception handling pattern is recommended for security-sensitive applications? A. except Exception: pass B. except: continue C. except (KeyError, TypeError, ValueError) as e: logging.warning(...) D. except: logging.error(...) Correct Answer: C. except (KeyError, TypeError, ValueError) as e: logging.warning(...) Rationale: The recommended pattern is to catch specific exception types and log them at the appropriate level. This prevents hiding unexpected errors (which could indicate attacks) while still handling anticipated failures gracefully. Options A and B use bare except clauses that catch all exceptions. Option D uses a bare except with logging, which still catches everything and could hide security-relevant errors.

Source: WGU D385 Task 1 Performance Assessment Question 33: What information should NOT be included in user-facing error messages? A. A generic error description B. Stack traces and internal implementation details C. A request ID for tracking D. Instructions for contacting support Correct Answer: B. Stack traces and internal implementation details Rationale: User-facing error messages should not include stack traces, internal paths, package names, source lines, data shapes, or internal control flow. These details could disclose architecture information that helps attackers understand the system. Instead, errors should be converted to safe responses with generic messages, while detailed logging preserves operational visibility. Source: WGU D385 Task 1 Performance Assessment Question 34: What is the security implication of logging stack traces in production? A. It improves debugging efficiency B. It discloses architecture and implementation details to potential attackers C. It increases log file size D. It slows down application performance Correct Answer: B. It discloses architecture and implementation details to potential attackers Rationale: Logging stack traces in production can disclose paths, package names, source lines, data shapes, and internal control flow. This information helps attackers understand the system architecture and identify potential attack vectors. While stack traces are useful for debugging in development, production error responses should provide safe messages while detailed errors are logged internally.