Docsity

WGU D385 ZHN1 Task 2 – Software Security and Testing | Secure Coding, API Security Implem, Exams of Computer Science

Toggle sidebar
bg1
Page 1 of 76
WGU D385 ZHN1 Task 2 – Software Security and Testing | Secure
Coding, API Security Implementation, Python Vulnerability
Remediation & Pytest Solutions | 2027 Updated
This study resource supports students preparing for WGU D385 ZHN1 Task 2 across secure Python
coding, API security controls, input validation, and automated testing with pytest. Each multiple-
choice item presents practical engineering scenarios covering vulnerability remediation,
authentication, exception handling, logging hygiene, and test coverage. Correct answers appear in
blue bold italic text paired with concise bold red rationales to reinforce defensive programming and
assessment readiness.
Question 1
A Python application accepts user input and uses that input directly in a database query. Which
security vulnerability is most likely to occur if an attacker submits malicious SQL statements?
A. Cross-site scripting
B. SQL injection
C. Denial of service
D. Buffer overflow
**Correct Answer: B. SQL injection
Rationale: SQL injection occurs when an application incorporates untrusted user input into database
queries without proper parameterization. Attackers may manipulate queries to access, modify, or
delete unauthorized database information. Parameterized queries are an effective prevention
technique.
Question 2
Which secure coding practice is most effective for preventing SQL injection in Python applications
that communicate with relational databases?
A. Increasing database connection timeouts
B. Hiding database error messages
C. Using parameterized SQL queries
D. Disabling application logging
**Correct Answer: C. Using parameterized SQL queries
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 Implem and more Exams Computer Science in PDF only on Docsity!

WGU D385 ZHN1 Task 2 – Software Security and Testing | Secure

Coding, API Security Implementation, Python Vulnerability

Remediation & Pytest Solutions | 2027 Updated

This study resource supports students preparing for WGU D385 ZHN1 Task 2 across secure Python coding, API security controls, input validation, and automated testing with pytest. Each multiple- choice item presents practical engineering scenarios covering vulnerability remediation, authentication, exception handling, logging hygiene, and test coverage. Correct answers appear in blue bold italic text paired with concise bold red rationales to reinforce defensive programming and assessment readiness. Question 1 A Python application accepts user input and uses that input directly in a database query. Which security vulnerability is most likely to occur if an attacker submits malicious SQL statements? A. Cross-site scripting B. SQL injection C. Denial of service D. Buffer overflow **Correct Answer: B. SQL injection Rationale: SQL injection occurs when an application incorporates untrusted user input into database queries without proper parameterization. Attackers may manipulate queries to access, modify, or delete unauthorized database information. Parameterized queries are an effective prevention technique. Question 2 Which secure coding practice is most effective for preventing SQL injection in Python applications that communicate with relational databases? A. Increasing database connection timeouts B. Hiding database error messages C. Using parameterized SQL queries D. Disabling application logging **Correct Answer: C. Using parameterized SQL queries

Rationale: Parameterized queries separate SQL instructions from user-supplied data. This prevents malicious input from being interpreted as executable SQL commands and significantly reduces SQL injection risks. Question 3 A developer discovers that an application stores database usernames and passwords directly inside its Python source code. What is the most appropriate remediation? A. Store credentials in environment variables or a secure secrets manager B. Rename the Python source file C. Convert the credentials into comments D. Store credentials in a publicly accessible configuration file **Correct Answer: A. Store credentials in environment variables or a secure secrets manager Rationale: Hardcoded credentials can be exposed through source-code repositories, application packages, and backups. Environment variables or dedicated secrets-management systems provide safer credential handling and make credential rotation easier. Question 4 Which principle requires an application to provide users and processes with only the permissions necessary to perform their assigned responsibilities? A. Open access B. Complete mediation C. Security through obscurity D. Principle of least privilege **Correct Answer: D. Principle of least privilege Rationale: The principle of least privilege limits permissions to the minimum required for a specific task. This reduces the potential damage caused by compromised accounts, malicious users, and application vulnerabilities. Question 5 A developer wants to identify common security weaknesses in a Python codebase before deploying the application. Which tool is specifically designed to perform automated Python security analysis? A. Pytest B. Bandit C. Matplotlib D. Jupyter Notebook **Correct Answer: B. Bandit

