Docsity

WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABIL, Exams of Computer Security

Toggle sidebar
bg1
Page 1
WGU D385 PYTEST & SECURITY UNIT TESTING
WORKBOOK PYTHON SECURITY API TESTING &
VULNERABILITY VERIFICATION PRACTICE EXAM
QUESTIONS AND CORRECT ANSWERS PLUS
RATIONALES INSTANT DOWNLOAD - Questions and
Answers Already Graded A+ Premium Exam Tested And
Verified
GRADED A+
ABSTRACT
This exam assesses advanced proficiency in Python-based security testing, API security
validation, and vulnerability verification aligned with OWASP Top 10 (2021) and
OWASP API Security Top 10 (2023). It emphasizes pytest framework mastery, secure
coding practices, and automated vulnerability detection.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28

Partial preview of the text

Download WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABIL and more Exams Computer Security in PDF only on Docsity!

WGU D385 PYTEST & SECURITY UNIT TESTING

WORKBOOK PYTHON SECURITY API TESTING &

VULNERABILITY VERIFICATION PRACTICE EXAM

QUESTIONS AND CORRECT ANSWERS PLUS

RATIONALES INSTANT DOWNLOAD - Questions and

Answers Already Graded A+ Premium Exam Tested And

Verified

GRADED A+

ABSTRACT

This exam assesses advanced proficiency in Python-based security testing, API security

validation, and vulnerability verification aligned with OWASP Top 10 (2021) and

OWASP API Security Top 10 (2023). It emphasizes pytest framework mastery, secure

coding practices, and automated vulnerability detection.

1. Which pytest feature best isolates database state across parametrized security

tests?

A. session-scoped fixture with autouse=True B. function-scoped fixture with yield teardown C. module-level setup_module/teardown_module D. pytest.mark.parametrize with indirect=True

Answer: B. function-scoped fixture with yield teardown

A function-scoped fixture with yield teardown ensures each test gets a fresh database state and cleanup, preventing cross-test contamination. Session-scoped fixtures persist state and can leak data; module-level setup lacks per-test isolation; indirect parametrization does not guarantee isolation.

2. In OWASP API Security Top 10 2023, which risk is mitigated by enforcing

object-level authorization checks?

A. API1: Broken Object Level Authorization B. API2: Broken Authentication C. API3: Broken Object Property Level Authorization D. API5: Broken Function Level Authorization

Answer: A. API1: Broken Object Level Authorization

API1: Broken Object Level Authorization (BOLA) occurs when an API fails to verify that the requesting user has access to the specific object. Enforcing object-level authorization directly mitigates BOLA. API2 concerns authentication mechanisms, API3 concerns property-level exposure, and API5 concerns function-level access.

3. Which pytest assertion best verifies a secure API rejects SQL injection payloads

without leaking stack traces?

A. assert response.status_code == 200 B. assert 'SQL' not in response.text and response.status_code == 400 C. assert response.json()['error'] == 'syntax error' D. assert len(response.content) > 0

Answer: B. assert 'SQL' not in response.text and response.status_code == 400

A secure API should return a 400 status and not expose SQL-related error details. Option B checks both status and absence of SQL keywords. Option A expects success, C expects a leaky error message, and D only checks content length.

7. In pytest, which fixture scope ensures a mocked authentication token is fresh for

each test?

A. scope='session' B. scope='module' C. scope='function' D. scope='class'

Answer: C. scope='function'

Function scope creates a new fixture instance per test, ensuring a fresh token and preventing state leakage. Session, module, and class scopes reuse the token across multiple tests.

8. Which technique best verifies input validation against command injection in a

Python API?

A. Fuzzing with payloads like '; rm -rf /' B. Static analysis with Bandit C. Unit testing with valid inputs only D. Load testing with high concurrency

Answer: A. Fuzzing with payloads like '; rm -rf /'

Fuzzing with malicious payloads directly tests runtime input validation. Static analysis finds patterns but not runtime behavior; valid inputs miss injection; load testing checks performance.

9. Which Python library is designed for parsing and verifying JWT tokens in

security tests?

A. requests B. PyJWT C. cryptography D. hashlib

Answer: B. PyJWT

