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 security audit reveals that an application logs full HTTP request bodies at
DEBUG level in production, and the log files are world-readable on the host. Which
combination of changes most effectively mitigates the risk while preserving
operational debuggability?
A. Raise the logging level to WARNING and remove all request-body logging
B. Introduce a logging filter that redacts sensitive fields, set file permissions to 640, and
gate DEBUG logging behind an environment flag
C. Switch to syslog and rely on the OS to protect log integrity
D. Encrypt the log files at rest and continue logging all request bodies at DEBUG
Answer: B. Introduce a logging filter that redacts sensitive fields, set file permissions
to 640, and gate DEBUG logging behind an environment flag
Rationale: Redaction filters remove sensitive data at the source, restrictive permissions
limit exposure, and environment-gated DEBUG prevents production leakage. Raising to
WARNING (A) destroys debuggability, syslog (C) does not redact content, and encryption
at rest (D) still leaves plaintext accessible to the application and any process reading logs.
2. Which statement most accurately distinguishes the appropriate use of assert
statements in production Python code versus their use in test suites?
A. assert is optimized away under python -O, so it should never be used for input
validation in production, but is appropriate in tests
B. assert should be used for all runtime validation because it raises AssertionError with a
clear message
C. assert is only valid inside unittest.TestCase methods and is a syntax error elsewhere
D. assert statements are always executed regardless of interpreter flags and are therefore
safe for security checks
Answer: A. assert is optimized away under python -O, so it should never be used for
input validation in production, but is appropriate in tests
Rationale: Python's -O flag strips assert statements, making them unreliable for production
validation; they are intended for internal sanity checks and test assertions. Option B
Page 1 of 32
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

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 security audit reveals that an application logs full HTTP request bodies at DEBUG level in production, and the log files are world-readable on the host. Which combination of changes most effectively mitigates the risk while preserving operational debuggability?

A. Raise the logging level to WARNING and remove all request-body logging B. Introduce a logging filter that redacts sensitive fields, set file permissions to 640, and gate DEBUG logging behind an environment flag C. Switch to syslog and rely on the OS to protect log integrity D. Encrypt the log files at rest and continue logging all request bodies at DEBUG

Answer: B. Introduce a logging filter that redacts sensitive fields, set file permissions to 640, and gate DEBUG logging behind an environment flag

Rationale: Redaction filters remove sensitive data at the source, restrictive permissions limit exposure, and environment-gated DEBUG prevents production leakage. Raising to WARNING (A) destroys debuggability, syslog (C) does not redact content, and encryption at rest (D) still leaves plaintext accessible to the application and any process reading logs.

2. Which statement most accurately distinguishes the appropriate use of assert statements in production Python code versus their use in test suites?

A. assert is optimized away under python -O, so it should never be used for input validation in production, but is appropriate in tests B. assert should be used for all runtime validation because it raises AssertionError with a clear message C. assert is only valid inside unittest.TestCase methods and is a syntax error elsewhere D. assert statements are always executed regardless of interpreter flags and are therefore safe for security checks

Answer: A. assert is optimized away under python -O, so it should never be used for input validation in production, but is appropriate in tests

Rationale: Python's -O flag strips assert statements, making them unreliable for production validation; they are intended for internal sanity checks and test assertions. Option B

ignores the -O stripping, C is factually wrong (assert works anywhere), and D is false because -O disables them.

5. mypy reports 'error: Incompatible return value type (got "Optional[str]", expected "str")' in a function that returns a value from a dict.get() call. Which change most precisely resolves the type error without weakening type safety?

A. Change the return type annotation to Optional[str] B. Add # type: ignore to the line C. Use a default value in dict.get() or explicitly handle the None case before returning D. Cast the result with typing.cast(str, ...)

Answer: C. Use a default value in dict.get() or explicitly handle the None case before returning

Rationale: Handling the None case or providing a default ensures a str is always returned, preserving the contract. Changing the annotation (A) weakens the interface, # type: ignore (B) suppresses rather than fixes, and cast (D) lies to the type checker without runtime guarantee.

6. In a CI pipeline, coverage reports show 95% line coverage but mutation testing (mutmut) reveals a mutation score of 40%. What does this discrepancy most strongly indicate about the test suite?

A. The tests execute most lines but fail to assert on the behavior those lines produce B. The coverage tool is misconfigured and should be replaced C. Mutation testing is unreliable and should be ignored D. The codebase has too many lines to test effectively