Rationale: HTTP 403 Forbidden indicates that the server understands the request but refuses to authorize access. HTTP 401 Unauthorized generally indicates that valid authentication credentials are missing or invalid. Question 9 A developer needs to ensure that passwords are not stored in plaintext in a user database. Which approach is most appropriate? A. Store passwords using Base64 encoding B. Hash passwords using Argon2 or bcrypt with appropriate parameters C. Encrypt passwords using a hardcoded key D. Store passwords in a hidden database table **Correct Answer: B. Hash passwords using Argon2 or bcrypt with appropriate parameters Rationale: Password hashing algorithms such as Argon2 and bcrypt are specifically designed to make password verification computationally expensive for attackers. Unique salts help prevent attackers from efficiently using precomputed password tables. Question 10 Which statement best describes the purpose of input validation in secure software development? A. To ensure user-supplied data meets expected requirements before processing B. To eliminate the need for authentication C. To increase the application's visual appearance D. To prevent all network communication **Correct Answer: A. To ensure user-supplied data meets expected requirements before processing Rationale: Input validation checks that submitted information conforms to expected formats, types, ranges, and business rules. It helps prevent malformed data, injection attacks, and unexpected application behavior. Question 11 A Python application executes operating-system commands using values supplied by users. Which vulnerability should developers primarily consider? A. Cross-site request forgery B. Weak session expiration C. Command injection D. Insecure cookie storage **Correct Answer: C. Command injection

Rationale: Command injection occurs when an application passes untrusted input into operating- system commands without appropriate safeguards. Developers should avoid shell execution where possible, use safe APIs, and pass arguments separately rather than constructing shell commands from user input. Question 12 Which Python programming practice is safest when reading files specified by users? A. Allowing unrestricted absolute file paths B. Automatically granting administrator permissions C. Disabling filesystem permissions D. Validating paths and restricting access to an approved directory **Correct Answer: D. Validating paths and restricting access to an approved directory Rationale: Restricting file access to approved directories helps prevent path traversal attacks. Developers should validate filenames, resolve paths safely, and ensure that user input cannot access sensitive files outside the intended location. Question 13 What is the primary purpose of authentication in an API? A. To verify the identity of the requesting user or system B. To increase database storage capacity C. To compress network traffic D. To generate application documentation **Correct Answer: A. To verify the identity of the requesting user or system Rationale: Authentication establishes who is making an API request. Authorization is a separate process that determines which resources and operations the authenticated identity is permitted to access. Question 14 Which security mechanism is commonly used to transmit authentication claims between applications and APIs in a JSON-based format? A. FTP B. JWT C. SMTP D. HTML **Correct Answer: B. JWT

Rationale: HTTPS uses Transport Layer Security (TLS) to provide encryption and help protect the integrity and authenticity of data transmitted between a client and server. It does not independently eliminate application-level vulnerabilities. Question 18 Which of the following best describes cross-site scripting (XSS)? A. An attacker physically accesses a server B. Malicious scripts are injected into content delivered to users' browsers C. An application stores duplicate database records D. A user enters an incorrect password **Correct Answer: B. Malicious scripts are injected into content delivered to users' browsers Rationale: Cross-site scripting occurs when untrusted content is included in web pages in a way that allows malicious scripts to execute in a victim's browser. Context-aware output encoding and safe content handling help prevent XSS. Question 19 A Python application displays user-submitted comments on a webpage. Which technique is most appropriate for reducing stored XSS risks? A. Disabling database backups B. Increasing the number of server threads C. Applying context-appropriate output encoding D. Changing the database password every hour **Correct Answer: C. Applying context-appropriate output encoding Rationale: Output encoding ensures that untrusted content is interpreted as data rather than executable browser code. The correct encoding method depends on the output context, such as HTML text, attributes, JavaScript, or URLs. Question 20 Which security principle recommends using multiple independent protective controls rather than relying on a single security mechanism? A. Open design B. Complete mediation C. Single-factor protection D. Defense in depth **Correct Answer: D. Defense in depth

