Docsity

WGU D385 ZHN1 TASK 2-SOFTWARE SECURITY AND TESTING | SECURE CODING,API SECURITY IMPLEMENT, Exams of Software Engineering

Toggle sidebar
bg1
WGU D385 ZHN1 TASK 2-SOFTWARE SECURITY AND TESTING | SECURE
CODING,API SECURITY IMPLEMENTATION,PYTHON VULNERABILITY
REMEDATION & PYTEST SOLUTION – QUESTIONS AND ANSWERS | VERIFIED
AND WELL DETAILED ANSWERS | PLUS RATIONALES | DOWNLOAD AND
PASS | LATEST EXAM UPDATE 2026/20227
Core Domains
Secure Coding Principles and Input Validation
API Security and Access Control (OWASP API Top 10)
Python Vulnerability Identification and Remediation
Automated Testing with Pytest
Authentication, Authorization, and Session Management
Cryptography and Data Protection
Logging, Monitoring, and Error Handling
Regulatory Compliance and Professional Ethics
Introduction
This comprehensive assessment evaluates the critical competencies required for
secure software development and testing within modern Python environments.
The examination focuses on the identification and remediation of software
vulnerabilities, the implementation of robust API security controls, and the
validation of fixes through automated testing frameworks like Pytest. Questions
are designed to test both foundational knowledge and applied decision-making
through scenario-based multiple-choice items. Emphasis is placed on real-world
application, ensuring that candidates can translate security theory into
defensible engineering practices. Mastery of these domains demonstrates
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 ZHN1 TASK 2-SOFTWARE SECURITY AND TESTING | SECURE CODING,API SECURITY IMPLEMENT and more Exams Software Engineering in PDF only on Docsity!

WGU D385 ZHN1 TASK 2-SOFTWARE SECURITY AND TESTING | SECURE

CODING,API SECURITY IMPLEMENTATION,PYTHON VULNERABILITY

REMEDATION & PYTEST SOLUTION – QUESTIONS AND ANSWERS | VERIFIED

AND WELL DETAILED ANSWERS | PLUS RATIONALES | DOWNLOAD AND

PASS | LATEST EXAM UPDATE 2026/

Core Domains

Secure Coding Principles and Input Validation API Security and Access Control (OWASP API Top 10) Python Vulnerability Identification and Remediation Automated Testing with Pytest Authentication, Authorization, and Session Management Cryptography and Data Protection Logging, Monitoring, and Error Handling Regulatory Compliance and Professional Ethics

Introduction

This comprehensive assessment evaluates the critical competencies required for secure software development and testing within modern Python environments. The examination focuses on the identification and remediation of software vulnerabilities, the implementation of robust API security controls, and the validation of fixes through automated testing frameworks like Pytest. Questions are designed to test both foundational knowledge and applied decision-making through scenario-based multiple-choice items. Emphasis is placed on real-world application, ensuring that candidates can translate security theory into defensible engineering practices. Mastery of these domains demonstrates

readiness to protect organizational assets, maintain compliance, and uphold professional standards in software security.

SECTION ONE: QUESTIONS 1–

Question 1

A Python developer is reviewing a Flask application and notices the following code snippet: cursor.execute("SELECT * FROM users WHERE username = '%s'" % username). Which vulnerability is most directly introduced by this practice?

A. Cross-Site Scripting (XSS) B. SQL Injection C. Insecure Deserialization D. Server-Side Request Forgery (SSRF)

🟢 Correct Answer: B. SQL Injection

🔴 Explanation: Directly formatting user input into SQL queries allows an attacker to manipulate the query structure, leading to unauthorized data access or modification. Parameterized queries are the required remediation.

Question 2

When configuring Cross-Origin Resource Sharing (CORS) in a production API, which of the following settings represents a significant security risk?

A. Access-Control-Allow-Origin: https://app.example.com B. Access-Control-Allow-Credentials: true with a wildcard origin C. Access-Control-Allow-Methods: GET, POST D. Access-Control-Max-Age: 600

🟢 Correct Answer: B. Server-Side Request Forgery (SSRF)

🔴 Explanation: Without validating the destination URL, an attacker can force the server to make requests to internal resources, such as metadata services or internal admin panels.

Question 5

Which of the following is the most appropriate way to store user passwords in a Python application?

A. Base64 encoding B. SHA-256 hashing without a salt C. Argon2 or bcrypt with a unique salt per user D. AES encryption with a hardcoded key

🟢 Correct Answer: C. Argon2 or bcrypt with a unique salt per user

🔴 Explanation: Password hashing requires slow, memory-hard algorithms with unique salts to resist rainbow table and brute-force attacks. Encoding and plain hashing are insufficient.

Question 6

A developer runs pytest and sees assert 4 == 5. What does this output indicate?

A. The test passed because the assertion was skipped B. The test failed because the function returned an unexpected value C. The test encountered a syntax error D. The test was not collected by Pytest

🟢 Correct Answer: B. The test failed because the function returned an unexpected value

