Docsity

WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python,, Exams of Computer Security

Toggle sidebar
bg1
WGU D385 Software Security and Testing Static
Code Analysis & Flake8 Practice Lab Python,
Exams of Computer Security - Complete 39
Verified Q&A with Answers & Rationales for Exam
Prep
Q1
Which Flake8 invocation enforces a max line length of 100 while ignoring E203?
A. flake8 --max-line-length=100 --extend-ignore=E203
B. flake8 --line-length 100 --ignore E203
C. flake8 --config max_line=100 --skip=E203
D. flake8 --max-line-length 100 --disable E203
Answer: A
Rationale: Flake8 uses --max-line-length (pycodestyle) and --extend-ignore to add to the default ignore
list. --ignore replaces defaults (risking re-enabling unwanted codes), and the other flags are not valid
Flake8 options.
Q2
In secure SDLC terms, integrating Flake8 into a pre-commit hook primarily mitigates which risk?
A. Runtime injection attacks in production
B. Defects and insecure patterns reaching version control
C. Insufficient test coverage of business logic
D. Dependency supply-chain compromise
Answer: B
Rationale: Pre-commit linting shifts detection left, blocking insecure or defective code before it enters the
repository (NIST SSDF PW.7/PW.8). It does not address runtime exploitation, coverage, or dependency
integrity, which require other controls.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python, and more Exams Computer Security in PDF only on Docsity!

WGU D385 Software Security and Testing Static

Code Analysis & Flake8 Practice Lab Python,

Exams of Computer Security - Complete 39

Verified Q&A with Answers & Rationales for Exam

Prep

Q

Which Flake8 invocation enforces a max line length of 100 while ignoring E203?

A. flake8 --max-line-length=100 --extend-ignore=E B. flake8 --line-length 100 --ignore E C. flake8 --config max_line=100 --skip=E D. flake8 --max-line-length 100 --disable E

Answer: A Rationale: Flake8 uses --max-line-length (pycodestyle) and --extend-ignore to add to the default ignore list. --ignore replaces defaults (risking re-enabling unwanted codes), and the other flags are not valid Flake8 options.

Q

In secure SDLC terms, integrating Flake8 into a pre-commit hook primarily mitigates which risk?

A. Runtime injection attacks in production B. Defects and insecure patterns reaching version control C. Insufficient test coverage of business logic D. Dependency supply-chain compromise

Answer: B Rationale: Pre-commit linting shifts detection left, blocking insecure or defective code before it enters the repository (NIST SSDF PW.7/PW.8). It does not address runtime exploitation, coverage, or dependency integrity, which require other controls.

A function has C901 complexity 22. Which refactor most directly reduces mccabe complexity while preserving behavior?

A. Add type hints and docstrings B. Extract nested conditionals into helper functions C. Replace if/else with ternary expressions D. Add # noqa: C901 to the function

Answer: B Rationale: mccabe counts decision points (branches, loops, boolean operators); extracting branches into helpers lowers the count. Type hints/docstrings don't affect complexity, ternaries still count as branches, and noqa merely suppresses the finding.

Q

Which is the most secure remediation for CWE-89 SQL injection flagged during Python review?

A. Escape single quotes in user input before concatenation B. Use parameterized queries with bound parameters C. Restrict the database account to SELECT only D. Add a WAF rule blocking SQL metacharacters

Answer: B Rationale: Parameterized queries separate code from data, eliminating injection at the root (OWASP). Escaping is error-prone, least-privilege limits blast radius but not injection, and WAFs are compensating controls, not fixes.

Q

A flake8 plugin reports B608 (SQL built via string concat). Which test best verifies remediation?

A. Unit test asserting the SQL string equals expected text B. Integration test sending a malicious payload and asserting no injection C. Coverage test reaching 100% on the module D. Lint test confirming B608 no longer appears

Answer: B Rationale: A negative security test with an injection payload validates the behavior change. String equality tests don't prove safety, coverage is not security, and lint absence alone doesn't prove runtime safety (though it is a useful gate).

A Flake8 plugin reports E501 on a line containing a long URL in a comment. Which remediation best preserves the URL while satisfying PEP 8?