Answer: A. The tests execute most lines but fail to assert on the behavior those lines produce

Rationale: High line coverage with low mutation score indicates tests run code without meaningful assertions, allowing mutants to survive. B and C misattribute the problem to tooling, and D is irrelevant to the assertion gap.

7. A logging configuration uses a RotatingFileHandler with maxBytes=10MB and backupCount=5, but an incident shows logs older than the rotation window were lost during a high-volume attack. Which adjustment most directly improves forensic retention without unbounded disk growth?

A. Increase the logging level to CRITICAL B. Switch to a TimedRotatingFileHandler with a longer retention interval and off-host shipping C. Disable rotation and write to a single file D. Compress logs in memory before writing

Answer: B. Switch to a TimedRotatingFileHandler with a longer retention interval and off-host shipping

Rationale: Timed rotation with longer retention plus off-host shipping preserves forensic data while bounding local disk use. Raising level (A) reduces detail, disabling rotation (C) risks disk exhaustion, and in-memory compression (D) does not address retention.

8. Which pytest feature best supports property-based testing to uncover edge cases a hand-written example-based test would miss?

A. pytest.mark.parametrize with a fixed list of inputs B. hypothesis.given with strategies generating varied inputs C. pytest.fixture(scope='session') D. pytest.raises context manager

Answer: B. hypothesis.given with strategies generating varied inputs

Rationale: Hypothesis generates diverse inputs and shrinks failing cases, exposing edge cases beyond fixed examples. Parametrize (A) uses predefined inputs, fixtures (C) manage setup, and pytest.raises (D) only asserts exceptions.

11. A security review flags a module for using assert to validate that an authenticated user's role is 'admin' before executing a privileged operation. Why is this pattern considered a critical vulnerability in production?

A. Assertions raise AssertionError, which is not a subclass of Exception and therefore cannot be caught by standard error handlers. B. Python's -O flag strips assert statements entirely, so the authorization check silently vanishes while the privileged operation still executes. C. Assertions evaluate both operands eagerly, leaking the admin role value into logs through side-channel timing. D. Assertions are only evaluated inside unittest test cases, so production code never runs them.

Answer: B. Python's -O flag strips assert statements entirely, so the authorization check silently vanishes while the privileged operation still executes.

Rationale: Running with -O or PYTHONOPTIMIZE removes all assert statements, so an authorization guard built on assert is compiled away and the privileged path runs unchecked. Assertions are for internal invariants, not security enforcement; A is wrong because AssertionError subclasses Exception, C misstates evaluation semantics, and D is false.

12. A team configures a root logger with a StreamHandler at DEBUG and a FileHandler at ERROR, then calls logging.getLogger('app').warning('x'). Given Python's effective-level and handler-level filtering rules, what is emitted?

A. Nothing, because the child logger inherits the root's DEBUG level but its own default level is WARNING and propagation is disabled. B. The record is filtered at the logger level (WARNING >= effective level) and then each handler independently decides: stream emits it, file drops it. C. Only the FileHandler emits it, since handler levels override the logger's effective level. D. Both handlers emit it because the root logger's DEBUG level is the lowest configured threshold.

Answer: B. The record is filtered at the logger level (WARNING >= effective level) and then each handler independently decides: stream emits it, file drops it.

Rationale: A record passes the logger's effective level first, then each attached handler applies its own level: the DEBUG stream handler emits the WARNING, while the ERROR

file handler discards it. A is wrong because child loggers default to NOTSET and inherit the root level; C and D invert the two-stage filtering model.

15. A developer writes with pytest.raises(ValueError): parse('bad'), but the test passes even when parse raises TypeError. Which pytest behavior explains this false positive, and what is the correct fix?

A. pytest.raises matches by MRO, so TypeError is a subclass of ValueError; use pytest.raises(ValueError, match=...). B. pytest.raises catches any exception unless strict=True; the fix is to pass strict=True to pytest.raises. C. The context manager only fails if no exception is raised; TypeError is not caught by pytest.raises(ValueError), so the test should already fail - the premise is incorrect. D. pytest.raises catches Exception by default; the fix is to use except ValueError in a try/except block instead.

Answer: C. The context manager only fails if no exception is raised; TypeError is not caught by pytest.raises(ValueError), so the test should already fail - the premise is incorrect.

