Docsity

WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging,, Exams of Computer Security

Partial preview of the text

Download WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging, and more Exams Computer Security in PDF only on Docsity!

Table of Contents

Content Area Questions Key Topics

WGU D385 TASK 1 Performance Assessment Guide Software Security & Testing Python Logging Assertions Static CODE Analysis & Testing 2026 Software Security & Testing Python Logging Assertions Static CODE Analysis & Testing Undergraduate YEAR 3 / Graduate Advanced Software Engineering

1-9 Function, Logging, Username, Directly, Developer

Directly 10-18 Finding, Class, Logging, Pipeline RUNS, Bandit

Function 19-27 Module, Pytest, Coverage, Change, Assertion

Security 28-36 Logging, Validate, Security Review, Developer, Assert

Pytest 37-45 Function, Behavior, Fixture, Configures Logging, Change

Coverage 46-50 Subprocess Popen, Security, Shell, Password, Developer USES Coverage

TOTAL 50 All questions include answers and detailed rationales

Section A - WGU D385 TASK 1 Performance Assessment Guide Software Security & Testing Python Logging Assertions Static CODE Analysis & Testing 2026 Software Security & Testing Python Logging Assertions Static CODE Analysis & Testing Undergraduate YEAR 3 / Graduate

Rationale: Under -O/PYTHONOPTIMIZE, the compiler removes assert statements entirely, eliminating the guard and its message. Assertions must never enforce security; explicit if/raise or authorization decorators are required. The other options misstate optimization semantics.

Q3. Bandit reports B301 (pickle) on a function that deserializes data from a trusted internal queue, but the queue is fed by a webhook that accepts unauthenticated JSON. Which action best reflects correct triage?

A. Suppress B301 with # nosec because the queue is internal.

B. Treat the finding as a true positive and replace pickle with a safe format (e.g., JSON) plus schema validation.

C. Downgrade severity to LOW because the queue is internal.

D. Add a try/except around pickle.loads to catch malicious payloads. Correct: B - Treat the finding as a true positive and replace pickle with a safe format (e.g., JSON) plus schema validation.

Rationale: Taint flows from an unauthenticated webhook through the queue to pickle.loads, making the finding a true positive with potential RCE. Suppression or severity downgrade ignores the taint path, and try/except cannot prevent code execution during deserialization.

Q4. A test suite achieves 100% line coverage yet misses a bug where a function returns None for empty input. Which testing technique would most likely expose this defect?

A. Increasing line coverage to 100% on all branches.

B. Adding property-based tests that assert invariants across generated inputs, including empty sequences.

C. Running the suite under pytest -x to stop on first failure.

D. Adding more assertions inside the function under test. Correct: B - Adding property-based tests that assert invariants across generated inputs, including empty sequences.

Rationale: Line coverage does not guarantee oracle quality or input diversity; property-based testing generates edge cases like empty inputs and checks invariants, exposing the None return. Branch coverage may still miss it, -x only changes failure handling, and internal assertions do not create external test oracles.

Q5. A Semgrep rule flags f"SELECT * FROM users WHERE name = '{name}'" but the codebase uses a custom ORM that parameterizes queries before execution. What is the most rigorous next step?

Section A - WGU D385 TASK 1 Performance Assessment Guide Software Security & Testing Python Logging Assertions Static CODE Analysis & Testing 2026 Software Security & Testing Python Logging Assertions Static CODE Analysis & Testing Undergraduate YEAR 3 / Graduate

A. Disable the rule globally to reduce false positives.

B. Verify the ORM's parameterization path with a taint-mode Semgrep rule and adjust the rule's sanitizer configuration.

C. Convert all queries to string concatenation to satisfy the rule.

D. Add # nosemgrep to every flagged line.

Correct: B - Verify the ORM's parameterization path with a taint-mode Semgrep rule and adjust the rule's sanitizer configuration.

Rationale: The correct response is to validate the sanitizer behavior and refine the rule using taint mode so it recognizes the ORM's parameterization. Global disabling or blanket suppression hides real issues, and reverting to concatenation would introduce vulnerabilities.

Q6. A team uses mypy in strict mode but disables --disallow-untyped-defs to speed adoption. A security-critical function lacks type annotations and accepts Any. Which risk does this pose to static security analysis?

A. None; mypy still checks all operations on Any values.

B. Any propagates and suppresses type-based taint tracking, allowing unsafe flows to pass unchecked.