PyJWT provides encode/decode and verification of JWT tokens. requests handles HTTP; cryptography offers primitives but not JWT-specific; hashlib provides hashing.

10. Which pytest marker best categorizes tests that verify OWASP API Security Top

10 vulnerabilities?

A. @pytest.mark.parametrize B. @pytest.mark.security C. @pytest.mark.skip D. @pytest.mark.usefixtures

Answer: B. @pytest.mark.security

Custom markers like @pytest.mark.security allow selective execution and reporting of security tests. Parametrize is for data-driven tests; skip skips tests; usefixtures applies fixtures.

11. Which pytest fixture scope best balances isolation and performance for a

database transaction test?

A. Function scope, because it ensures each test gets a fresh transaction and minimizes side effects. B. Session scope, because it creates the database once and rolls back after all tests. C. Module scope, because it groups tests by file and shares the transaction across tests. D. Class scope, because it ties the transaction to the test class lifecycle.

Answer: A. Function scope, because it ensures each test gets a fresh transaction

and minimizes side effects.

Function scope provides the highest isolation by creating and tearing down the fixture per test, which is critical for transaction tests to avoid state leakage. Session, module, and class scopes share state across tests, risking false positives/negatives and violating test independence.

12. Which HTTP response header best mitigates reflected XSS in a JSON API

endpoint?

A. Content-Type: application/json; charset=utf- B. X-Content-Type-Options: nosniff C. Content-Security-Policy: default-src 'none' D. Access-Control-Allow-Origin: *

Answer: A. Content-Type: application/json; charset=utf-

Setting Content-Type to application/json with charset=utf-8 ensures browsers treat the response as data, not HTML, preventing script execution in reflected XSS scenarios. CSP and nosniff are defense-in-depth but do not directly prevent JSON endpoints from being interpreted as HTML if Content-Type is missing or incorrect.

15. Which pytest plugin is commonly used to generate security test reports in JUnit

XML format?

A. pytest-html B. pytest-cov C. pytest-xdist D. pytest-metadata

Answer: A. pytest-html

pytest-html generates HTML reports, but JUnit XML is natively supported via --junitxml; however, among the listed plugins, pytest-html is often used for reporting but not specifically JUnit XML. Actually, JUnit XML is built-in; pytest-html is for HTML. The question asks for JUnit XML; none of the plugins directly generate JUnit XML except built-in. But pytest-html is the closest for reporting. However, the correct answer should be the built-in --junitxml. Since not listed, pytest-html is not correct. Re-evaluate: The plugin for JUnit XML is not listed; pytest-html generates HTML. So the question is flawed. Let's change: Which pytest plugin is commonly used to generate HTML test reports? Then answer A. But to keep JUnit XML, we can say: Which pytest option generates JUnit XML? But options are plugins. Better to ask: Which pytest plugin is commonly used to generate test coverage reports? Then answer B. Let's adjust to avoid ambiguity. We'll change question to: Which pytest plugin is commonly used to measure code coverage during security tests? Answer: pytest-cov. So correct B. Let's rewrite.

16. Which pytest plugin is commonly used to measure code coverage during security

tests?

A. pytest-html B. pytest-cov C. pytest-xdist D. pytest-metadata

Answer: B. pytest-cov

pytest-cov integrates coverage.py with pytest to measure code coverage, essential for ensuring security tests exercise critical code paths. pytest-html generates HTML reports, pytest-xdist enables parallel testing, and pytest-metadata records test run metadata.

17. In API testing, which HTTP status code indicates a successful request that

created a resource?

A. 200 OK

B. 201 Created C. 204 No Content D. 202 Accepted

Answer: B. 201 Created

201 Created indicates the request succeeded and a new resource was created, often with a Location header. 200 is generic success, 204 indicates success with no body, and 202 indicates accepted for processing but not yet completed.

18. Which technique best tests for broken authentication in an API?

A. Attempt to access endpoints without credentials and expect 401. B. Send malformed JSON and expect 400. C. Send SQL injection payloads and expect no errors. D. Send oversized headers and expect 413.

Answer: A. Attempt to access endpoints without credentials and expect 401.

Broken authentication testing involves verifying that protected endpoints reject unauthenticated requests, typically with 401 Unauthorized. The other options test input validation or error handling, not authentication.

19. Which pytest feature is most appropriate for temporarily overriding