🔴 Explanation: Pytest's assertion introspection shows the actual value (4) versus the expected value (5), indicating a failed test due to a logic error.

Question 7

According to the principle of least privilege, an API service account should be granted:

A. Full administrative rights to simplify troubleshooting B. Only the permissions necessary to perform its specific function C. Permissions based on the developer's convenience D. Read-only access to all databases regardless of function

🟢 Correct Answer: B. Only the permissions necessary to perform its specific function

🔴 Explanation: Least privilege limits the blast radius of a compromise by ensuring accounts have only the minimum access required for their tasks.

Question 8

Which HTTP status code should an API return when an authenticated user attempts to access a resource they do not own, and the server correctly enforces object-level authorization?

A. 200 OK B. 401 Unauthorized C. 403 Forbidden D. 404 Not Found

🟢 Correct Answer: C. 403 Forbidden

🔴 Explanation: A 403 indicates the server understood the request but refuses to authorize it. A 401 is for missing authentication, while 404 is often used to

/users/123 to /users/.

Question 11

Which Pytest feature allows a developer to run a specific test function without running the entire test suite?

A. pytest --all B. pytest -k test_function_name C. pytest --exclude D. pytest --skip

🟢 Correct Answer: B. pytest -k test_function_name

🔴 Explanation: The -k flag filters tests by name substring, allowing targeted execution of specific test functions.

Question 12

A code review reveals that an application logs the following: logger.info(f"User login attempt: {username} with password: {password}")

. What is the primary security issue?

A. The log message is not formatted correctly B. Sensitive credentials are being written to logs C. The logger is using f-strings which are slow D. The log level should be DEBUG instead of INFO

🟢 Correct Answer: B. Sensitive credentials are being written to logs

🔴 Explanation: Logging passwords or secrets violates security best practices and compliance requirements, as logs are often accessible to operations staff or attackers.

Question 13

Which of the following is a secure way to handle database credentials in a Python application?

A. Hardcode them in the source file for simplicity B. Store them in a .env file committed to the repository C. Load them from environment variables or a secrets manager D. Include them in a public configuration file

🟢 Correct Answer: C. Load them from environment variables or a secrets manager

🔴 Explanation: Environment variables or dedicated secrets managers keep credentials out of source code and version control, reducing exposure risk.

Question 14

A developer is writing a Pytest test to verify that a function raises a ValueError when given invalid input. Which approach is correct?

A. assert function_raises_value_error() B. with pytest.raises(ValueError): function(invalid_input) C. try: function(invalid_input) except: pass D. assert ValueError in function(invalid_input)

🟢 Correct Answer: B. with pytest.raises(ValueError): function(invalid_input)

🔴 Explanation: Pytest's raises context manager asserts that the specified exception is raised within the block.

Question 15

A. Pytest B. Bandit C. Flask D. Requests

🟢 Correct Answer: B. Bandit

🔴 Explanation: Bandit is a static application security testing (SAST) tool that scans Python code for common security issues like hardcoded passwords and insecure function usage.

Question 18

In a Pytest test, what is the purpose of a fixture?

A. To permanently modify the application code B. To provide a fixed baseline for tests, such as test data or a configured client C. To replace the need for assertions D. To automatically generate test reports

🟢 Correct Answer: B. To provide a fixed baseline for tests, such as test data or a configured client

🔴 Explanation: Fixtures provide reusable setup and teardown logic, ensuring tests run against consistent, isolated state.

Question 19

Which of the following represents a failure to enforce function-level authorization in an API?

A. A user can view their own profile B. A regular user can call an administrative endpoint to delete other users

C. An unauthenticated user receives a 401 response D. A user receives a 403 when accessing another user's data

🟢 Correct Answer: B. A regular user can call an administrative endpoint to delete other users

🔴 Explanation: Function-level authorization ensures that users cannot access functions outside their role. Allowing a regular user to execute admin actions is a critical flaw.

Question 20

What is the correct way to compare a user-supplied password against a stored hash using bcrypt in Python?

A. if password == stored_hash: B. if bcrypt.checkpw(password.encode(), stored_hash): C. if hashlib.sha256(password) == stored_hash: D. if stored_hash in password:

🟢 Correct Answer: B. if bcrypt.checkpw(password.encode(), stored_hash):

🔴 Explanation: bcrypt.checkpw securely compares a plaintext password against a stored hash, using constant-time comparison to prevent timing attacks.

Question 21

A developer notices that pytest is not discovering tests in a file named mytests.py. What is the most likely reason?

A. The file is in the wrong directory B. The file name does not match the test_*.py pattern

🔴 Explanation: The OWASP API Security Top 10 is a standardized awareness document for developers and security professionals, highlighting risks like BOLA, broken authentication, and excessive data exposure.

Question 24

A Pytest test contains the line assert response.status_code == 403. What is this test verifying?

A. That the API returns a server error B. That the API correctly denies unauthorized access C. That the API successfully processed the request D. That the API endpoint exists

🟢 Correct Answer: B. That the API correctly denies unauthorized access