Rationale: Defense in depth uses multiple layers of security, including authentication, authorization, encryption, input validation, monitoring, and network protection. If one control fails, additional controls may still prevent or reduce an attack. Question 21 What is the primary purpose of a software dependency vulnerability scanner? A. To identify known security vulnerabilities in third-party packages B. To create graphical user interfaces C. To increase processor speed D. To automatically rewrite all application functions **Correct Answer: A. To identify known security vulnerabilities in third-party packages Rationale: Dependency scanners compare installed libraries and package versions against known vulnerability databases. They help developers identify outdated or vulnerable dependencies and determine whether updates or alternative packages are necessary. Question 22 A developer discovers that a Python application uses an outdated library with a publicly documented critical vulnerability. What should be the first appropriate remediation approach? A. Ignore the vulnerability if the application runs correctly B. Upgrade to a secure supported version after compatibility and testing checks C. Remove all application logging D. Disable the application's authentication system **Correct Answer: B. Upgrade to a secure supported version after compatibility and testing checks Rationale: Updating a vulnerable dependency to a patched version is generally the preferred remediation when a compatible fix is available. Developers should review release notes, assess compatibility, and run regression and security tests. Question 23 Which Pytest assertion checks whether two values are equal? A. assert_true() B. assert_same() C. assert value1 == value D. assert_match() **Correct Answer: C. assert value1 == value

**Correct Answer: B. pytest.mark.parametrize Rationale: The pytest.mark.parametrize decorator allows one test function to execute multiple times with different parameter combinations. It reduces duplicated code and helps test multiple input scenarios efficiently. Question 27 Which test category evaluates an individual function or method independently from the rest of the application? A. Acceptance testing B. System testing C. Unit testing D. Penetration testing **Correct Answer: C. Unit testing Rationale: Unit testing focuses on small, isolated components such as individual functions and methods. It helps identify defects early and makes it easier to determine which component is responsible for a failure. Question 28 A developer writes a test to verify that an application rejects a user attempting to access an administrator-only endpoint without authorization. What type of testing is primarily being performed? A. Performance testing B. Usability testing C. Visual regression testing D. Security testing **Correct Answer: D. Security testing Rationale: Security testing evaluates whether an application properly protects resources against unauthorized access. Testing restricted endpoints verifies that authentication and authorization controls work as intended. Question 29 Which statement best describes static application security testing (SAST)? A. Analyzing source code or compiled code without executing the application B. Testing application performance under heavy network traffic C. Monitoring users while they interact with a live application D. Measuring database storage capacity **Correct Answer: A. Analyzing source code or compiled code without executing the application

Rationale: SAST examines application code without requiring the software to run. It identifies potentially insecure programming patterns, such as hardcoded secrets, unsafe function calls, and improper input handling. Question 30 Which statement best describes dynamic application security testing (DAST)? A. Reviewing only the application's source-code comments B. Testing a running application to identify security weaknesses C. Checking whether variable names follow naming conventions D. Formatting Python source files **Correct Answer: B. Testing a running application to identify security weaknesses Rationale: DAST evaluates an application while it is running, often by sending crafted requests and observing responses. It can identify vulnerabilities involving authentication, session management, input handling, and server behavior. Question 31 Which Python module is commonly used to generate cryptographically secure random values? A. random B. math C. secrets D. statistics **Correct Answer: C. secrets Rationale: The Python secrets module is designed to generate cryptographically strong random values suitable for passwords, authentication tokens, and security-sensitive identifiers. The standard random module is not intended for cryptographic security. Question 32 A developer needs to store sensitive application data so that unauthorized individuals cannot read it. Which security technique is most appropriate? A. Data compression B. File renaming C. Base64 encoding D. Encryption **Correct Answer: D. Encryption