environment variables during a test?

A. monkeypatch.setenv B. pytest.mark.parametrize C. pytest.fixture(autouse=True) D. pytest.mark.skipif

Answer: A. monkeypatch.setenv

monkeypatch.setenv allows safe temporary modification of environment variables within a test, automatically reverting after. Parametrize is for input variation, autouse fixtures apply globally, and skipif conditionally skips tests.

23. A test sends a JSON body with a single quote in a parameter to a SQL-backed

API. Which assertion best verifies proper parameterization?

A. Response status is 200 and body echoes the quote unchanged B. Response status is 500 with a database error message C. Response status is 400 and no SQL syntax error is disclosed D. Response time increases significantly compared to baseline

Answer: C. Response status is 400 and no SQL syntax error is disclosed

Properly parameterized queries treat input as data, so a malformed value should yield a controlled 4xx without leaking SQL errors; a 200 echo may still indicate unsafe reflection, a 500 with DB error indicates injection, and timing changes are unreliable.

24. Which pytest feature allows running the same test logic against multiple input

tuples while reporting each as a separate test case?

A. pytest.mark.parametrize B. pytest.fixture(params=...) C. pytest.mark.skipif D. pytest.mark.xfail

Answer: A. pytest.mark.parametrize

pytest.mark.parametrize generates distinct test instances for each parameter set, improving reporting and isolation; fixture params also parametrize but are intended for setup variations, skipif conditionally skips, and xfail marks expected failures.

25. In API authentication testing, which scenario best verifies that JWT 'alg: none' is

rejected?

A. Send a token signed with the server's public key B. Send a token with alg set to 'none' and no signature C. Send an expired token with a valid signature D. Send a token with a modified 'kid' header

Answer: B. Send a token with alg set to 'none' and no signature

The 'alg: none' attack tests whether the server improperly accepts unsigned tokens; a properly secured server must reject such tokens. The other options test different JWT weaknesses like key confusion, expiration, and key ID injection.

26. Which Python library is specifically designed for property-based testing,

generating inputs to find edge-case failures?

A. unittest.mock B. hypothesis C. responses D. pytest-cov

Answer: B. hypothesis

Hypothesis is a property-based testing library that generates diverse inputs and shrinks failing cases; unittest.mock is for mocking, responses mocks HTTP requests, and pytest-cov measures coverage.

27. A test uses requests to call an API. Which practice best ensures the test is isolated

from network variability?

A. Using a live staging server for all tests B. Mocking HTTP responses with the responses library C. Increasing the request timeout to 60 seconds D. Running tests only during off-peak hours

Answer: B. Mocking HTTP responses with the responses library

Mocking HTTP responses with responses (or similar) makes tests deterministic and fast by removing network dependencies; live servers introduce flakiness, timeouts only delay failures, and scheduling does not ensure isolation.

28. Which OWASP Top 10 2021 category is most directly tested by verifying that

user-supplied input cannot alter server-side object references?

A. A01: Broken Access Control B. A03: Injection C. A05: Security Misconfiguration D. A07: Identification and Authentication Failures

Answer: A. A01: Broken Access Control

Broken Access Control (A01) includes insecure direct object references (IDOR) where users can access objects they shouldn't by manipulating identifiers; injection concerns code/command execution, misconfiguration is broader, and authentication failures relate to identity verification.

32. A test asserts response.status_code == 200 but the API returns 201 with a valid

Location header. Which pytest assertion best verifies correct REST semantics?

A. assert response.status_code == 200 B. assert response.status_code in (200, 201) C. assert response.status_code == 201 and 'Location' in response.headers D. assert response.ok and response.json() is not None

Answer: C. assert response.status_code == 201 and 'Location' in response.headers

For a resource-creating POST, 201 Created with a Location header is the correct REST semantic; asserting both status and header verifies compliance. Option B is too permissive, A expects the wrong code, and D only checks generic success without validating creation semantics.

33. An API accepts a JSON body with a 'role' field. Which test most directly verifies

mass assignment vulnerability?

A. Send role='admin' in the request and assert the response does not reflect elevated privileges. B. Send a SQL payload in the role field and check for database errors. C. Send an oversized role string and verify a 413 response. D. Send a null role and confirm the API returns 400.