Rationale: pytest.raises(ValueError) re-raises any exception that is not an instance of ValueError, so a TypeError would fail the test - the described false positive cannot occur with this code. A is false (TypeError is not a ValueError subclass), and B/D misstate pytest.raises semantics.

16. A test uses unittest.mock.patch('mymodule.requests.get') but the code under test imports requests as import requests and calls requests.get. The mock has no effect. What is the correct patching target and principle?

A. Patch 'requests.get'; patch always targets the original definition site. B. Patch 'mymodule.requests.get'; patch targets where the object is looked up (the importing module's namespace), not its origin. C. Patch 'requests.get' with create=True; the create flag resolves namespace mismatches. D. Patch 'mymodule.requests'; you must replace the whole module object to intercept get.

Answer: B. Patch 'mymodule.requests.get'; patch targets where the object is looked up (the importing module's namespace), not its origin.

Rationale: unittest.mock.patch replaces the name in the namespace where it is looked up - here mymodule.requests.get - so the code under test resolves the mock. A and C misstate the lookup rule; D replaces the module unnecessarily and breaks other attributes.

19. A CI gate fails when branch coverage drops below 85%, yet a critical authentication bypass ships undetected. Which testing principle best explains this failure of the gate?

A. Branch coverage is a weaker metric than statement coverage, so the gate is misconfigured. B. Coverage measures executed code, not the adequacy of assertions or the exploration of input space, so high coverage can coexist with untested security-relevant behavior. C. Coverage tools cannot measure code that uses assertions, so security paths are invisible. D. The gate should use mutation testing exclusively, since coverage is always meaningless.

Answer: B. Coverage measures executed code, not the adequacy of assertions or the exploration of input space, so high coverage can coexist with untested security-relevant behavior.

Rationale: Coverage quantifies which lines/branches executed, not whether assertions validate behavior or whether adversarial inputs were explored; a bypass can sit on a covered branch with no effective oracle. A misstates the metric hierarchy, C is false, and D overstates the case against coverage.

20. A developer wants to guarantee that a production service never emits stack traces containing secrets, even when unexpected exceptions occur. Which logging configuration achieves this most robustly?

A. Set the logger level to CRITICAL so lower-severity exceptions are never logged. B. Attach a custom Filter that redacts sensitive patterns from record.msg, record.args, and record.exc_info before formatting, and log exceptions with exc_info=True. C. Use print() instead of logging for exception output to avoid formatter processing. D. Disable propagation and rely on the default formatter, which omits exception details.

Answer: B. Attach a custom Filter that redacts sensitive patterns from record.msg, record.args, and record.exc_info before formatting, and log exceptions with exc_info=True.

Rationale: A redacting Filter that scrubs msg, args, and exc_info is the only approach that sanitizes both the message and the traceback regardless of severity. A suppresses rather than redacts, C bypasses logging controls entirely, and D is false - the default formatter does include exception text.

23. A repository's CI runs bandit -r src/ and reports B608 (hardcoded SQL) on a line using a parameterized query with a constant table name. What is the most defensible engineering response?

A. Suppress B608 globally in the Bandit config to keep the build green. B. Refactor the query to remove the constant table name. C. Add a targeted # nosec B608 with a comment justifying the constant, since the table name is not user-controlled. D. Switch from Bandit to Pylint, which does not flag SQL construction.

Answer: C. Add a targeted # nosec B608 with a comment justifying the constant, since the table name is not user-controlled.

Rationale: A targeted # nosec B608 with justification is the accepted practice for a verified false positive, preserving the rule's signal elsewhere. Global suppression (A) blinds the tool to real findings, refactoring a constant table name (B) is unnecessary, and switching tools (D) merely hides the issue rather than resolving it.

24. A developer writes assert user.is_admin to gate a privileged operation in production code. Which statement best characterizes the security risk?

A. Assertions are removed when Python runs with -O, so the check silently disappears, enabling privilege bypass. B. Assertions raise AssertionError, which is uncaught and crashes the process, causing a denial of service. C. Assertions are evaluated lazily, so the check may not run on the first call. D. Assertions cannot reference attributes, so user.is_admin is always falsy.

Answer: A. Assertions are removed when Python runs with -O, so the check silently disappears, enabling privilege bypass.

Rationale: The -O flag strips assert statements entirely, so a security gate built on assert vanishes in optimized deployments. Assertions are eager, not lazy (C), can reference attributes (D), and an AssertionError crash (B) is a lesser concern than the silent bypass.

25. A test suite uses unittest.mock.patch on requests.get and asserts it was called once. The production code actually calls requests.get via an aliased import from requests import get. Why might the test pass while production remains broken?

A. patch replaces the attribute on the module object, so aliased references bound earlier are unaffected, and the assertion checks the wrong target. B. patch only works on class methods, not module-level functions. C. requests.get is a C extension and cannot be patched. D. The mock returns a MagicMock that always equals the real response.

Answer: A. patch replaces the attribute on the module object, so aliased references bound earlier are unaffected, and the assertion checks the wrong target.

Rationale: patch('requests.get') rebinds the attribute on the requests module, but from requests import get created an independent name binding in the importing module, so the production call bypasses the mock. The assertion then verifies a call that never occurred in the real path, giving a false green. patch works on module functions (B), requests is pure Python (C), and MagicMock equality (D) is irrelevant.

26. Which property of pytest.mark.parametrize most improves failure diagnosis compared to a loop over cases inside a single test function?

A. It runs cases in parallel across processes by default. B. It generates a distinct test ID per parameter set, so failures localize to a single case. C. It caches results so re-runs skip unchanged cases. D. It automatically retries flaky parameter sets.

Answer: B. It generates a distinct test ID per parameter set, so failures localize to a single case.

Rationale: Parametrize yields one test item per case with a unique ID, so a failure points to the specific inputs rather than aborting the loop at the first failure. Parallelism (A), caching (C), and retries (D) are not default behaviors of parametrize.

29. A flaky test fails only when run in the full suite but passes in isolation. The test relies on a module-level mutable list that another test mutates. Which fix best addresses the root cause?

A. Add time.sleep(0.1) before the assertion to stabilize timing. B. Mark the test with @pytest.mark.flaky(reruns=3) to mask the failure. C. Replace the shared module-level list with a fixture that constructs a fresh instance per test. D. Reorder the suite so the offending test runs first.

Answer: C. Replace the shared module-level list with a fixture that constructs a fresh instance per test.

Rationale: The failure is test pollution from shared mutable state; a per-test fixture restores isolation and eliminates order dependence. Sleeping (A) does not fix shared state, reruns (B) hide the defect, and reordering (D) leaves the latent coupling in place.

30. In a security review, which use of eval() is least objectionable from a secure-coding standpoint?

A. eval(user_input) to evaluate a user-supplied arithmetic expression. B. eval(config_string) where config_string is loaded from an untrusted network source. C. ast.literal_eval(user_input) restricted to literals, used instead of eval for parsing. D. eval(open('plugin.py').read()) to dynamically load plugins at runtime.

Answer: C. ast.literal_eval(user_input) restricted to literals, used instead of eval for parsing.

Rationale: ast.literal_eval parses only Python literals and raises on arbitrary expressions, eliminating code execution-the safe replacement for eval in parsing scenarios. Options A, B, and D all evaluate untrusted or attacker-influenced input with full interpreter semantics, enabling arbitrary code execution.

31. A test suite uses caplog.at_level(logging.WARNING) while the module under test configures logging.basicConfig(level=logging.INFO) at import time. Which statement best explains why the test still captures INFO-level records emitted inside the function?

A. caplog.at_level temporarily lowers the handler level, but the root logger level set by basicConfig still filters INFO records before propagation. B. caplog.at_level sets both the logger and handler levels to WARNING, so INFO records are dropped unless propagate is disabled. C. caplog.at_level sets the level on the handler attached by caplog and on the specified logger, but records are still gated by the effective level of the originating logger, which basicConfig may have left at INFO. D. basicConfig is idempotent and therefore ignored during tests, so the root logger defaults to WARNING and caplog's handler level is the only filter.

Answer: C. caplog.at_level sets the level on the handler attached by caplog and on the specified logger, but records are still gated by the effective level of the originating logger, which basicConfig may have left at INFO.

Rationale: caplog.at_level sets the level on the caplog handler and on the named logger, but emission is still gated by the originating logger's effective level; basicConfig's INFO setting on the root logger can therefore allow INFO records through. Options A and B misdescribe which levels caplog manipulates, and D incorrectly claims basicConfig is a no-op when it is actually idempotent only after the first successful call.