Rationale: Path traversal occurs when attackers manipulate filenames or directory paths to access unauthorized files. Developers should validate input, normalize resolved paths, and restrict filesystem operations to approved directories. Question 36 Which HTTP response code generally indicates that a requested resource was successfully created? A. 400 B. 403 C. 404 D. 201 **Correct Answer: D. 201 Rationale: HTTP 201 Created indicates that a request successfully resulted in the creation of a new resource. It is commonly returned after a successful POST request that creates a resource. Question 37 A developer wants to prevent users from accessing another user's private records through an API. What should the application implement? A. Object-level authorization checks B. Larger database storage C. Automatic browser refresh D. Public resource identifiers only **Correct Answer: A. Object-level authorization checks Rationale: Object-level authorization ensures that the authenticated user has permission to access the specific record requested. Authorization must be checked on the server rather than relying on user interfaces or unpredictable identifiers. Question 38 Which practice helps prevent sensitive information from appearing in application log files? A. Logging every password entered by users B. Redacting passwords, access tokens, and other sensitive values C. Making all logs publicly accessible D. Disabling access controls for log files **Correct Answer: B. Redacting passwords, access tokens, and other sensitive values Rationale: Logs may contain sensitive information that attackers could exploit if exposed. Developers should avoid recording passwords, tokens, and confidential personal information, and should restrict access to logs.

Question 39 What is the primary purpose of the HTTP Authorization header? A. To identify the browser's screen resolution B. To define the server's storage capacity C. To transmit authentication credentials or authorization tokens D. To specify the webpage's background color **Correct Answer: C. To transmit authentication credentials or authorization tokens Rationale: The Authorization header carries credentials used by a server to authenticate a request. Common examples include Bearer tokens and Basic authentication credentials. HTTPS should be used to protect these values during transmission. Question 40 A Python developer wants to ensure that a function raises a ValueError when given an invalid input. Which Pytest approach is most appropriate? A. pytest.mark.skip B. pytest.fixture C. pytest.mark.parametrize only D. pytest.raises(ValueError) **Correct Answer: D. pytest.raises(ValueError) Rationale: The pytest.raises context manager verifies that a specific exception is raised during test execution. It is useful for validating error handling and ensuring that functions reject invalid inputs as expected. Question 41 Which of the following is the most appropriate way to handle unexpected exceptions in a production Python application? A. Catch exceptions appropriately, log useful diagnostic information, and avoid exposing sensitive details B. Display complete internal stack traces to every user C. Ignore all exceptions without recording them D. Disable all application error handling **Correct Answer: A. Catch exceptions appropriately, log useful diagnostic information, and avoid exposing sensitive details Rationale: Proper exception handling prevents unexpected failures from exposing sensitive implementation details. Developers should record relevant diagnostic information securely while returning generic, appropriate error messages to users.

Rationale: MFA requires users to verify their identity using two or more different authentication factors, such as something they know, something they possess, or something they are. This provides additional protection if a password is compromised. Question 45 A developer wants to verify that an API returns an HTTP 401 response when a request lacks valid authentication credentials. Which testing approach is most appropriate? A. Send an unauthenticated request and assert that the response status code equals 401 B. Send a valid administrator token and expect a successful response C. Delete the application's source code D. Disable the API endpoint before testing **Correct Answer: A. Send an unauthenticated request and assert that the response status code equals 401 Rationale: Testing an API without authentication credentials verifies whether authentication controls are enforced. The test should assert that the server returns the expected 401 response instead of granting unauthorized access. Question 46 Which security testing technique involves attempting to exploit weaknesses in an application to determine whether they can be abused? A. Code formatting B. Penetration testing C. Documentation review D. Database indexing **Correct Answer: B. Penetration testing Rationale: Penetration testing involves authorized security assessments that simulate attacker techniques to identify exploitable vulnerabilities. Findings are documented and prioritized so developers can implement appropriate security improvements. Question 47 What is the primary purpose of regression testing after fixing a software vulnerability? A. To remove all previous test cases B. To increase the application's file size C. To verify that the changes have not broken existing functionality D. To replace the application's authentication system **Correct Answer: C. To verify that the changes have not broken existing functionality