A. Add # noqa: E501 to the line to suppress the warning. B. Insert a backslash line continuation within the URL string. C. Break the URL across lines using implicit string concatenation. D. Move the URL to a separate module-level constant and reference it.

Answer: D Rationale: PEP 8 permits long URLs when they cannot be split; however, the cleanest fix is to extract the URL into a named constant, which also improves maintainability. Using # noqa suppresses the warning without fixing the underlying style issue, and backslash continuation or concatenation can alter the URL semantics or introduce errors.

Q

A developer writes: def f(x): return x if x else []. Flake8 with default plugins emits no warning. Which security-relevant weakness does this pattern most closely align with?

A. CWE-89 SQL Injection due to unparameterized input. B. CWE-476 NULL Pointer Dereference from unchecked None. C. CWE-20 Improper Input Validation because falsy values bypass checks. D. CWE-798 Use of Hard-coded Credentials embedded in source.

Answer: C Rationale: The conditional x if x else [] treats any falsy value (0, '', None, []) as equivalent to an invalid input, which can silently bypass validation and lead to CWE-20. Flake8 cannot detect this logic flaw because it is syntactically valid and stylistically acceptable.

Q

Which Flake8 invocation correctly enforces a maximum line length of 100 while ignoring the E203 rule?

A. flake8 --max-line-length=100 --ignore=E B. flake8 --max-line-length 100 --extend-ignore=E C. flake8 --line-length=100 --exclude=E D. flake8 --max-line-length=100 --select=E

Answer: B Rationale: --extend-ignore adds E203 to the default ignore list without overriding other defaults, and --max-line-length 100 is a valid space-separated form. --ignore=E203 would replace the entire default ignore list, --exclude filters files not codes, and --select=E203 would run only E203.

A team wants to enforce that all new code passes Flake8 before merge but allow legacy files to be excluded. Which configuration approach best supports this?

A. Add # noqa to every line in legacy files. B. Use a .flake8 file with exclude = legacy/ and run Flake8 in CI on changed files. C. Set --select=E,W,F globally and ignore failures in legacy directories. D. Run Flake8 only on the main branch after merge.

Answer: B Rationale: Excluding legacy directories in .flake8 and running Flake8 on changed files in CI enforces quality on new code without blocking on pre-existing issues. Blanket # noqa is unmaintainable, global select does not exclude legacy, and post-merge checks do not prevent defects from entering the main branch.

Q

A developer adds # noqa: E501 to a line. What is the effect compared to # noqa alone?

A. It suppresses all warnings on that line. B. It suppresses only E501 on that line. C. It reports E501 as an error instead of a warning. D. It disables E501 globally for the file.

Answer: B Rationale: # noqa: E501 is a targeted suppression that silences only the E501 code on that line, preserving detection of other issues. Bare # noqa suppresses all codes on the line, and neither changes severity nor global configuration.

Q

In a secure SDLC, at which phase is static code analysis with Flake8 most cost-effective for preventing security defects?

A. During production incident response. B. During the design phase before code is written. C. During development and pre-commit/CI checks. D. During post-release penetration testing.

Answer: C Rationale: Static analysis is most cost-effective when integrated into development and CI so defects are caught before merge, aligning with NIST SSDF practices. Design phase precedes code, and incident response or post-release testing are far more costly remediation points.

A CWE-89 finding shows string concatenation into cursor.execute(). Which remediation best satisfies SSDF secure coding?

A. Escape single quotes with replace("'", "''") before concatenation B. Use parameterized queries with bound placeholders C. Wrap the concatenated SQL in a try/except block D. Validate input length with a regex before concatenation

Answer: B Rationale: Parameterized queries separate SQL code from data, eliminating injection regardless of input content, which is the SSDF-aligned fix for CWE-89. Manual escaping, exception handling, and length validation do not remove the injection sink and remain bypassable.

Q

Which pytest construct correctly asserts that divide(1, 0) raises ZeroDivisionError during the call?

