


















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



















A+ VERIFIED
Clinical | Rationale-Driven - Pass Guaranteed - A+ Graded
119
QUESTIONS
1
SECTIONS
119
RATIONALES
WHAT THIS COVERS
01 Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)
02 Static code analysis
03 Flake8 linting
04 Python vulnerability mitigation
05 Secure logging
06 Software testing methodologies
ABOUT THIS ASSESSMENT This practice exam assesses mastery of secure coding principles, static code analysis, Flake8 linting, Python vulnerability mitigation, secure logging, software testing methodologies, and remediation within the SDLC, aligned to WGU D385 competencies and current OWASP/CWE/NIST standards.
A. Concatenate raw user input into log messages B. Sanitize CR/LF and encode user-controlled fields before logging C. Log only at DEBUG level in production D. Store logs in a world-readable file Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: CWE-117 occurs when untrusted input containing newline characters forges log entries; sanitizing CR/LF and encoding user data prevents this. Concatenation enables injection, DEBUG-only logging reduces detection, and world-readable logs violate confidentiality (CWE-532).
A. A stub returning a fixed boolean B. A mock asserting the hash function was called with expected args C. An integration test hitting the production database D. A fuzz test generating random passwords Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: A mock verifies interaction behavior-that the verifier calls the hash function with correct arguments-isolating the unit under test. A stub only supplies canned output without verifying interaction; integration and fuzz tests do not isolate the unit or verify the call contract.
A. shell=True with quoted args B. Passing an argument list with shell=False C. Using os.system with sanitized strings D. Encoding commands as base Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Passing a list with shell=False bypasses the shell, so metacharacters cannot inject commands. shell=True, os.system, and base64 encoding all still route through shell interpretation or add no protection.
A. Confirming password hashes use a current memory-hard KDF B. Checking that login pages return HTTP 200 C. Verifying session cookies lack the HttpOnly flag D. Ensuring error messages reveal stack traces for debugging Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: ASVS authentication requirements mandate strong, current password storage such as memory-hard KDFs (e.g., Argon2id). HTTP 200 checks are superficial, missing HttpOnly weakens sessions, and stack-trace disclosure violates secure error handling.
A. Concatenating user input into f-strings before logging B. Sanitizing CR/LF from user-controlled values before logging C. Logging at DEBUG level only D. Writing logs to stdout without formatting Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: CWE-117 arises when attacker-controlled newlines forge log entries; stripping CR/LF (or using structured logging) neutralizes it. F-string concatenation worsens injection, and log level or stream choice does not prevent it.
A. It cannot parse syntax errors B. It lacks runtime data-flow across dynamic dispatch C. It enforces PEP 8 style D. It requires unit tests to run Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: SAST analyzes code statically; Python's dynamic dispatch, reflection, and metaprogramming obscure taint flows, causing missed vulnerabilities. Syntax errors, style rules, and test execution are unrelated to false-negative taint analysis.
A. Hardcoded credentials flagged by a security linter plugin B. Lines exceeding 79 characters C. Trailing whitespace on blank lines D. Missing blank line between function definitions Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: E501 selects only line-length violations, so security rules (e.g., hardcoded passwords via flake8-bandit/bandit plugins) are never executed. The other options are style checks that E501 or default pycodestyle rules would catch, not security defects.
A. Resolve with os.path.realpath and verify it starts with the base directory. B. Strip '../' substrings from the filename. C. URL-encode the filename before use. D. Restrict filenames to lowercase alphanumerics. Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Canonicalizing with realpath and checking the result is within the intended base directory defeats traversal regardless of encoding tricks. Stripping '../' misses encoded/alternate separators, URL-encoding is reversible, and lowercase restriction is not a traversal control.
A. Enable E501 and W503 to enforce line-length and line-break style. B. Enable C901 with a low max-complexity threshold and select bandit checks. C. Enable F401 and F841 to catch unused imports and variables. D. Enable E302 and E305 to enforce blank-line conventions. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: C901 flags functions exceeding a complexity threshold, and bandit plugins surface security issues like hardcoded passwords or eval use; together they target security-relevant complexity. E501/W503, F401/F841, and E302/E305 address style and unused-code hygiene, not security complexity.
A. flake8 --select=E,W,F --max-line-length=79 with bandit run separately B. flake8 --extend-select=S --max-line-length=88 plus flake8-bandit plugin C. flake8 --ignore=E501,W503 --enable-security with pylint-security D. flake8 --max-complexity=10 --format=json with safety check Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: flake8-bandit exposes Bandit security checks as Flake8 'S' codes; --extend-select=S enables them alongside PEP 8, and --max-line-length=88 aligns with Black. Option A omits integrated security linting; C uses a nonexistent flag and wrong tool; D checks dependencies, not source security.
A. Escape single quotes in the input before concatenation. B. Use parameterized queries with bound parameters via the DB-API. C. Restrict the route to authenticated users only. D. Log the raw query for later forensic review. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Parameterized queries separate code from data, structurally preventing SQL injection (CWE-89). Escaping is error-prone, authentication does not stop injection, and logging the query increases exposure without fixing the flaw.
A. A01:2021 Broken Access Control B. A03:2021 Injection C. A07:2021 Identification and Authentication Failures D. A05:2021 Security Misconfiguration Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: A01 Broken Access Control explicitly includes missing function-level access control and privilege escalation. Injection concerns untrusted data in interpreters, A07 concerns identity proofing, and A05 concerns configuration weaknesses.
A. Move the key to an environment variable loaded at runtime and rotate it B. Base64-encode the key in source C. Add the key to .gitignore after commit D. Rename the variable to avoid detection Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Secrets must be removed from source, loaded from environment or a secrets manager, and rotated because Git history retains them (CWE-798). Encoding, gitignore after commit, or renaming does not remove exposure and leaves the credential compromised.
A. Assert the function raises ValueError for input '../../etc/passwd'. B. Assert os.path.exists returns False after calling the function. C. Assert the returned path starts with the configured base directory using Path.resolve().is_relative_to(base). D. Mock open() and assert it was never called with a path containing '..'. Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Canonicalizing with Path.resolve() and checking is_relative_to(base) verifies containment against encoded/symlink traversal, the strongest invariant. A single string assertion (A) is bypassable; exists (B) is environment-dependent; mocking open (D) tests implementation, not security behavior.
A. Disable the rule globally to prevent future noise B. Document a justified suppression with a scoped inline comment and reviewer sign-off C. Delete the flagged code path without analysis D. Mark the build as passing by lowering the severity threshold Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: NIST SSDF and OWASP recommend triaging SAST findings and, for verified false positives, recording a scoped, justified suppression with peer review so auditability is preserved. Disabling rules or lowering thresholds hides real defects; deleting code without analysis risks regression.
A. [flake8]\nmax-line-length = 100\nextend-ignore = E B. [flake8]\nmax_line_length=100\nignore=E C. [flake8]\nline-length = 100\nskip = E D. [flake8]\nmax-length:100\nignore: E Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Flake8 reads INI-style keys max-line-length and extend-ignore (hyphenated). Underscored/hyphenated variants, wrong key names (line-length, max-length), and colon syntax are not recognized by Flake8.
A. flake8-docstrings and flake8-import-order. B. flake8-bandit and flake8-bugbear. C. flake8-quotes and flake8-commas. D. flake8-builtins and flake8-comprehensions. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: flake8-bandit surfaces security issues and flake8-bugbear catches likely bugs, giving security-relevant lint coverage. The other plugins enforce style or minor correctness conventions with little security impact.
A. A unit test asserting the query string equals expected text B. A test submitting quote and comment payloads expecting no error or leak C. A snapshot test of the HTML response body D. A load test measuring query latency under concurrency Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Negative security tests with injection payloads verify the vulnerability is actually mitigated. String-equality, snapshot, and load tests do not exercise injection behavior and can pass despite the flaw.
A. Direct string equality with early return on mismatch. B. hmac.compare_digest over fixed-length byte representations. C. Hash both values with MD5 and compare hex digests. D. Compare lengths first, then characters in reverse order. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: hmac.compare_digest performs a constant-time comparison, preventing timing side channels (CWE-208). Early-return equality, MD5 hashing (also cryptographically broken), and reversed comparison all leak timing information.
A. Pin exact versions in requirements.txt and run pip-audit in CI on every build. B. Allow latest versions and rely on developers to review release notes. C. Vendor all packages once and never update them to ensure stability. D. Use only packages with no transitive dependencies to reduce risk. Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Pinning exact versions with continuous vulnerability scanning (pip-audit) provides reproducible, auditable dependency provenance per SSDF PS.3. Unpinned versions, frozen vendoring, and avoiding transitive deps either miss vulnerabilities or are impractical.
A. Adding a try/except around execute() B. Replacing string concatenation with parameterized queries C. Escaping single quotes with replace() D. Enabling autocommit Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Parameterized queries bind values separately from SQL, eliminating injection. Exception handling, manual quote escaping (bypassable), and autocommit do not address the root cause.
A. Add '# nosec B608' with a justification comment and review approval. B. Disable B608 globally in the bandit configuration. C. Rename the variable to avoid the pattern match. D. Move the query into a separate module excluded from scanning. Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Targeted '# nosec' with justification and review preserves traceability while documenting the risk acceptance. Global disablement, renaming to evade detection, and excluding modules undermine the scanner and hide real risk.
A. Concatenating the identifier after escaping single quotes. B. Validating the identifier against a strict allowlist before interpolation. C. Wrapping the query in a transaction with rollback. D. Encoding the identifier with base64 before concatenation. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: When identifiers cannot be bound as parameters, an allowlist of known-safe values prevents injection per OWASP guidance. Manual escaping is error-prone, transactions do not stop injection, and base64 encoding is reversible and provides no security.
A. Total number of warnings generated B. Lines of code scanned per minute C. Precision and recall against a labeled vulnerability benchmark D. Number of rules enabled by default Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Precision and recall measured against a labeled benchmark quantify true-positive and false-negative performance, the meaningful measure of detection effectiveness. Warning volume, throughput, and rule counts do not indicate accuracy and can reward noisy tools.
A. PW.4 Reuse well-secured software with continuous vulnerability monitoring B. PS.1 Protect all forms of code from tampering C. PO.3 Implement supporting toolchains D. RV.2 Assess, prioritize, and remediate vulnerabilities Answer: D [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: NIST SSDF RV.2 requires assessing, prioritizing, and remediating discovered vulnerabilities, which governs dependency remediation workflow. PW.4 covers secure reuse, PS.1 protects code integrity, and PO.3 addresses toolchains.
A. Log the submitted username and password hash at DEBUG level B. Log a generic failure with timestamp, source IP, and correlation ID C. Suppress all failure logs to avoid log injection D. Log only the HTTP status code with no context Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Security logging should capture sufficient context (time, source, correlation ID) for detection and forensics while excluding secrets, per OWASP Logging guidance. Logging credentials or hashes leaks sensitive data; suppressing logs defeats monitoring; status-only logs lack investigative value.
A. Rely on developers' local editors with default settings B. Pin flake8 and security plugins in a shared config, run in CI, fail on violations C. Run flake8 only at release time on changed files D. Disable E501 to reduce noise and enable only W Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Pinning versions, centralizing configuration, and enforcing in CI with a failing gate ensures consistent, repeatable security linting per NIST SSDF practices. Local-only, release-only, or style-only configurations leave gaps and drift.
A. Vendoring all dependencies into the repository B. Continuous SCA scanning with pinned versions and prompt patching C. Increasing unit test coverage to 100% D. Obfuscating dependency names in requirements files Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Software composition analysis with pinned, tracked versions and timely patching directly addresses vulnerable third-party components, aligning with SSDF PW.4 and RV.1. Vendoring, coverage, and obfuscation do not detect or remediate known CVEs.
A. Conducting threat modeling during design for each new microservice. B. Maintaining an approved component inventory with provenance and vulnerability monitoring. C. Requiring signed commits and mandatory peer review before merge. D. Running DAST scans against staging before each release. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: PW.4 concerns selecting and reusing well-secured components; an approved inventory with provenance and continuous vulnerability monitoring directly implements it. Threat modeling maps to PW.1, code review to PW.7/PS.2, and DAST to PW.8/PW.9.
A. Escaping single quotes with a custom regex before concatenation B. Using parameterized queries with bound placeholders C. Wrapping the query in a try/except and logging exceptions D. Enforcing a maximum length on the input string Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Parameterized queries separate code from data so user input cannot alter SQL structure, which is the definitive CWE- remediation. Regex escaping, exception handling, and length limits are bypassable and do not address the root cause.
A. Replace pickle with a schema-validated JSON parser B. Wrap pickle.loads in a try/except block C. Run deserialization inside a subprocess with a timeout D. Add an HMAC check after deserialization completes Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: CWE-502 is unsafe deserialization; pickle can execute arbitrary code, so replacing it with a non-executable, schema-validated format removes the weakness. Exception handling, subprocess isolation, and post-hoc HMAC checks do not prevent code execution during load.
A. A01: Broken Access Control B. A03: Injection C. A05: Security Misconfiguration D. A07: Identification and Authentication Failures Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Untrusted data concatenated into SQL is the canonical Injection (A03) flaw. Access control, misconfiguration, and authentication categories address different weaknesses.
A. A pre-commit hook that runs Flake8 style checks only. B. A CI policy that fails the build on new high-severity SAST findings. C. A quarterly manual code review of the main branch. D. A dashboard that displays SAST findings to managers weekly. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: A CI gate that fails builds on new high-severity findings enforces remediation before merge, operationalizing SSDF PW.7/PW.8. Style-only hooks, periodic reviews, and reporting dashboards do not block vulnerable code from reaching production.
A. Signing pickles with HMAC B. Replacing pickle with JSON serialization C. Restricting unpickling to authenticated users D. Compressing pickles before storage Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: pickle deserialization can execute arbitrary code even from signed payloads if the key leaks; JSON (with schema validation) avoids code execution entirely. HMAC, auth gating, and compression do not eliminate the deserialization gadget risk.
A. Encrypt the credential string in source with a static AES key. B. Inject secrets at runtime from a managed vault via workload identity. C. Store credentials in a .env file committed with the repository. D. Obfuscate the credential using base64 within settings.py. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Runtime injection from a vault using workload identity removes secrets from code and images, satisfying SSDF PS.6 and OWASP guidance. Encryption with a static key, committed .env files, and base64 obfuscation all leave recoverable secrets in the repository.
A. PW.4: Reuse well-secured software B. PS.2: Provide a mechanism to verify software release integrity C. PW.7: Review and/or analyze code for vulnerabilities D. PO.5: Implement and maintain secure environments Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: PW.7 covers code review/analysis to detect vulnerabilities-exactly what automated linting/SAST in CI provides. PW.4, PS.2, and PO.5 address reuse, release integrity, and environment hardening.
A. Escape shell metacharacters in the input before interpolation B. Use subprocess.run with a list of args and shell=False C. Wrap the command in shlex.quote only when input contains spaces D. Log the command and rely on WAF rules to block injection Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Passing an argument list with shell=False bypasses the shell entirely, eliminating command-injection (CWE-78). Quoting and escaping are error-prone mitigations; logging and WAFs are detective/preventive layers, not root-cause fixes.
A. Add a noqa comment to suppress E501 on that line. B. Refactor using implicit line joining inside parentheses. C. Increase max-line-length in setup.cfg to silence the error. D. Convert the line into a triple-quoted string literal. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Implicit joining inside parentheses is PEP 8-compliant and avoids backslash continuations, which are fragile and can hide injected content. Suppressing with noqa or raising max-line-length masks the defect, and wrapping code in a string literal changes semantics and can create injection risk.
A. assert_called() on the check after the test completes B. A side_effect on the data accessor that asserts the check's mock was called C. Patching the check with return_value=True and asserting the result D. Using assert_not_called() on the data accessor Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Attaching a side_effect to the data accessor lets the test assert ordering, proving the check ran before access. assert_called only proves invocation, return_value=True bypasses ordering, and assert_not_called on the accessor tests the opposite behavior.
A. PW.4 Reuse existing well-secured software B. PS.1 Protect all forms of code from tampering C. PW.7 Review and/or analyze human-readable code for vulnerabilities D. RV.1 Identify and confirm vulnerabilities on an ongoing basis Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: SSDF PW.7 explicitly requires code review and/or automated analysis to find vulnerabilities. PW.4 concerns reuse, PS. integrity, and RV.1 is ongoing vulnerability response.
A. A setup.cfg [flake8] section listing select = E,W,F only B. A tox.ini [flake8] section with extend-select = S,B and max-line-length tuned C. A .flake8 file with ignore = S,B to reduce noise D. Relying on default Flake8 behavior with no configuration Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: extend-select = S,B activates bandit (S) and bugbear (B) security-relevant checks while retaining defaults, giving CI meaningful coverage. Selecting only E,W,F omits security plugins; ignoring S,B or using defaults disables them.
A. flake8-bandit (B105/B106) with a custom baseline and CI fail threshold B. flake8-bugbear alone with default selectors enabled C. flake8-import-order plus flake8-comprehensions D. pycodestyle E501 with max-line-length raised to 200 Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Bandit's B105/B106 checks target hardcoded password/secret strings, and a baseline plus fail threshold prevents noisy regressions in CI. Bugbear, import-order, comprehensions, and E501 are style/complexity checks that do not detect secrets.
A. pycodestyle E501 line-too-long warning B. bandit B105 hardcoded_password_string finding C. mccabe C901 complexity score D. pyflakes F401 unused-import warning Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Bandit's B105 plugin performs AST-based detection of hardcoded password/secret string assignments, which Flake surfaces when bandit is installed as a plugin. E501, C901, and F401 are style/complexity/import checks with no security semantics.
A. Replace pickle with a schema-validated format such as JSON plus explicit validation. B. Wrap pickle.loads in a try/except to catch malicious payload errors. C. Restrict pickle to a single worker thread to limit gadget execution. D. Compute a checksum of the payload before calling pickle.loads. Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Pickle can execute arbitrary code on load (CWE-502); switching to a data-only format with schema validation removes the gadget surface. Exception handling, thread restriction, and checksums do not prevent code execution during deserialization.
A. Alphabetical by file path to ensure coverage B. Highest severity and exploitability first, with reachability analysis C. Newest findings first regardless of severity D. Lowest severity first to clear volume quickly Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: SSDF emphasizes risk-based prioritization; severity, exploitability, and reachability determine real risk. Alphabetical, recency, or low-severity-first ordering ignores risk and can delay critical fixes.
A. A unit test of the role-check helper with valid roles B. A negative test submitting another user's resource ID and asserting denial C. A performance test measuring authorization latency D. A snapshot test of the authorization page HTML Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Negative testing with tampered identifiers directly exercises broken access control (OWASP A01) and confirms denial. Unit tests with valid roles, performance tests, and snapshot tests do not attempt bypass and therefore cannot demonstrate enforcement.
A. Line-length violations exist; invalid escape sequences are absent B. Invalid escape sequences exist; line-length violations are absent C. Both line-length and escape-sequence violations are suppressed by config D. Flake8 is misconfigured and reporting only pycodestyle errors Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: E501 is pycodestyle's line-too-long error, while W605 is pycodestyle's invalid-escape-sequence warning. Reporting E without W605 means long lines exist but no invalid escapes were detected. The other options invert the codes or assume suppression without evidence.
A. Replace os.system with subprocess.run(..., shell=False) and argument lists B. Add a try/except around os.system C. Increase logging verbosity around the call D. Rename the function to avoid detection Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Using subprocess with shell=False and a list of arguments prevents shell metacharacter interpretation, eliminating CWE-78. Exception handling, logging, or renaming do not remove the injection vector and may mask the vulnerability.
A. It generates inputs from strategies and shrinks failing cases automatically B. It executes faster because it avoids random input generation C. It replaces the need for assertions by comparing against golden files D. It guarantees full branch coverage through deterministic enumeration Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Hypothesis draws inputs from strategies and minimizes failing examples via shrinking, exposing edge cases fixed examples miss. It is not faster, does not replace assertions, and does not guarantee coverage.
A. Fail the build on any finding regardless of severity B. Baseline existing findings and fail only on newly introduced high-severity issues C. Disable static analysis to avoid blocking releases D. Run analysis only after deployment to production Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: SSDF PW.7 and PW.8 call for reviewing code and configuring tooling to detect vulnerabilities; baselining existing debt while blocking new high-severity issues enforces remediation without halting all work. Failing on any finding is impractical, disabling analysis removes control, and post-deployment scanning is too late.
A. Use parameterized queries with bound parameters. B. Escape single quotes in user input. C. Enable verbose SQL error messages. D. Store queries in external configuration files. Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Parameterized queries separate code from data, eliminating injection regardless of input content (OWASP). Manual escaping is error-prone and bypassable, verbose errors aid attackers, and externalizing queries does not stop injection if concatenation persists.
A. Immediately patch by adding escaping on top of parameterization B. Suppress the finding and record it as a false positive with justification C. Escalate to the CISO as a confirmed critical vulnerability D. Rewrite the query using string concatenation to satisfy the scanner Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Parameterized queries eliminate SQL injection, so a flagged finding on such a path is a false positive that should be documented with justification. Adding escaping or concatenation weakens security; escalation misstates risk.
A. Use the %s lazy formatting with a sanitizing formatter filter B. Concatenate user data into the message before calling logger.info C. Log at DEBUG level so injection attempts are hidden in production D. Disable newline characters globally in the logging configuration Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Lazy %-style formatting plus a filter that strips or escapes CR/LF and control characters neutralizes forged log entries (CWE-117). Concatenation enables injection, hiding at DEBUG loses evidence, and global newline disabling is not supported.
A. Set --exit-zero so the pipeline always passes but logs warnings B. Pin select=E,F,W and ignore all other plugin codes permanently C. Use --max-line-length=120 and --count with a baseline of existing violations D. Run flake8 with --statistics and no exit code enforcement Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: A violation baseline plus strict exit codes blocks new issues while grandfathering legacy debt. --exit-zero and non-enforcing runs let defects through; permanently ignoring plugin codes hides security-relevant checks.
A. Configure compilation with security flags and review code. B. Define security requirements for the software. C. Respond to reported vulnerabilities. D. Protect all forms of code from tampering. Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: SP 800-218's PW (Produce Well-Secured Software) group includes secure coding, code review, and secure build/compiler flags. Defining requirements is PO, responding to vulnerabilities is RV, and protecting code integrity is PS-so only A fits PW.
A. Using an ORM with lazy loading enabled B. Escaping single quotes with backslashes before concatenation C. Strict allowlist validation of input against a fixed pattern D. Applying html.escape() to all user-supplied values Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Allowlist validation constrains input to a known-safe grammar, preventing injection even without parameter binding. Backslash escaping is fragile and DBMS-dependent, ORMs with lazy loading do not guarantee parameterization, and html.escape targets XSS, not SQL injection.
A. V7.1.1 - Verify no sensitive data is logged. B. V7.2.1 - Verify the application logs security-relevant events with sufficient detail. C. V2.1.1 - Verify passwords are at least 12 characters. D. V5.3.4 - Verify output encoding is context-appropriate. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: V7.2.1 requires logging security-relevant events with sufficient user/context detail, directly addressing OWASP A logging/monitoring failures. V7.1.1 addresses data protection, V2.1.1 authentication strength, and V5.3.4 output encoding (XSS), not monitoring.
A. Use pytest.raises with a broad Exception type B. Assert on return value only and ignore exceptions C. Use pytest.raises(SpecificError) and assert no broader catch D. Wrap the test body in try/except and call pytest.skip Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Catching a specific expected exception and asserting no broader catch ensures silent swallowing is detected. Broad Exception hides regressions; ignoring exceptions or skipping masks failures.
A. Log full request payloads at DEBUG to aid incident reconstruction. B. Write logs to append-only storage with structured fields and UTC timestamps. C. Use print() for critical events to avoid logger configuration drift. D. Hash user identifiers before logging to anonymize all events. Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: OWASP recommends structured, timestamped logs on append-only or tamper-evident storage to preserve integrity for forensics. Logging full payloads risks sensitive-data exposure, print() bypasses logging controls, and blanket hashing destroys the correlation needed for investigations.
A. Guarantees no injection flaws exist B. Limits cyclomatic complexity to reduce untested, error-prone code paths C. Enforces PEP 8 line length only D. Replaces Bandit security scanning Answer: B [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: McCabe complexity limits (C901) flag overly complex functions that are hard to test and review, indirectly reducing latent defects; they do not guarantee absence of vulnerabilities or replace security scanners. Line length is a separate E501 check.
A. Sanitize CR/LF characters and use parameterized logging. B. Log raw input with f-strings for full fidelity. C. Disable logging of user-supplied data entirely. D. Rely on the default StreamHandler formatting. Answer: A [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: CWE-117 occurs when attackers inject newline/control characters to forge log entries; sanitizing CR/LF and using parameterized logging (logger.info('%s', val)) prevents injection and format-string issues. f-strings risk format-string injection, disabling logging harms monitoring, and default handlers do not sanitize input.
A. A module-scoped fixture that truncates tables in teardown B. A session-scoped fixture sharing one connection across workers C. A function-scoped fixture using transactional rollback per test D. A class-scoped fixture seeded once per test class Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Function-scoped fixtures with per-test transaction rollback give each test a clean, isolated state even under pytest-xdist parallelism. Broader scopes leak state between tests and cause order-dependent flakiness.
A. function B. class C. module D. session Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: A module-scoped fixture is instantiated once per test module, giving isolation from other modules while sharing within the module; function scope recreates per test (less efficient), class scope ties to class, and session scope shares globally (risking cross-module state leakage).
A. scope="session" B. scope="module" C. scope="function" D. scope="package" Answer: C [Concept: Software Security and Testing (Python security, static analysis, Flake8, logging, testing, remediation)] Rationale: Function-scoped fixtures are torn down after each test, preventing state leakage between tests. Session, module, and package scopes reuse the object across multiple tests, allowing mutations to persist and causing order-dependent failures.