














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!















Hardcoded secrets and credentials
Passwords and application secrets should not be exposed unnecessarily in source code. A Flask session secret, for example, protects the integrity of signed session information. Static analyzers may identify obvious embedded passwords or secrets; manual inspection is still required to decide how the values are used. In the
demonstration implementation, the login password is supplied through an environment variable, and the application supports an externally configured Flask secret.
Improper exception handling
An exception can arise even in a small application. Looking up an equipment identifier that is not in a dictionary
raises a KeyError. Converting a nonnumeric string to an integer raises a ValueError. If those conditions are not handled, the request may fail in a way the user cannot understand. The relevant issue is not merely whether an exception occurs, but whether the program recovers from an expected error and avoids exposing internal details.
Security misconfiguration
Development settings are not necessarily appropriate for production. Flask debug mode can expose sensitive
diagnostic information and should not be enabled on a public deployment. The reconstructed application runs with debug mode disabled and avoids writing authentication secrets to the log. Configuration review is still necessary before any real deployment.
Unused code and unreliable program logic
Unused branches, duplicated routines, and inconsistent checks make a program harder to inspect and maintain. They may also conceal mistakes in security-sensitive paths. A static analyzer can report some of these defects. Manual review provides a second opportunity to check whether the validation and authentication logic follow
the intended order.
A3. Issues Identified in the Supplied Application Reference
The supplied D385 Task 1 reference reports five concerns in a Flask-based equipment rental system: missing structured logging, a hardcoded secret, insufficient input validation, missing exception handling, and a limited response to suspicious activity. These findings are summarized here as reported observations; the original WGU
application files were not available for independent code inspection.
1. Missing structured logging
Without a reliable event record, it is difficult to determine why a login failed or why a rental calculation did not complete. I addressed this concern in the reconstructed application by configuring Python logging at the INFO
level and recording the event together with the action taken by the program. Authentication results, input rejections, and successful calculations are each given a consistent message.
2. A secret embedded in the application
The reference identifies a hardcoded session secret. A disclosed signing key creates an unnecessary risk because
session data can no longer be trusted in the same way. The demonstration reads FLASK_SECRET_KEY from its environment when one is provided, rather than depending on a fixed value in the source. A secure, persistent key and managed storage would be necessary for a deployed system.
B2. Exception Handling
The rental route processes equipment selection before rental duration. An identifier that is not present in the EQUIPMENT_PRICES dictionary raises KeyError when the price is retrieved. In the reconstructed implementation, a dedicated handler catches the exception, records an ERROR event, and returns HTTP 400
with the message “Please select valid equipment.” Because normal use presents a fixed equipment list, an unknown identifier is unexpected and deserves attention.
Rental duration is handled separately. The value is submitted as text and converted using int(). A nonnumeric
value raises ValueError, and a missing value may raise TypeError. The application also raises ValueError when the number is zero or negative. These conditions share one handler that records WARNING and returns “Days must be a positive whole number.” An incorrect day value is more likely to be an ordinary input mistake than evidence of malicious behavior.
Both handlers return controlled responses rather than exposing an exception trace in the user interface. This behavior improves reliability without hiding the fact that an error occurred: the application still writes a record of the rejected operation for troubleshooting.
B3. Assertions
Assertions were added to express two assumptions about values that the application has already checked. The first verifies that a username is a nonempty string after explicit username validation. The second verifies that the login request contains a nonempty client-address string after the route has checked that the value is present.
Each successful assertion has a corresponding INFO-level log message.
The assertions serve as development checks, not as security barriers. Python can remove assert statements when optimization is enabled, so the application performs ordinary validation before either assertion. The username allowlist and password comparison remain the actual authentication checks. A separate assertion in the rental
route checks the internal assumption that the validated rental price and number of days are positive.
B4. Working Application
The Flask application contains a home page, a login page, and a rental form. An authorized account can sign in, choose Bulldozer, Excavator, or Forklift, and enter the number of rental days. The daily demonstration rates are
800, 650, and 350 units, respectively. Three days of Bulldozer rental therefore yields 800 × 3 = 2,400 units.
The login page distinguishes valid credentials from failed authentication, and the rental form provides an understandable message when the days value is invalid. Access to the rental route without a session redirects the
user to the login page. These are the behaviors implemented in the source listing in Appendix A.
Application evidence. The screenshot of the application running in a browser must be obtained from an actual local run. No new browser screenshot is included in this report because the Flask runtime was unavailable in the document-preparation environment. The screenshots reproduced in the supplied reference show a different run
and are not being presented as evidence for the code attached here.
B5. Testing the Application
The test suite in Appendix B uses pytest and Flask’s test client. It sends requests to the application and checks response codes, displayed messages, calculation results, and selected logging behavior. The following four tests are the principal evidence cases because each exercises a different validation or error-handling path.
Test case Request being checked Expected result
Invalid equipment Unknown equipment_type with three rental days HTTP 400; equipment message
Nonnumeric duration Bulldozer with days="abc" HTTP 400; duration warning
Negative duration Bulldozer with days="-2" HTTP 400; duration warning
Unapproved username Username outside approved allowlist HTTP 401; login denied
Five additional tests cover successful login, rejected credentials, missing days, a valid total of 2,400 units, and the two INFO records associated with the login assertions. These tests are included so that a correction in one area is less likely to introduce an unnoticed regression elsewhere.
Test evidence. The Python scripts were checked for syntax errors. The integration tests could not be run here
because Flask was not installed in the available Python environment and package installation was unsuccessful. Passing test screenshots are therefore not claimed or attached. Four distinct screenshots should be captured after running the suite in a configured environment, with each relevant test name and PASS result visible.
C. Review of Logs and Debugging Decisions
C1. Log Analysis
a. Relationship between program activity and the log
The most useful feature of the logging design is that application outcomes can be connected to a specific action. A successful login records that the session was created. A rejected login records that credentials were not accepted. When a rental request succeeds, the program logs the successful calculation; when input is rejected, it
logs the corresponding error category. This makes the log more useful than a series of generic print statements.
The configured format supports a chronological review of events. The expected shape is “timestamp - severity - EVENT: description | ACTION: response.” Actual entries must come from the output file after running the application; a representative format alone does not establish that the application wrote those entries.
b. Two events worth examining
One event to investigate is an unknown equipment identifier. The equipment field normally comes from a fixed selection list. An identifier that is not in the price dictionary could indicate a changed request, an outdated form, or an application error. The handler classifies the event as ERROR and refuses the calculation. If it occurs
repeatedly, the log offers a starting point for investigating request origin and sequence.
A second event is an invalid rental duration. A value such as “abc” cannot be converted to an integer, while a negative duration violates the business rule even though the conversion itself succeeds. Both lead to a
There are still limits to the demonstration. It does not implement complete account management, production password storage, login rate limiting, or centralized alerting. Those concerns would require additional design and verification before public deployment. The purpose here is narrower: to make the rental workflow more
predictable and easier to troubleshoot.
C4. Role of Static Analysis in Software Security
Static analysis is useful because it brings attention to weaknesses before the code is deployed. In the rental application, reviewing how values move from the login and rental forms into the program reveals several places
where defensive checks are necessary. Reviewing configuration and logging is equally important, since application failures and security events should be diagnosed without exposing sensitive information.
At the same time, a clean static-analysis result would not prove that the application behaves correctly. A test must still show what happens when an invalid equipment name is sent, when rental days are missing, or when a
username is not approved. The combination of source review, logging, exception handling, and repeatable tests is therefore more useful than any one technique alone. This approach is consistent with the secure development practices described in NIST SP 800-218 (NIST, 2022).
D. References
National Institute of Standards and Technology. (2022). Secure software development framework (SSDF), version 1.1: Recommendations for mitigating the risk of software vulnerabilities (NIST SP 800-218). https://doi.org/10.6028/NIST.SP.800-
Open Worldwide Application Security Project. (n.d.-a). Static code analysis. https://owasp.org/www-community/controls/Static_Code_Analysis
Open Worldwide Application Security Project. (n.d.-b). Logging cheat sheet. https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
Pallets Projects. (n.d.). Testing Flask applications. https://flask.palletsprojects.com/en/stable/testing/
Python Software Foundation. (n.d.). Logging HOWTO. https://docs.python.org/3/howto/logging.html
pytest Development Team. (n.d.). pytest documentation. https://docs.pytest.org/en/stable/
Appendix A. Python Application Source
The following listing is the reconstructed Flask application referred to in the report. It is provided for review and reproduction; it is not represented as the official WGU starter code.
File: app_student.py
"""Original D385 Task 1 demonstration: local equipment rental Flask app.""" import hmac import logging import os import secrets from pathlib import Path
from flask import Flask, redirect, render_template_string, request, session, url_for
LOG_FILE = Path(file).resolve().parent / 'Troubleshooting_DEMO.log' logging.basicConfig( filename=str(LOG_FILE), filemode='a', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', encoding='utf-8', force=True, ) logger = logging.getLogger('equipment_rental')
app = Flask(name)
app.config['SECRET_KEY'] = os.environ.get('FLASK_SECRET_KEY') or secrets.token_hex(32) app.config['TESTING'] = False
ALLOWED_USERS = {'admin', 'alice', 'bob', 'charlie'} EQUIPMENT_PRICES = {'Bulldozer': 800, 'Excavator': 650, 'Forklift': 350}
LOGIN_HTML = ''' Equipment Rental System: Login
Username Password Login
{% if message %}
{{ message }}
{% endif %} ''' RENT_HTML = ''' Rent EquipmentEquipment {% for name in prices %}{% endfor %}
Number of Days Calculate
{% if message %}
{{ message }}
{% endif %} {% if total is not none %}Total Cost: {{ total }}
{% endif %} '''def record(level, event, action): """Record an event and the defensive action without sensitive data.""" logger.log(level, 'EVENT: %s | ACTION: %s', event, action)
def validate_username(username): """Explicitly reject invalid user input; assert only after validation."""
message=None, total=total)
except KeyError: record(logging.ERROR, 'Unknown equipment identifier', 'Reject unapproved equipment') return render_template_string(RENT_HTML, prices=EQUIPMENT_PRICES, message='Please select valid equipment.', total=None), 400 except (ValueError, TypeError): record(logging.WARNING, 'Invalid rental duration', 'Reject malformed or nonpositive days') return render_template_string(RENT_HTML, prices=EQUIPMENT_PRICES, message='Days must be a positive whole number.', total=None), 400
if name == 'main': app.run(host='127.0.0.1', port=5000, debug=False)
Appendix B. Automated Tests
The pytest suite exercises login validation, rental calculation, exception handlers, and assertion-related logging. The code is supplied as written; actual execution evidence has not been invented.
File: test_run.py
"""Tests for original D385 Task 1 demonstration application.""" import logging import pytest
from app_student import app, LOG_FILE, logger
TEST_PASSWORD = 'LocalTestPassword-Only'
@pytest.fixture def client(monkeypatch): monkeypatch.setenv('RENTAL_DEMO_PASSWORD', TEST_PASSWORD) app.config.update(TESTING=True) with app.test_client() as test_client: yield test_client
def login_as_admin(client): response = client.post('/login', data={'username': 'admin', 'password': TEST_PASSWORD}) assert response.status_code == 200 return response
def test_successful_login(client): result = login_as_admin(client) assert b'LOGIN SUCCESS' in result.data
def test_failed_login(client): response = client.post('/login', data={'username': 'admin', 'password': 'incorrect'}) assert response.status_code == 401 assert b'Invalid username or password' in response.data
def test_invalid_equipment_type_handled(client): login_as_admin(client) response = client.post('/rent', data={'equipment_type': 'NotInPriceList', 'days': '3'}) assert response.status_code == 400 assert b'Please select valid equipment' in response.data
def test_non_numeric_days_handled(client): login_as_admin(client) response = client.post('/rent', data={'equipment_type': 'Bulldozer', 'days': 'abc'}) assert response.status_code == 400 assert b'positive whole number' in response.data
def test_negative_days_rejected(client): login_as_admin(client) response = client.post('/rent', data={'equipment_type': 'Bulldozer', 'days': '-2'}) assert response.status_code == 400 assert b'positive whole number' in response.data
def test_invalid_username_rejected(client): response = client.post('/login', data={'username': 'unknown-user',
Appendix C. Setup and Evidence Collection
The requirements file contains Flask and pytest. On a Windows computer with Python installed, run the following commands from the project directory. The example password is intended only for local testing.
py -m pip install -r requirements.txt $env:RENTAL_DEMO_PASSWORD = 'ChooseYourLocalDemoPassword' $env:FLASK_SECRET_KEY = py -c "import secrets;print(secrets.token_hex(32))" py -m pytest test_run.py -v py app_student.py
Open http://127.0.0.1:5000 and sign in with the username admin and the password chosen in the first environment variable. Check both valid and invalid rental entries, then open Troubleshooting_DEMO.log in the same project directory. The file should show corresponding timestamped INFO, WARNING, and ERROR entries when the relevant actions have been exercised.
For the final task evidence, retain a screenshot of the running application and four separate readable screenshots of the designated passing tests. Check that the screenshot content matches the code and log file being submitted. Also compare the implementation and its filenames against the current official task instructions and any starter files issued for the course.
The source files, dependency list, and setup instructions are also packaged separately as WGU_D385_Task1_Original_Demo_Code.zip.