
































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. 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
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.
A. API1: Broken Object Level Authorization B. API2: Broken Authentication C. API3: Broken Object Property Level Authorization D. API5: Broken Function 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.
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
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.
A. scope='session' B. scope='module' C. scope='function' D. scope='class'
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.
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
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.
A. requests B. PyJWT C. cryptography D. hashlib
PyJWT provides encode/decode and verification of JWT tokens. requests handles HTTP; cryptography offers primitives but not JWT-specific; hashlib provides hashing.
A. @pytest.mark.parametrize B. @pytest.mark.security C. @pytest.mark.skip D. @pytest.mark.usefixtures
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.
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.
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.
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: *
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.
A. pytest-html B. pytest-cov C. pytest-xdist D. pytest-metadata
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.
A. pytest-html B. pytest-cov C. pytest-xdist D. pytest-metadata
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.
B. 201 Created C. 204 No Content D. 202 Accepted
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.
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.
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.
A. monkeypatch.setenv B. pytest.mark.parametrize C. pytest.fixture(autouse=True) D. pytest.mark.skipif
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.
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
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.
A. pytest.mark.parametrize B. pytest.fixture(params=...) C. pytest.mark.skipif D. pytest.mark.xfail
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.
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
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.
A. unittest.mock B. hypothesis C. responses D. pytest-cov
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.
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
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.
A. A01: Broken Access Control B. A03: Injection C. A05: Security Misconfiguration D. A07: Identification and Authentication Failures
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
A. session B. module C. function D. class
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.
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
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.
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
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.
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
@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.
A. Content-Type: application/json B. X-Content-Type-Options: nosniff C. Content-Security-Policy: default-src 'none' D. Access-Control-Allow-Origin: *
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.
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
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.
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
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.
A. function B. module C. session D. class
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.
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
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.
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
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.