Rationale: Regression testing checks whether new changes have unintentionally affected previously working features. After security remediation, developers should verify both that the vulnerability is fixed and that existing functionality continues to operate correctly. Question 48 Which of the following best describes secure software development? A. Adding security controls only after an attack occurs B. Allowing unrestricted access to application resources C. Ignoring security testing to accelerate deployment D. Integrating security considerations throughout the software development lifecycle **Correct Answer: D. Integrating security considerations throughout the software development lifecycle Rationale: Secure software development incorporates security requirements, threat analysis, secure coding, testing, deployment safeguards, and ongoing maintenance. Integrating security throughout development helps identify and address weaknesses earlier. Question 49 A developer is preparing a security remediation report after discovering and fixing a vulnerability. Which information should be included to make the report useful? A. The vulnerability identified, its potential impact, remediation steps, and testing evidence B. Only the developer's name C. The application's color scheme D. A list of unrelated software packages **Correct Answer: A. The vulnerability identified, its potential impact, remediation steps, and testing evidence Rationale: A useful remediation report documents the original security issue, its potential consequences, the corrective action taken, and evidence demonstrating that the fix works. This supports accountability, verification, and future maintenance. Question 50 A development team has fixed an insecure API endpoint, upgraded a vulnerable Python dependency, and implemented additional authentication checks. What should the team do before approving the application for production deployment? A. Immediately remove all security tests B. Run relevant automated tests, security scans, and regression tests to verify the changes C. Disable application monitoring D. Publish the application's credentials for review

3. Which practice is safest when storing user passwords in a Python application

database?

A. Hash passwords using a slow, salted cryptographic hashing algorithm such as Argon2, bcrypt, or PBKDF B. Encrypt passwords with a symmetric AES key hardcoded in config.py C. Store SHA-256 hashes without a per-user salt D. Encode passwords using rot13 or hexadecimal strings Answer: A. Hash passwords using a slow, salted cryptographic hashing algorithm such as Argon2, bcrypt, or PBKDF Rationale: Salted, slow key-derivation/hashing functions (Argon2, bcrypt, PBKDF2) resist precomputed rainbow tables and slow down brute-force attacks.

4. A Flask or FastAPI endpoint accepts a JSON payload containing a user role field

('role': 'admin') and assigns it directly to the user model without authorization

checks. What weakness does this demonstrate?

A. Mass assignment (over-posting) or broken object/function-level authorization B. Deterministic unit test isolation C. Proper principle of least privilege D. Safe deserialization with schema allowlisting Answer: A. Mass assignment (over-posting) or broken object/function-level authorization Rationale: Binding untrusted client fields directly to privileged attributes without allowlisting or authorization checks lets attackers escalate privileges.

5. When writing a pytest test for a Python function that must raise a ValueError

when given a negative amount, which construct is idiomatic?

A. Use 'with pytest.raises(ValueError):' around the call that should fail B. Use 'assert True' inside an except block that catches all exceptions C. Print the error message to stdout and check length with len() D. Disable assertions by passing '-O' to pytest Answer: A. Use 'with pytest.raises(ValueError):' around the call that should fail Rationale: pytest.raises(ValueError) verifies both that the expected exception type is raised and allows asserting details about the exception.

6. A Python API calls subprocess.run(f'ping - c 1 {host}', shell=True). What security risk

is introduced by shell=True with unvalidated input?

A. OS command injection allowing arbitrary shell commands to run via metacharacters like ';' or '|' B. Automatic removal of environment variables across the operating system C. Guaranteed TLS downgrade to SSLv D. Compilation errors in pytest parameterized tests Answer: A. OS command injection allowing arbitrary shell commands to run via metacharacters like ';' or '|' Rationale: Passing unsanitized input to a shell interpreter lets attackers chain commands; passing an argument list with shell=False is much safer.

7. Which approach best protects sensitive API tokens and database credentials in a

Python project?

A. Inject secrets via environment variables or a dedicated secrets manager and exclude .env/secret files from version control B. Commit production API keys to a private Git branch and share them in chat C. Embed tokens in client-side JavaScript bundles D. Log full Authorization headers at the INFO level for debugging Answer: A. Inject secrets via environment variables or a dedicated secrets manager and exclude .env/secret files from version control Rationale: Keeping secrets out of source code and logs prevents accidental exposure when repositories are cloned, shared, or breached.

8. A Python application uses pickle.loads(data) on bytes received over an

unauthenticated network socket. Why is this dangerous?

A. Arbitrary code execution can occur during unpickling of untrusted data B. pickle.loads only works on read-only JSON strings C. It automatically encrypts payloads with RSA- 4096 D. It prevents integer overflow in all C extensions Answer: A. Arbitrary code execution can occur during unpickling of untrusted data Rationale: Python's pickle module is not secure against maliciously constructed data; unpickling untrusted input can execute arbitrary code.