C. mypy will raise a runtime error when Any is used.

D. Disabling that flag only affects documentation generation. Correct: B - Any propagates and suppresses type-based taint tracking, allowing unsafe flows to pass unchecked.

Rationale: Any is compatible with all types and effectively disables type checking for those values, which can break taint propagation in type-aware analyzers. The other options misstate mypy's behavior; mypy is static and does not raise runtime errors.

Q7. A pytest suite uses unittest.mock.patch to replace a payment gateway with a stub that always returns success. Mutation testing shows zero mutants killed in the payment module. What is the most likely cause?

A. The mutants are equivalent and cannot be killed.

B. The mock removes the real logic from the test path, so mutants in the payment module are never executed.

C. Mutation testing requires 100% branch coverage to run.

D. The stub returns success, which is the expected behavior. Correct: B - The mock removes the real logic from the test path, so mutants in the payment module are never executed.

Section B - Directly

Q10.

A CI pipeline runs bandit -r. -ll and exits 0 despite a HIGH severity finding because the finding is in a test file excluded by default. Which configuration change ensures security findings in test code are also reviewed?

A. Remove the -ll flag to include all severities.

B. Add --exclude tests to the command.

C. Override the default exclusion with --include or remove tests from the excluded set.

D. Run bandit with -s B101 to skip assert checks.

Correct: C - Override the default exclusion with --include or remove tests from the excluded set.

Rationale: Bandit's default exclusions include common test directories; to scan them, the exclusion set must be overridden or removed. -ll only filters severity, --exclude adds exclusions, and -s skips specific tests rather than including test files.

Q11. A developer writes assert user.is_admin, "denied" inside a request handler that is deployed with python -O. Which security property does this deployment most directly violate?

A. Confidentiality of the assertion message in logs

B. Integrity of the authorization check, because assertions are stripped under -O

C. Availability, because -O disables exception handling

D. Non-repudiation, because assert writes no audit record Correct: B - Integrity of the authorization check, because assertions are stripped under -O

Rationale: CPython removes assert statements when debug is false (e.g., -O/-OO), so an authorization guard implemented as an assertion silently disappears, breaking the integrity of the access-control decision. Assertions are for internal invariants, not security enforcement; the other options misattribute the failure mode to logging, availability, or auditability.

Q12. A test suite passes locally but fails in CI only when a test that mutates a module-level dict runs before another test. Which pytest mechanism most directly eliminates this class of inter-test coupling?

Section B - Directly

A. pytest.mark.parametrize B. A session-scoped fixture that shares the dict

C. pytest-randomly with a fixed seed D. An autouse function-scoped fixture that restores the dict Correct: D - An autouse function-scoped fixture that restores the dict

Rationale: An autouse function-scoped fixture that snapshots and restores the module-level dict isolates state between tests, removing order dependence. Parametrization changes inputs, session-scoped fixtures worsen sharing, and a fixed random seed only makes the order deterministic-not independent.

Q13. Bandit reports B608: hardcoded_sql_expressions for cur.execute(f"SELECT * FROM t WHERE id={uid}"). Which remediation most completely removes the vulnerability class rather than masking the finding?

A. Cast uid to int before interpolation B. Add # nosec with a justification comment

C. Use a parameterized query with a placeholder and pass uid as a bound parameter

D. Escape single quotes in uid with a regex

Correct: C - Use a parameterized query with a placeholder and pass uid as a bound parameter

Rationale: Parameterized queries separate SQL structure from data, eliminating injection regardless of input shape. Integer casting and regex escaping are fragile allowlist/denylist mitigations, and # nosec suppresses the detector without fixing the flaw.

Q14. A logger configured with logging.getLogger('app').setLevel(logging.WARNING) emits records to a handler with setLevel(logging.DEBUG). A call to app.debug('x') produces no output. Which explanation is correct?

A. The handler level overrides the logger level, so DEBUG should appear

B. The logger's effective level filters the record before it reaches the handler

C. DEBUG records require logging.basicConfig(level=DEBUG) regardless of levels

D. propagate=False on the root logger discards the record

Correct: B - The logger's effective level filters the record before it reaches the handler

Section B - Directly

A. Increase the fuzzer's timeout B. Run the parser in a thread with a larger stack

C. Enforce a maximum nesting depth and reject inputs exceeding it

D. Catch RecursionError and return None