🔴 Explanation: A 403 status code indicates that the server understood the request but refused to authorize it, which is the expected behavior for an access control test.

Question 25

Which of the following is a secure practice for handling exceptions in Python?

A. Using a bare except: clause to catch all errors B. Logging the exception details and returning a generic error message to the user C. Displaying the full traceback to the user for debugging D. Ignoring all exceptions to prevent crashes

🟢 Correct Answer: B. Logging the exception details and returning a generic error message to the user

🔴 Explanation: Detailed exceptions should be logged internally for debugging, while users should receive generic messages to avoid leaking implementation details.

Question 26

An API returns a list of users with fields including id , name , email , password_hash , and ssn. The client only needs id and name. What security principle is violated?

A. Least functionality B. Excessive Data Exposure C. Broken Authentication D. Security Misconfiguration

🟢 Correct Answer: B. Excessive Data Exposure

🔴 Explanation: APIs should only return the data explicitly required by the client. Exposing sensitive fields like password hashes and SSNs increases the impact of a data breach.

Question 27

In Pytest, what is the purpose of the conftest.py file?

A. To configure the Python interpreter B. To define shared fixtures and hooks that are available across multiple test files C. To store production database credentials D. To replace pytest.ini

🟢 Correct Answer: B. To define shared fixtures and hooks that are available across multiple test files

Question 30

A developer is testing an API endpoint that requires a valid JWT. The test receives a 401 response. What does this indicate?

A. The request was successful B. The authentication credentials are missing or invalid C. The user is authenticated but lacks permission D. The server encountered an internal error

🟢 Correct Answer: B. The authentication credentials are missing or invalid

🔴 Explanation: A 401 Unauthorized response indicates that the request lacks valid authentication credentials for the target resource.

Question 31

Which Python module should be avoided for parsing XML data from untrusted sources due to vulnerability to XML External Entity (XXE) attacks?

A. defusedxml B. xml.etree.ElementTree with default settings C. json D. csv

🟢 Correct Answer: B. xml.etree.ElementTree with default settings

🔴 Explanation: Standard XML parsers may resolve external entities, leading to XXE attacks. Libraries like defusedxml are designed to mitigate this risk.

Question 32

In the context of security testing, what is the difference between SAST and DAST?

A. SAST analyzes running code; DAST analyzes source code B. SAST analyzes source code; DAST analyzes running applications C. SAST is for Python only; DAST is for Java only D. SAST is manual; DAST is automated

🟢 Correct Answer: B. SAST analyzes source code; DAST analyzes running applications

🔴 Explanation: Static Application Security Testing (SAST) examines source code without executing it. Dynamic Application Security Testing (DAST) tests the running application from the outside.

Question 33

A Pytest test is written to verify that a login function returns a session token upon valid credentials. Which assertion is most appropriate?

A. assert login(user, pass) is None B. assert login(user, pass).startswith("token_") C. assert login(user, pass) == "password" D. assert login(user, pass) != True

🟢 Correct Answer: B. assert login(user, pass).startswith("token_")

🔴 Explanation: Verifying that the returned token conforms to an expected format (e.g., prefix) is a reasonable behavioral assertion for a login function.

Question 34

Which of the following is an example of a security misconfiguration in a Python web application?

A. Using environment variables for secrets B. Leaving default administrative credentials unchanged

🟢 Correct Answer: B. Object-level authorization check

🔴 Explanation: The API must verify that the authenticated user owns or is authorized to access the requested invoice ID before returning data.

Question 37

Which of the following is a secure method for generating random tokens for password reset in Python?

A. random.random() B. secrets.token_urlsafe() C. time.time() D. hashlib.md5(str(user_id))

🟢 Correct Answer: B. secrets.token_urlsafe()

🔴 Explanation: The secrets module generates cryptographically secure random numbers suitable for managing tokens and secrets, unlike the random module.

Question 38

In Pytest, how can a developer verify that a function does not raise an exception?

A. By using pytest.raises with no arguments B. By simply calling the function; if it raises, the test fails C. By using assert not function() D. By using pytest.fail()

🟢 Correct Answer: B. By simply calling the function; if it raises, the test fails

🔴 Explanation: If a function raises an unexpected exception during a test, Pytest will report the test as failed. No special assertion is needed to verify the absence of an exception.

Question 39

What is the primary risk of using eval() on user-supplied input in Python?

A. The input may contain syntax errors B. The input may be executed as arbitrary Python code C. The input may be too large D. The input may be a string instead of a number

🟢 Correct Answer: B. The input may be executed as arbitrary Python code

🔴 Explanation: eval() interprets its argument as a Python expression, allowing an attacker to execute commands or access sensitive data.

Question 40

Which of the following HTTP headers helps mitigate Cross-Site Scripting (XSS) by restricting the sources from which scripts can be loaded?

A. Content-Type B. Content-Security-Policy C. Authorization D. Accept

🟢 Correct Answer: B. Content-Security-Policy

🔴 Explanation: CSP allows developers to whitelist trusted sources for scripts and other resources, significantly reducing the impact of XSS vulnerabilities.

Question 41