Docsity

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

Toggle sidebar
bg1
WGU D385 Task 1 Performance
Assessment Guide Software Security &
Testing Python Logging, Assertions, Static
1. A logging configuration uses logging.basicConfig(format='%(asctime)s
%(levelname)s %(message)s') and logs a user-supplied username directly. An attacker
sets the username to a string containing a newline followed by a forged log entry.
Which mitigation most directly prevents log injection while preserving structured
auditability?
A. Set the logging level to WARNING to reduce the attack surface.
B. Use a JSON formatter that serializes the message field and escapes control characters.
C. Wrap the log call in a try/except to catch injection exceptions.
D. Encode the username with base64 before logging.
Answer: B. Use a JSON formatter that serializes the message field and escapes control
characters.
Rationale: Structured JSON logging serializes and escapes newlines/control characters,
neutralizing forged entries while keeping fields queryable. Level changes and exception
handling do not sanitize content, and base64 obscures but does not structurally separate
attacker-controlled data from log metadata.
2. A developer writes: assert user.is_admin, 'denied' to guard a privileged function,
then deploys with PYTHONOPTIMIZE=1. Which statement best characterizes the
resulting security posture?
A. The assertion still raises AssertionError because the message is present.
B. The assertion is stripped, so the guard never executes and the function becomes
unconditionally accessible.
C. The assertion is converted to a warning but execution continues.
D. PYTHONOPTIMIZE only affects docstrings, so the assertion is unaffected.
Answer: B. The assertion is stripped, so the guard never executes and the function
becomes unconditionally accessible.
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
Page 1 of 29
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

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!

WGU D385 Task 1 Performance

Assessment Guide Software Security &

Testing Python Logging, Assertions, Static

1. A logging configuration uses logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s') and logs a user-supplied username directly. An attacker sets the username to a string containing a newline followed by a forged log entry. Which mitigation most directly prevents log injection while preserving structured auditability?

A. Set the logging level to WARNING to reduce the attack surface. B. Use a JSON formatter that serializes the message field and escapes control characters. C. Wrap the log call in a try/except to catch injection exceptions. D. Encode the username with base64 before logging.

Answer: B. Use a JSON formatter that serializes the message field and escapes control characters.

Rationale: Structured JSON logging serializes and escapes newlines/control characters, neutralizing forged entries while keeping fields queryable. Level changes and exception handling do not sanitize content, and base64 obscures but does not structurally separate attacker-controlled data from log metadata.

2. A developer writes: assert user.is_admin, 'denied' to guard a privileged function, then deploys with PYTHONOPTIMIZE=1. Which statement best characterizes the resulting security posture?

A. The assertion still raises AssertionError because the message is present. B. The assertion is stripped, so the guard never executes and the function becomes unconditionally accessible. C. The assertion is converted to a warning but execution continues. D. PYTHONOPTIMIZE only affects docstrings, so the assertion is unaffected.

Answer: B. The assertion is stripped, so the guard never executes and the function becomes unconditionally accessible.

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.

5. 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?

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.

Answer: 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.

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

Answer: 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.

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

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

Rationale: Patching out the module under test prevents its mutated code from executing, yielding zero kills regardless of test quality. Equivalent mutants are possible but unlikely across an entire module, and mutation testing does not require full branch coverage to operate.

8. A logging handler writes to a file with mode='w' on every application start. An incident review finds that audit logs from the previous run are missing. Which change best preserves audit integrity?

A. Switch to mode='a' and rotate files with a size-based handler. B. Increase the log level to CRITICAL to reduce writes. C. Buffer logs in memory and flush at shutdown. D. Write logs to stdout and rely on the shell to redirect.

Answer: A. Switch to mode='a' and rotate files with a size-based handler.

Rationale: Mode 'w' truncates the file at each start, destroying prior audit records; append mode with rotation preserves history while controlling size. Higher levels, in-memory buffering, and stdout redirection do not guarantee durable, tamper-resistant audit trails.

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

Answer: 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.

12. 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?

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

Answer: 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.

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

Answer: 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.

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

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

Rationale: A logger's level is checked first; if the record's severity is below the logger's effective level, it is discarded before handler-level filtering. Handler levels only refine what the logger already allowed, so options A/C/D misstate the filter ordering.

17. A fuzz target wraps a JSON parser and crashes only when given deeply nested arrays, exhausting the C stack. Which mitigation most directly addresses this denial-of-service class?

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

Answer: 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.

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

Answer: 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.

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

Answer: 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.

20. 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 ==

Answer: 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.

23. A test asserts assert result == expected with no message. In pytest, when the assertion fails on a large dict, which feature most improves diagnostic output without changing the assertion semantics?

A. Wrap the assertion in try/except and call logging.exception. B. Enable pytest's assertion rewriting (default) and add a descriptive message after a comma. C. Replace with self.assertEqual from unittest for richer diffs. D. Add --tb=no to suppress the traceback and rely on logs.

Answer: B. Enable pytest's assertion rewriting (default) and add a descriptive message after a comma.

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.

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

Answer: 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.

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

Answer: 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.

26. 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?

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.

Answer: 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.

29. In a security review, a developer proposes assert user.is_admin to gate an admin action in production code. Why is this considered an anti-pattern?

A. Assertions are slower than if-statements at runtime. B. Assertions can be stripped when Python runs with -O, silently disabling the check. C. Assertions cannot reference object attributes. D. Assertions raise SystemExit instead of AssertionError.

Answer: B. Assertions can be stripped when Python runs with -O, silently disabling the check.

Rationale: Python's -O flag removes assert statements, so security-relevant checks may vanish in optimized deployments. Assertions are for internal invariants; authorization must use explicit conditionals and proper exceptions.

30. A test suite uses unittest.mock.patch to stub a network client but tests intermittently fail when run in parallel. Which practice most improves reliability?

A. Increase the mock's side_effect to raise on any unexpected call. B. Use patch as a context manager or decorator scoped to each test rather than module-level patching. C. Set autospec=True on every patch call. D. Add retries to the test to mask flakiness.

Answer: B. Use patch as a context manager or decorator scoped to each test rather than 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.

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

Answer: 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).

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

Answer: 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).

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

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

Rationale: Branch coverage tracks whether both outcomes of conditional constructs (including exception paths) are exercised, exposing the never-taken handler. Line coverage can mark the handler lines as present without execution (A), mutation testing detects fault sensitivity but not branch execution per se (C), and complexity metrics measure structure, not test execution (D).