Correct: C - Enforce a maximum nesting depth and reject inputs exceeding it

Rationale: Bounding nesting depth constrains resource consumption at the input boundary, preventing stack exhaustion. Raising timeouts or stack size only delays the crash, and catching RecursionError is unreliable once the C stack is exhausted.

Q18. A CI pipeline runs coverage run -m pytest then coverage report --fail-under=90. A module with only if TYPE_CHECKING: imports reports uncovered lines. Which action is most appropriate?

A. Lower the threshold to 80% B. Add # pragma: no cover to type-checking blocks and enable coverage's branch analysis

C. Delete the type-checking imports D. Run tests with -O to skip the block Correct: B - Add # pragma: no cover to type-checking blocks and enable coverage's branch analysis

Rationale: Type-checking-only blocks never execute at runtime, so # pragma: no cover (with branch coverage enabled) accurately excludes them without masking real gaps. Lowering the bar, deleting imports, or running with -O degrades type safety or coverage fidelity.

Section C - Function

Q19.

A developer uses logging.info(f"user={user}") in a hot loop and disables INFO in production. Which combination of changes best improves both performance and security?

A. Switch to %-style lazy formatting and log a hashed user identifier

B. Use logging.debug with f-strings

C. Buffer messages in a list and flush at exit D. Set the logger level to CRITICAL and remove the log call Correct: A - Switch to %-style lazy formatting and log a hashed user identifier

Rationale: Lazy %-style formatting defers string construction until the record is emitted, avoiding cost when disabled, while hashing the identifier prevents PII leakage. Debug f-strings still format eagerly, buffering risks data loss, and removing logs destroys observability.

Q20. A property-based test uses Hypothesis to validate sort(xs). Which strategy most effectively uncovers subtle ordering bugs while controlling runtime?

A. Generate only lists of unique integers B. Use st.lists(st.integers()) with @settings(max_examples=5)

C. Use st.lists(st.integers()) with @settings(max_examples=1000, deadline=None) and assert sortedness plus permutation equivalence

D. Generate random floats and compare with ==

Correct: C - Use st.lists(st.integers()) with @settings(max_examples=1000, deadline=None) and assert sortedness plus permutation equivalence

Rationale: Broad integer lists with many examples and a deadline disabled exercise edge cases, while asserting both sortedness and permutation equivalence catches reordering or duplication bugs. Restricting to unique ints, too few examples, or float equality weakens the oracle.

Q21. A CI pipeline runs pytest --cov=src --cov-fail-under=90. After adding a new module, coverage drops to 87% and the build fails. Which pytest-cov configuration change most precisely restores the build while still enforcing 90% coverage only on the newly added module?

Section C - Function

Rationale: pytest's assertion rewriting produces detailed diffs for complex objects automatically; adding a message supplements context. Option A bypasses rewriting, C loses pytest's introspection, and D hides diagnostics.

Q24. A module uses logging.getLogger(__name__) and configures handlers at import time. Under pytest, log records from the module are not captured in caplog. Which design change most reliably enables capture?

A. Call logging.basicConfig(level=logging.DEBUG) at module top.

B. Add a FileHandler in the module to persist logs.

C. Defer handler configuration to the application entry point and let pytest manage the root logger.

D. Set logging.disable(logging.CRITICAL) in the module.

Correct: C - Defer handler configuration to the application entry point and let pytest manage the root logger.

Rationale: pytest's caplog fixture installs its own handler on the root logger; libraries that configure handlers at import interfere with propagation. Deferring configuration to the application entry point preserves library hygiene and enables capture.

Q25. A team wants deterministic tests for code that calls datetime.now(). Which approach best supports testability without monkeypatching the standard library globally?

A. Freeze time with freezegun in every test module via a conftest autouse fixture.

B. Inject a clock callable (e.g., clock=datetime.now) as a default parameter or dependency.

C. Patch datetime.datetime with unittest.mock.patch in each test.

D. Set the system clock in CI to a fixed date.

Correct: B - Inject a clock callable (e.g., clock=datetime.now) as a default parameter or dependency.

Rationale: Dependency injection of a clock is the most surgical, side-effect-free approach and aligns with testable design principles. Freezegun and global patching work but are broader and can mask unrelated time usage; altering the system clock is non-portable.

Q26. Which assertion strategy best balances coverage and maintainability when testing a function that returns a large nested dictionary whose schema is stable but values vary?