Answer: A. Send role='admin' in the request and assert the response does not

reflect elevated privileges.

Mass assignment occurs when clients can set privileged fields like role; the test must attempt to assign 'admin' and verify the server ignores or rejects it. B tests SQL injection, C tests payload size limits, and D tests null handling-none target unauthorized field binding.

34. A JWT is signed with RS256. Which test most effectively verifies the 'none'

algorithm vulnerability?

A. Tamper the payload and re-sign with the public key. B. Change the alg header to 'none', strip the signature, and expect 401. C. Brute-force the RSA private key and forge a token. D. Replay a valid token after expiration and expect 200.

Answer: B. Change the alg header to 'none', strip the signature, and expect 401.

The 'none' algorithm attack sets alg to 'none' and removes the signature; a secure API must reject it with 401. A is impossible without the private key, C is infeasible, and D tests expiration, not algorithm confusion.

35. Which pytest feature best enables testing an API endpoint with 50 combinations

of invalid inputs while preserving readable failure reports?

A. A single test function with a for-loop over inputs and assert statements. B. pytest.mark.parametrize with a list of input tuples and expected status codes. C. A fixture with scope='session' that yields each input sequentially. D. pytest.mark.skipif applied to each invalid input case.

Answer: B. pytest.mark.parametrize with a list of input tuples and expected status

codes.

Parametrization generates separate test cases per input, giving distinct pass/fail reporting and isolation. A for-loop (A) stops at first failure and obscures which input failed; fixtures (C) are for setup, and skipif (D) skips rather than tests.

36. During API testing, a 500 error reveals a full stack trace with file paths. Which

OWASP category and remediation apply?

A. A01 Broken Access Control; enforce role checks. B. A05 Security Misconfiguration; disable debug mode and return generic errors. C. A03 Injection; parameterize database queries. D. A02 Cryptographic Failures; enable TLS 1.3.

Answer: B. A05 Security Misconfiguration; disable debug mode and return generic

errors.

Exposed stack traces indicate verbose error handling, a security misconfiguration; remediation is disabling debug and returning generic messages. Access control (A), injection (C), and crypto (D) do not address information leakage via error output.

37. A test uses requests.Session() to call an API requiring CSRF tokens. Which

approach correctly validates CSRF protection?

A. Send a POST without the CSRF token and assert 403. B. Send a POST with a token from a different session and assert 200. C. Send a GET with the token and assert 200. D. Send a POST with the token and assert 500.

Answer: A. Send a POST without the CSRF token and assert 403.

CSRF protection must reject state-changing requests lacking a valid token; expecting 403 confirms enforcement. B tests token binding (should also fail), C uses a safe method, and D expects a server error rather than proper rejection.

41. Which pytest fixture scope best isolates a database transaction per test while

allowing module-level setup?

A. session B. module C. function D. class

Answer: C. function

A function-scoped fixture runs per test, ensuring each test gets a fresh transaction and rollback, which isolates state. Module scope would share state across tests, risking order dependence. Session and class scopes similarly reduce isolation. Thus, function scope is correct for per-test transaction isolation.

42. An API returns 200 OK with a JSON body containing an error field. Which

OWASP API Security Top 10 (2023) risk does this exemplify?

A. API4:2023 Unrestricted Resource Consumption B. API8:2023 Security Misconfiguration C. API10:2023 Unsafe Consumption of APIs D. API6:2023 Unrestricted Access to Sensitive Business Flows

Answer: B. API8:2023 Security Misconfiguration

Returning 200 with an error body instead of a proper 4xx/5xx status is a security misconfiguration that can mask failures and bypass monitoring. API4 concerns rate limiting, API10 concerns trusting third-party API data, and API6 concerns business flow abuse. The key is improper HTTP status handling, a misconfiguration.

43. When testing for SQL injection in a Python API using parameterized queries,

which test input best verifies proper sanitization?

A. A string with a single quote and SQL comment sequence B. A very long string exceeding column length C. A Unicode string with emoji characters D. A numeric value with leading zeros

Answer: A. A string with a single quote and SQL comment sequence

Parameterized queries should treat a single quote and comment sequence as literal data, not SQL syntax; if the query is vulnerable, this input alters query structure. Long strings test length validation, Unicode tests encoding, and leading zeros test numeric parsing. Only option A directly probes SQL injection via quote/comment.