A. assert divide(1, 0) == ZeroDivisionError B. with pytest.raises(ZeroDivisionError): divide(1, 0) C. pytest.raises(divide, 1, 0, ZeroDivisionError) D. @pytest.raises(ZeroDivisionError) def test_divide(): divide(1, 0)

Answer: B Rationale: pytest.raises used as a context manager asserts the enclosed call raises the specified exception. Comparing the call result to the exception class, passing arguments in that order to pytest.raises, and decorating a test function are not valid pytest idioms for exception assertion.

Q

A pipeline needs Flake8 to fail only on security-relevant plugin codes, not style. Which configuration is correct?

A. select = E,W,F in setup.cfg B. extend-select = S in setup.cfg C. ignore = S in setup.cfg D. per-file-ignores = S in setup.cfg

Answer: B Rationale: extend-select = S adds the bandit-style security plugin codes to the selection so the build fails on those findings while retaining defaults. Selecting E,W,F targets style and pyflakes rather than security; ignore and per-file-ignores suppress rather than enforce S codes.

A SAST report lists a high-severity finding in vendored third-party code. What is the most defensible triage action?

A. Suppress it globally with a noqa comment B. Record it as accepted risk with owner and review date C. Delete the vendored directory from the repository D. Lower the severity threshold until it disappears

Answer: B Rationale: Vendored code cannot be fixed directly, so documenting it as accepted risk with an owner and review date follows SSDF risk-management practice. Global suppression hides the issue, deletion breaks functionality, and threshold manipulation falsifies reporting.

Q

Which setup.cfg section and key correctly set Flake8 max-line-length to 100?

A. [flake8] max-line-length = 100 B. [pycodestyle] max_line_length = 100 C. [flake8] max_line_length: 100 D. [flake8] line-length = 100

Answer: A Rationale: Flake8 reads its options from the [flake8] section using the key max-line-length (hyphenated). The [pycodestyle] section is not read by Flake8, and the other key spellings are unrecognized, so they leave the default in effect.

Q

A developer adds # noqa: E501 to a line. What is the precise effect in Flake8?

A. Suppresses all Flake8 messages on that line B. Suppresses only E501 on that line C. Suppresses E501 for the entire file D. Raises E501 to an error

Answer: B Rationale: The noqa directive with a code list suppresses only the listed codes on that physical line, so E501 is hidden while other violations still report. A bare # noqa would suppress all codes on the line; file-wide suppression requires per-file-ignores, and noqa never escalates severity.

Given code def f(a, b=[]): b.append(a); return b, which Flake8-bugbear check flags this and why?

A. B006, mutable default argument B. B008, function call in default argument C. B001, bare except D. B007, unused loop variable

Answer: A Rationale: B006 warns about mutable default arguments such as a list, which persist across calls and cause state leakage. B008 flags function calls in defaults, B001 flags bare except, and B007 flags unused loop variables, none of which apply here.

Q

Which Flake8 invocation correctly ignores E501 and W503 while selecting only errors (E) and pyflakes (F) codes?

A. flake8 --select=E,F --ignore=E501,W B. flake8 --extend-ignore=E501,W503 --select=E,F C. flake8 --ignore=E501,W503 --select=E,F D. flake8 --select=E,F --extend-select=E501,W

Answer: A Rationale: Flake8 applies --ignore after --select, so --select=E,F --ignore=E501,W503 yields E and F codes except E501 and W503. Option B uses extend-ignore, which adds to rather than replaces defaults, and C omits the select restriction; D extends selection instead of ignoring.

Q

A CI pipeline runs Flake8 and fails on any finding. Which strategy best balances security and developer productivity?

A. Run Flake8 with a curated select list of security-relevant plugins and fail only on high-severity codes. B. Disable all Flake8 checks in CI and rely on manual code review. C. Run Flake8 only on changed files with all default checks and fail on any warning. D. Use Flake8 only locally and never enforce it in CI.

Answer: A Rationale: A curated select list focusing on security plugins (e.g., bandit) and failing on high-severity codes reduces noise while catching real risks. Disabling checks (B), enforcing all defaults on changed files (C), or local-only use (D) either misses security issues or creates excessive false positives that erode adoption.