Section C - Function

A. Assert full equality against a hard-coded golden dict.

B. Assert only that the return value is a dict.

C. Assert on a curated subset of keys plus type/shape constraints.

D. Assert that the dict is non-empty and has more than three keys. Correct: C - Assert on a curated subset of keys plus type/shape constraints.

Rationale: Targeted assertions on stable keys and shape reduce brittleness while still catching meaningful regressions. Full equality (A) is fragile, and B/D are too weak to detect real defects.

Q27. Bandit reports B301 (pickle) on a deserialization path. Which change most directly preserves functionality while eliminating the vulnerability class?

A. Wrap pickle.loads in a try/except and log failures.

B. Replace pickle with a safe format such as JSON or a schema-validated parser.

C. Restrict pickle input length to a maximum size.

D. Run the deserialization inside a subprocess with reduced privileges. Correct: B - Replace pickle with a safe format such as JSON or a schema-validated parser.

Rationale: Pickle executes arbitrary code during unpickling; the only robust fix is to avoid it for untrusted data and use a safe serialization format. Length limits, exception handling, and sandboxing do not remove the code-execution primitive.

Section D - Security module-level patching.

Rationale: Module-level patches leak across tests and interact poorly with parallel execution; scoping patches to each test isolates state. Autospec improves fidelity but does not address leakage, and retries hide the underlying race.

Q31. A team uses logging.getLogger(__name__) throughout a package but configures handlers only in main.py via basicConfig(). A worker process imports a submodule directly and emits logs that never appear. Which root cause best explains the missing output?

A. basicConfig is idempotent and silently no-ops once any handler exists on the root logger; the submodule's import order triggered an earlier no-op configuration.

B. Child loggers created with __name__ do not propagate records to the root logger unless propagate=True is explicitly set on each child.

C. Logger levels default to WARNING, so INFO/DEBUG records from the submodule are filtered before reaching the root handler.

D. The submodule's logger name lacks a dot, so Python treats it as a top-level logger disconnected from the root hierarchy. Correct: A - basicConfig is idempotent and silently no-ops once any handler exists on the root logger; the submodule's import order triggered an earlier no-op configuration.

Rationale: basicConfig() is a no-op if the root logger already has handlers, so configuration performed after any prior logging call (or in a different import order) is silently ignored, leaving records unhandled. Propagation is on by default (B false), levels default to WARNING but that filters only lower-severity records, not all (C overgeneralized), and dotted names are not required for hierarchy (D false).

Q32. Under python -O, a module relies on assert to validate an untrusted deserialization payload before pickle.loads. Which statement most accurately characterizes the security consequence?

A. -O strips asserts, so the validation vanishes and arbitrary code execution via pickle may proceed unchecked.

B. -O converts asserts to warnings, so validation still runs but failures are downgraded to non-fatal log entries.

C. -O only disables asserts inside __debug__ blocks, so module-level asserts remain active and safe.

D. -O disables asserts but pickle.loads independently re-validates the payload via its own opcode whitelist. Correct: A - -O strips asserts, so the validation vanishes and arbitrary code execution via pickle may proceed unchecked.

Section D - Security

Rationale: -O removes assert statements entirely, so using asserts for security validation is unsafe; the check disappears at runtime and pickle can execute arbitrary code. Asserts are not downgraded (B), __debug__ blocks do not exempt module-level asserts (C), and pickle has no built-in opcode whitelist (D).

Q33. A CI pipeline runs bandit -r src/ and reports B301 (pickle) as LOW severity. The team suppresses it with # nosec. Which reasoning most correctly evaluates this decision from a secure-SDLC standpoint?

A. Suppression is acceptable because LOW severity findings are informational and never require triage.

B. Suppression is risky: severity reflects likelihood/impact heuristics, not exploitability in context; untrusted pickle input is an RCE vector regardless of the tool's default severity.

C. Suppression is required because Bandit's B301 is a known false positive whenever pickle is imported.

D. Suppression is fine only if the code also passes mypy --strict, because type checking proves the payload is trusted. Correct: B - Suppression is risky: severity reflects likelihood/impact heuristics, not exploitability in context; untrusted pickle input is an RCE vector regardless of the tool's default severity.

Rationale: Static analyzer severity is a heuristic, not a contextual risk judgment; deserializing untrusted pickle is remote code execution irrespective of Bandit's LOW label, so blanket # nosec without justification is unsafe. LOW findings still require triage (A), B301 is not inherently a false positive (C), and type checking does not establish data trustworthiness (D).