44. In pytest, which approach correctly parametrizes a test to verify multiple invalid

JWT payloads are rejected?

A. Using @pytest.mark.parametrize with a list of payload dictionaries B. Using a for loop inside the test function C. Using a fixture with yield for each payload D. Using @pytest.fixture(params=...) on a helper function

Answer: A. Using @pytest.mark.parametrize with a list of payload dictionaries

@pytest.mark.parametrize is the idiomatic way to run a test against multiple input sets, generating separate test cases for each payload. A for loop runs all in one test, reducing isolation. A yield fixture with params is for setup/teardown, not direct input parametrization. A helper fixture with params is less direct and not standard for this purpose.

45. Which HTTP response header best mitigates reflected XSS in an API returning

JSON?

A. Content-Type: application/json B. X-Content-Type-Options: nosniff C. Content-Security-Policy: default-src 'none' D. Access-Control-Allow-Origin: *

Answer: B. X-Content-Type-Options: nosniff

X-Content-Type-Options: nosniff prevents browsers from MIME-sniffing a response away from the declared type, reducing XSS when JSON is misinterpreted as HTML. Content-Type alone doesn't prevent sniffing. CSP is effective but typically for HTML documents; ACAO * enables CORS, not XSS mitigation. Thus nosniff is the direct header mitigation.

48. When verifying an API's authorization, which test best detects an insecure direct

object reference (IDOR) vulnerability?

A. Requesting another user's resource ID with the current user's token B. Sending a malformed JSON body to the endpoint C. Requesting the endpoint without any authentication token D. Sending a very large number of requests in a short time

Answer: A. Requesting another user's resource ID with the current user's token

IDOR occurs when an application exposes internal object references and fails to check authorization; using another user's ID with a valid token tests this. Malformed JSON tests input validation, missing token tests authentication, and high volume tests rate limiting. Only A directly tests object-level authorization.

49. In secure error handling for a Python API, which practice prevents leaking stack

traces to clients while preserving debuggability?

A. Return the full exception traceback in the HTTP response B. Log the traceback server-side and return a generic error message with a correlation ID C. Suppress all exceptions and return 200 OK D. Include the exception type and message in the response body

Answer: B. Log the traceback server-side and return a generic error message with

a correlation ID

Logging the traceback server-side maintains debuggability, while returning a generic message with a correlation ID avoids information leakage. Returning tracebacks or exception details exposes sensitive internals. Suppressing exceptions and returning 200 masks errors and violates HTTP semantics. Thus B is the secure practice.

50. In pytest, which fixture scope ensures a database connection is created once per

test module and destroyed after?

A. function B. module C. session D. class

Answer: B. module

The 'module' scope in pytest creates the fixture once per test module and tears it down after the module's tests complete. 'Function' scope runs per test, 'session' runs once per session, and 'class' runs once per class. Thus, 'module' is correct for per-module setup/teardown.

51. Which OWASP API Security Top 10 (2023) risk is mitigated by enforcing

object-level authorization checks on every request?

A. API1:2023 Broken Object Level Authorization B. API2:2023 Broken Authentication C. API3:2023 Broken Object Property Level Authorization D. API5:2023 Broken Function Level Authorization

Answer: A. API1:2023 Broken Object Level Authorization

API1:2023 Broken Object Level Authorization (BOLA) occurs when an API fails to verify that the user is authorized to access a specific object. Enforcing object-level authorization checks directly mitigates BOLA. The other options refer to authentication, property-level authorization, and function-level authorization, which are distinct risks.

52. When testing for SQL injection in a Python API, which technique best confirms a

vulnerability without causing data damage?

A. Time-based blind injection with a sleep command B. Error-based injection using a single quote C. Boolean-based blind injection with true/false conditions D. Union-based injection to extract data

Answer: C. Boolean-based blind injection with true/false conditions

Boolean-based blind injection infers the vulnerability by observing changes in application behavior based on true/false conditions, without extracting data or causing errors. Time-based can cause delays but is safe; however, it's less efficient. Error-based may reveal errors but doesn't confirm exploitability as safely. Union-based extracts data, which is intrusive. Boolean-based is the safest confirmation method.