Which pytest assertion most directly verifies that a function raises ValueError with a specific message?

A. with pytest.raises(ValueError, match='invalid input'): f() B. assert f() raises ValueError('invalid input') C. with pytest.raises(Exception): f() D. assertRaises(ValueError, f, 'invalid input')

Answer: A Rationale: pytest.raises with match uses a regex to confirm the exception type and message. Option B is invalid syntax, C catches any Exception without checking the message, and D is unittest syntax not valid in a plain pytest test.

Q

Which CWE category is most directly addressed by enforcing Flake8-bandit B602 (subprocess with shell=True)?

A. CWE-78 OS Command Injection B. CWE-89 SQL Injection C. CWE-79 Cross-site Scripting D. CWE-502 Deserialization of Untrusted Data

Answer: A Rationale: B602 flags subprocess calls with shell=True, which enables OS command injection (CWE-78). CWE-89 concerns SQL, CWE-79 concerns XSS, and CWE-502 concerns unsafe deserialization, none of which are directly detected by B602.

Q

Under NIST SSDF, which practice is most aligned with integrating static analysis like Flake8 into the secure development lifecycle?

A. PW.7: Review and/or analyze human-readable code to identify errors and security vulnerabilities. B. PS.1: Protect all forms of code from unauthorized access and tampering. C. PO.3: Implement supporting toolchains for secure development. D. RV.1: Identify and confirm vulnerabilities on an ongoing basis.

Answer: A Rationale: SSDF PW.7 explicitly covers code review and static analysis to find errors and vulnerabilities. PS.1 addresses code protection, PO.3 toolchains, and RV.1 vulnerability response, which are related but not the direct static analysis practice.

In a pre-commit hook, flake8 --diff is used. What behavior does this provide?

A. It analyzes only lines changed relative to the Git index, reducing noise on legacy files. B. It compares Flake8 output against the previous CI run and fails on new findings only. C. It runs Flake8 in parallel across all files and diffs the results for consistency. D. It patches files automatically by applying autopep8 to the reported violations.

Answer: A Rationale: The --diff option restricts reporting to lines that differ from the Git index, enabling incremental adoption on legacy codebases. It does not compare CI runs (B), parallelize and diff (C), or auto-fix code (D).

Q

A function has McCabe complexity 12 with max-complexity=10. Which remediation best addresses the underlying security concern?

A. Add # noqa: C901 to suppress the warning and document the complexity. B. Increase max-complexity to 15 project-wide to match the codebase. C. Extract cohesive branches into smaller functions with single responsibilities. D. Replace the function with a dictionary dispatch that preserves the same branching.

Answer: C Rationale: High cyclomatic complexity correlates with untested paths and latent defects, including security-relevant edge cases. Refactoring into smaller, single-responsibility functions reduces complexity and improves testability. Suppression (A), threshold inflation (B), and dispatch that preserves branching (D) do not reduce the risk.

Q

Which unit test most directly validates a fix for a Flake8-reported F841 (local variable assigned but never used)?

A. A test asserting the function's return value equals the expected output for a valid input. B. A test that runs Flake8 programmatically and asserts F841 is absent from the module. C. A test that measures code coverage of the module and asserts 100% line coverage. D. A test that monkeypatches the unused variable to verify it is never read.

Answer: B Rationale: F841 is a static defect; the most direct regression test is a static-analysis assertion that the code no longer emits F841. Behavioral tests (A), coverage (C), and monkeypatching (D) do not verify removal of the static finding.

Under NIST SSDF (SP 800-218), integrating Flake8 into CI primarily satisfies which practice?

A. PO.5: Implement and maintain secure environments for software development. B. PS.1: Protect all forms of code from unauthorized access and tampering. C. PW.7: Review and/or analyze human-readable code to identify errors and security weaknesses. D. RV.1: Identify and confirm vulnerabilities on an ongoing basis.

Answer: C Rationale: PW.7 covers code review and static analysis to find errors and security weaknesses in human-readable code. PO.5 addresses environments, PS.1 protects code integrity, and RV.1 concerns vulnerability identification and confirmation, not code-level static analysis.