Q34. A pytest suite achieves 95% line coverage but misses a critical branch where an except ValueError handler is never executed. Which metric and tool combination most directly exposes this gap?

A. Line coverage via coverage.py; the handler lines are counted as covered because they are syntactically present.

B. Branch coverage via coverage.py --branch; it flags the unexecuted handler path as a partial branch.

C. Mutation testing via mutmut; it measures whether tests detect injected faults, which correlates directly with handler execution.

D. Cyclomatic complexity via radon; high complexity in the try/except guarantees the handler is untested.

Correct: B - Branch coverage via coverage.py --branch; it flags the unexecuted handler path as a partial branch.

Section E - Pytest

Q37.

A team configures logging.config.dictConfig with a QueueHandler feeding a QueueListener. Under high load, log records are dropped. Which configuration change most directly addresses this?

A. Increase the root logger level to DEBUG to ensure records are enqueued.

B. Set queue to a bounded queue.Queue(maxsize=N) and handle queue.Full by blocking or applying backpressure.

C. Add a second StreamHandler to the root logger to duplicate records to stderr.

D. Disable propagate on all child loggers to reduce record volume. Correct: B - Set queue to a bounded queue.Queue(maxsize=N) and handle queue.Full by blocking or applying backpressure.

Rationale: Dropped records under load typically stem from a bounded queue that discards on Full; explicit backpressure or blocking enqueue preserves records. Level changes (A) do not affect capacity, extra handlers (C) bypass the queue, and disabling propagation (D) loses records rather than preserving them.

Q38. A property-based test uses Hypothesis to validate a parse_amount function. A counterexample shrinks to b"\x00". Which interpretation best reflects Hypothesis's shrinking behavior?

A. The shrunk input is the original failing case; shrinking only minimizes string length, not structure.

B. Shrinking searches for a simpler input that still fails, so b"\x00" is a minimal reproducible counterexample for the property.

C. The shrunk input indicates the property is vacuously true for all other inputs.

D. Shrinking randomizes the seed to find a different failure, so the counterexample is not reproducible. Correct: B - Shrinking searches for a simpler input that still fails, so b"\x00" is a minimal reproducible counterexample for the property.

Rationale: Hypothesis shrinking reduces a failing example to a minimal input that still violates the property, yielding a small reproducible counterexample like b"\x00". It is not merely length reduction (A), does not imply vacuous truth (C), and shrinking is deterministic given the failure (D).

Section E - Pytest

Q39. A codebase uses assert for input validation in a public API. A reviewer recommends replacing them with explicit if ... raise ValueError. Which principle best justifies this change?

A. Asserts are slower than explicit raises, so performance is the primary concern.

B. Asserts express internal invariants and are removed under -O, so they must not enforce public contract validation.

C. Explicit raises integrate with logging, whereas asserts cannot be logged.

D. Asserts cannot include error messages, so they provide no diagnostic value. Correct: B - Asserts express internal invariants and are removed under -O, so they must not enforce public contract validation.

Rationale: Asserts document internal invariants and are stripped under optimization, making them unsuitable for validating public inputs; explicit exceptions enforce contracts in all modes. Performance (A) is not the core issue, asserts can be logged indirectly (C), and asserts do accept messages (D).

Q40. A security test must verify that a function rejects path traversal. Which test design most rigorously validates the control rather than merely the happy path?

A. Assert the function returns the input unchanged for ../etc/passwd.

B. Parameterize over encoded variants (..%2f, ..\, null-byte suffixes) and assert each raises or normalizes to a safe path.

C. Mock os.path and assert it was called with the raw input.

D. Check that the function's docstring documents traversal handling. Correct: B - Parameterize over encoded variants (..%2f, ..\, null-byte suffixes) and assert each raises or normalizes to a safe path.

Rationale: Rigorous negative testing enumerates encoded and platform-specific traversal variants and asserts rejection or safe normalization, exercising the control across realistic bypasses. Returning input unchanged (A) validates nothing, mocking internals (C) tests implementation not behavior, and docstring checks (D) are not security tests.

Q41. A service configures logging with a RotatingFileHandler and sets propagate=False on a child logger. A developer then adds a StreamHandler to the root logger. Which statement best describes the resulting output behavior?