Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28d13ef5b8 | ||
|
|
83da3087c9 | ||
|
|
c35558c20b | ||
|
|
242372e381 | ||
|
|
f44cebd00e | ||
|
|
f55a36468c | ||
|
|
bda4ac8240 | ||
|
|
344dbcbcd4 | ||
|
|
10c85ea655 |
@@ -0,0 +1,25 @@
|
||||
pipeline {
|
||||
agent { label 'assignment8-trusted' }
|
||||
options { disableConcurrentBuilds(); timeout(time: 20, unit: 'MINUTES'); timestamps(); skipDefaultCheckout() }
|
||||
stages {
|
||||
stage('Checkout') { steps { checkout scm } }
|
||||
stage('Unit tests and dependency audit') {
|
||||
steps { dir('secure-delivery/v1') { sh '''set -eu
|
||||
python3 -m venv .test-venv
|
||||
.test-venv/bin/pip install -r requirements.txt pip-audit==2.10.1
|
||||
.test-venv/bin/python -m unittest -v
|
||||
.test-venv/bin/pip-audit -r requirements.txt
|
||||
''' } }
|
||||
}
|
||||
stage('Secret scan') { steps { sh 'sh secure-delivery/scan-secrets.sh' } }
|
||||
stage('Ansible syntax') { steps { dir('secure-delivery') { sh 'ansible-playbook -i ansible/inventory.ini ansible/deploy.yml --syntax-check' } } }
|
||||
stage('Build test image') { steps { sh 'docker build --build-arg APP_COMMIT=$(git rev-parse HEAD) -t assignment8-pricing:security-check secure-delivery/v1' } }
|
||||
stage('Image vulnerability scan') {
|
||||
steps { sh '''set -eu
|
||||
mkdir -p reports
|
||||
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v /home/codex/myfileagent-gitea/evidence/assignment8/trivy-cache:/root/.cache/ aquasec/trivy@sha256:1c78ed1ef824ab8bb05b04359d186e4c1229d0b3e67005faacb54a7d71974f73 image --quiet --scanners vuln --severity HIGH,CRITICAL --exit-code 1 --format json assignment8-pricing:security-check > reports/image-scan.json
|
||||
''' }
|
||||
}
|
||||
}
|
||||
post { always { archiveArtifacts artifacts: 'reports/*.json', allowEmptyArchive: true } }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
pipeline {
|
||||
agent { label 'assignment8-trusted' }
|
||||
options { disableConcurrentBuilds(); timeout(time: 15, unit: 'MINUTES'); timestamps() }
|
||||
stages {
|
||||
stage('Checkout') { steps { checkout scm } }
|
||||
stage('Unit tests') {
|
||||
steps {
|
||||
dir('secure-delivery/v1') {
|
||||
sh '''set -eu
|
||||
python3 -m venv .test-venv
|
||||
.test-venv/bin/pip install -r requirements.txt
|
||||
.test-venv/bin/python -m py_compile app.py test_app.py
|
||||
.test-venv/bin/python -m unittest -v
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Ansible syntax') {
|
||||
steps { dir('secure-delivery') { sh 'ansible-playbook -i ansible/inventory.ini ansible/deploy.yml --syntax-check' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
# Chapter 6: Startup Pricing Service
|
||||
|
||||
`v1/` and `v2/` are two releases of the same stateless Flask service. Version 1
|
||||
charges USD 10 per unit; version 2 charges USD 12. Three units cost 30 and 36.
|
||||
Both use Gunicorn, run as a non-root container user, and expose port 8000.
|
||||
No database, real customer data, payment processing, or credentials are involved.
|
||||
|
||||
## Local checks
|
||||
|
||||
Run from either version directory, using a disposable virtual environment:
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
. .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
python -m unittest -v
|
||||
```
|
||||
|
||||
Requirements are compatibility ranges, not a reproducible lock. Before the
|
||||
assessed release, resolve, review, scan, and commit exact dependency versions
|
||||
(including transitive dependencies) and an approved base-image digest. Save
|
||||
scanner versions and reports. These starter files make no vulnerability claim.
|
||||
|
||||
## Build and publish
|
||||
|
||||
Copy v1 into the team application's working directory and commit it. Build from
|
||||
that directory on the trusted Jenkins agent. Use the Gitea registry hostname
|
||||
without a URL scheme; replace the owner/team with its actual lowercase name.
|
||||
|
||||
```sh
|
||||
COMMIT=$(git rev-parse HEAD)
|
||||
IMAGE=gitea.example.edu/team/pricing
|
||||
# Authenticate separately using a Jenkins credential and --password-stdin.
|
||||
docker build --build-arg APP_COMMIT="$COMMIT" -t "$IMAGE:$COMMIT" .
|
||||
docker push "$IMAGE:$COMMIT"
|
||||
docker pull "$IMAGE:$COMMIT"
|
||||
docker image inspect "$IMAGE:$COMMIT" --format '{{index .RepoDigests 0}}'
|
||||
```
|
||||
|
||||
Save that repository digest in a release record. Build once; use the same digest
|
||||
in staging and production. For v2, replace app.py and test_app.py with the v2
|
||||
files, commit, and repeat the pipeline. Do not build the entire parent directory.
|
||||
Use a Linux image architecture compatible with the droplet.
|
||||
|
||||
## One-time deployment preparation
|
||||
|
||||
Install Ansible in a virtual environment on a trusted Linux Jenkins agent; use a
|
||||
Python version supported by your selected ansible-core release. Record exact
|
||||
resolved versions after installation.
|
||||
|
||||
```sh
|
||||
python3 -m venv .ansible-venv
|
||||
. .ansible-venv/bin/activate
|
||||
pip install ansible-core
|
||||
ansible-galaxy collection install -r ansible/requirements.yml
|
||||
ansible --version
|
||||
ansible-galaxy collection list
|
||||
```
|
||||
|
||||
On the target droplet, install Python 3, Docker Engine and the Compose v2 plugin
|
||||
(at least 2.18); verify `docker compose version`. Configure a dedicated SSH
|
||||
account and the approved escalation policy. The playbook uses become and needs
|
||||
noninteractive sudo; this is powerful host access. Do not grant it to untrusted
|
||||
pull-request jobs. Verify/pin the SSH host key in the Jenkins agent's known_hosts.
|
||||
Keep private keys, sudo credentials and package tokens in Jenkins credentials.
|
||||
|
||||
Identify the existing reverse proxy's Docker network with `docker network ls`
|
||||
and its current Compose configuration. Both app projects join that external
|
||||
network. Configure the proxy once, preserving all existing routes:
|
||||
|
||||
```caddyfile
|
||||
staging.example.edu {
|
||||
reverse_proxy pricing-staging:8000
|
||||
}
|
||||
app.example.edu {
|
||||
reverse_proxy pricing-production:8000
|
||||
}
|
||||
```
|
||||
|
||||
Use your real DNS names pointing to the droplet and valid TLS certificates.
|
||||
The proxy must be attached to that network. For a host-based proxy, adapt the
|
||||
Compose template to distinct loopback ports and proxy to those ports instead.
|
||||
The supplied template is for a container-based proxy; do not publish raw 8000.
|
||||
|
||||
Authenticate Docker on the target as the account used by become (normally root)
|
||||
using a read-only package credential and `docker login --password-stdin` through
|
||||
a protected administrator session. The Jenkins build agent separately needs a
|
||||
package-write credential. Never commit either credential or Docker config.json.
|
||||
Do not enable insecure registry access or disable certificate verification.
|
||||
|
||||
## Deploy and roll back
|
||||
|
||||
Fill inventory.ini and copy release.example.yml to releases/v1-staging.yml.
|
||||
Replace every placeholder. Keep this release metadata in Git; it has no secrets.
|
||||
Use the exact source commit, registry digest, proxy network, URL and expected
|
||||
values. From this starter directory:
|
||||
|
||||
```sh
|
||||
ansible-playbook -i ansible/inventory.ini ansible/deploy.yml --syntax-check
|
||||
ansible-playbook -i ansible/inventory.ini ansible/deploy.yml -e @releases/v1-staging.yml
|
||||
```
|
||||
|
||||
Run again unchanged and show changed=0. If the module reports unexpected
|
||||
changes, inspect Compose/plugin versions and the task diff before claiming
|
||||
idempotence. Create a production record with the same image digest and the
|
||||
production target and URL; deploy only after an authorized Jenkins approval.
|
||||
Disable concurrent delivery builds to prevent competing releases.
|
||||
|
||||
Preserve each release's Compose template/configuration commit as well as its
|
||||
image digest. For rollback, check out the previous reviewed deployment files
|
||||
and run its production release record again. The current playbook does not
|
||||
perform an automatic rollback: a failed check fails the run and requires the
|
||||
explicit rollback stage/runbook. Never use `down -v`, prune shared volumes, or
|
||||
roll back Gitea/Jenkins as part of the application exercise.
|
||||
|
||||
For a controlled failure, use staging only: temporarily set the service's
|
||||
Compose `command` to `["gunicorn", "--bind", "0.0.0.0:8001", "app:app"]` in a
|
||||
separate configuration commit. The image healthcheck still probes 8000, so
|
||||
Compose wait should fail. Save the failure, restore the previous configuration
|
||||
commit, and redeploy its release record. Do not stop the host Docker service.
|
||||
|
||||
For the business rollback, deploy healthy v2, verify version v2 and total 36,
|
||||
then redeploy v1 and verify version v1 and total 30. Measure interruption and
|
||||
recovery time. This recreate strategy does not provide zero downtime.
|
||||
|
||||
Implement the Jenkins stages, security policy, approval and evidence described
|
||||
in Chapter 6; the examples are application/deployment starters, not a complete
|
||||
Jenkins pipeline. Container builds and remote deployment were not executed by
|
||||
the author in a student environment.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Assignment 8 release security policy
|
||||
|
||||
The trusted release job must run only reviewed source and must not expose deployment or registry credentials to pull-request builds. Restrict the agent to labeled release jobs and authorized Jenkins users. Docker daemon access confers host-administrator privileges. Record agent identity, access scope, tool versions, scan time, database version, exit status, and archived reports for each release.
|
||||
|
||||
Before publication, fail on discovered secrets and on HIGH or CRITICAL vulnerabilities unless a documented time-limited exception is accepted by the instructor. Fail closed if a scanner fails or its database is unavailable. Investigate false positives and unfixed findings; document owner, reason, expiry, and approval for any exception. Never publish a deliberately vulnerable image as the working release.
|
||||
|
||||
Run a dependency audit against the exact locked requirements, a repository secret scan, and an image vulnerability scan against the built release image. Demonstrate a blocked gate with a scanner-supported synthetic fixture and remove it before release. The initial pip-audit result in WORK_LOG.md is a baseline, not the final release scan.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Assignment 8 work log
|
||||
|
||||
## 2026-11-04 baseline
|
||||
- Starting repository main: 10c85ea (Assignment 7 manual 1.9.2 merge). Working branch: assignment8/secure-delivery.
|
||||
- Existing Gitea, Jenkins, Caddy, and four monitoring containers observed running. Docker 29.8.1; Compose 5.5.1; architecture x86_64.
|
||||
- Jenkins controller is containerized; no dedicated agent found in initial inspection. Ansible core 2.22.0 and community.docker 5.0.4 installed under persistent Jenkins home. Python venv system package installed in running container; container recreation provisioning still needed. Controller must not be used for assessed deployment.
|
||||
- Starter v1 unit tests: 3 passed locally and inside isolated Jenkins Python 3.13 environment. Exact direct/transitive versions recorded in requirements.txt.
|
||||
- pip-audit against pinned requirements reported no known vulnerabilities at time of check. This does not establish image or secret scan status; retain a formal report in pipeline.
|
||||
- Python 3.13 slim base digest pinned to sha256:ae14d4ce8771606477a81446e7ef429edd6762305fc50c84507c1041fa8285d1 (linux/amd64). Local baseline image built with APP_COMMIT=baseline-test; this is not an assessed release or registry digest.
|
||||
- Droplet baseline: 961 MiB RAM, 270 MiB available and 840 MiB swap used at inspection. Recheck before adding services.
|
||||
- No staging/production deployment, approval, image publication, controlled failure, or rollback has been performed.
|
||||
|
||||
## Agent setup
|
||||
- Created Jenkins permanent node assignment8-trusted with one executor and label-only scheduling. An official inbound-agent container connects through the existing private Docker network using WebSocket and a protected secret file. Agent logs reported Connected. No Docker socket or deployment credentials were granted.
|
||||
- Built a draft agent Dockerfile with Python, Docker and Ansible, but image packaging stalled while the host reported all 1 GiB swap in use; the build was interrupted to avoid overloading existing services. The Dockerfile is not yet validated: the Docker collection was installed under root and must be moved to a location readable by the Jenkins user. The running agent remains the original image and does not yet have Python, Docker or Ansible. No agent job has been verified.
|
||||
|
||||
## Agent progress after swap increase
|
||||
- Total swap verified at 2 GiB. Agent image built and connected; Python 3.13.5, Ansible core 2.22.0 and community.docker 5.0.4 verified as Jenkins user. Docker CLI 26.1.5 installed in running container; Dockerfile corrected to include docker-cli but requires rebuilding and recreation to persist that change. No Docker socket or deployment credentials have been added. A Jenkins job has not yet been run on the agent.
|
||||
|
||||
- Corrected agent image built as assignment8-jenkins-agent:2 and agent reconnected on 2026-11-04. Python 3.13.5 and Docker CLI 26.1.5 observed in recreated container. Ansible and community.docker were verified in previous image with identical installation steps; recheck after recreation. No Docker socket, deployment credential, or Jenkins test job yet.
|
||||
|
||||
## Agent Jenkins verification
|
||||
- Jenkins job assignment8-agent-check build #1 failed during pipeline parsing because the initial one-line declarative script lacked section separators; no agent work occurred. Corrected script and reran. Build #2 succeeded on assignment8-trusted and verified Python 3.13.5, Git 2.47.3, Docker CLI 26.1.5, Ansible core 2.22.0, and community.docker 5.0.4. Evidence: https://ci.myfileagent.tech/job/assignment8-agent-check/2/console . Docker daemon access and deployment credentials remain unconfigured.
|
||||
|
||||
## Validation preparation
|
||||
- Ansible syntax check passed on assignment8-trusted against the starter playbook on 2026-11-04. The inventory and release records still contain placeholders; syntax success is not deployment. Added a separate draft validation Jenkinsfile for tests and syntax checks; it has not been run in Jenkins.
|
||||
|
||||
## Gitea-backed validation
|
||||
- Published branch assignment8/secure-delivery at 242372e381ecbcab4078e7d8c0916073d600d970. Jenkins assignment8-validation build #1 checked out that commit on assignment8-trusted, passed all 3 v1 unit tests and passed Ansible syntax check. Evidence: https://ci.myfileagent.tech/job/assignment8-validation/1/console . This does not demonstrate deployment, security gates, or image publication.
|
||||
|
||||
## Initial image security checks
|
||||
- User approved host Docker daemon access for the label-restricted trusted agent; its connection was verified. This access is effectively host administration. Agent-built test image succeeded with placeholder identity, not a release.
|
||||
- Trivy 0.69.1 scan of the Debian slim test image failed the HIGH/CRITICAL gate: 45 Debian and 5 Python findings. A pinned Python Alpine candidate had no OS findings but 5 Python tooling findings. After removing pip and ensurepip bundled wheels from runtime, the candidate scan reported zero HIGH/CRITICAL findings, exit 0, at the time of scan. Reports are in server evidence/assignment8; rescan the actual release image and archive results.
|
||||
- Isolated candidate smoke test initially ran before startup and got connection refused; after allowing startup, health was ok, v1 identity returned development placeholder, and quantity 3 returned 30. No production deployment occurred.
|
||||
|
||||
- Trivy 0.69.1 secret scanner standalone test: an example-format fixture was ignored (exit 0), then a newly generated disposable private-key fixture produced one finding and exit 1. Both fixture files were removed. This proves scanner behavior only; a blocked Jenkins pipeline run remains required.
|
||||
|
||||
## Jenkins synthetic secret gate
|
||||
- Jenkins assignment8-secret-gate-demo #4 detected one generated disposable private key and failed with scanner exit 1; the job removed the fixture. Earlier attempts #1-3 failed due to transfer or job-script errors, not secret detections. Evidence: https://ci.myfileagent.tech/job/assignment8-secret-gate-demo/4/console . Prepared source-controlled security pipeline; it has not yet been run.
|
||||
@@ -0,0 +1,6 @@
|
||||
FROM jenkins/inbound-agent@sha256:5069347cd3e72e5924e54c04fceb67209b41c8d0a3ab1c2b3f740e5fb2fab92a
|
||||
USER root
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends python3 python3-venv docker-cli openssh-client && rm -rf /var/lib/apt/lists/*
|
||||
RUN python3 -m venv /opt/ansible && /opt/ansible/bin/pip install --no-cache-dir ansible-core==2.22.0 && /opt/ansible/bin/ansible-galaxy collection install -p /usr/share/ansible/collections community.docker:5.0.4
|
||||
ENV PATH="/opt/ansible/bin:${PATH}"
|
||||
USER jenkins
|
||||
@@ -0,0 +1,10 @@
|
||||
pipeline {
|
||||
agent { label 'assignment8-trusted' }
|
||||
stages {
|
||||
stage('Verify tools') {
|
||||
steps {
|
||||
sh 'hostname; python3 --version; git --version; docker --version; ansible --version; ansible-galaxy collection list community.docker'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
- name: Deploy a selected immutable pricing release
|
||||
hosts: delivery
|
||||
become: true
|
||||
vars:
|
||||
project_dir: "/opt/startup/pricing-{{ target_env }}"
|
||||
tasks:
|
||||
- name: Validate release selection
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- target_env in ['staging', 'production']
|
||||
- "'@sha256:' in release_image"
|
||||
- expected_version in ['v1', 'v2']
|
||||
- expected_total | int > 0
|
||||
- public_url.startswith('https://')
|
||||
- proxy_network | length > 0
|
||||
- name: Create deployment directory
|
||||
ansible.builtin.file:
|
||||
path: "{{ project_dir }}"
|
||||
state: directory
|
||||
mode: '0750'
|
||||
- name: Render selected Compose configuration
|
||||
ansible.builtin.template:
|
||||
src: compose.yaml.j2
|
||||
dest: "{{ project_dir }}/compose.yaml"
|
||||
mode: '0640'
|
||||
- name: Converge application without rebuilding
|
||||
community.docker.docker_compose_v2:
|
||||
project_src: "{{ project_dir }}"
|
||||
project_name: "pricing-{{ target_env }}"
|
||||
state: present
|
||||
build: never
|
||||
pull: missing
|
||||
wait: true
|
||||
wait_timeout: 90
|
||||
- name: Verify health through public TLS endpoint
|
||||
ansible.builtin.uri:
|
||||
url: "{{ public_url }}/health"
|
||||
return_content: true
|
||||
validate_certs: true
|
||||
register: health
|
||||
until: health.status == 200 and health.json.status == 'ok'
|
||||
retries: 12
|
||||
delay: 5
|
||||
changed_when: false
|
||||
- name: Read release identity
|
||||
ansible.builtin.uri:
|
||||
url: "{{ public_url }}/"
|
||||
return_content: true
|
||||
register: identity
|
||||
changed_when: false
|
||||
- name: Exercise business behavior
|
||||
ansible.builtin.uri:
|
||||
url: "{{ public_url }}/price?quantity=3"
|
||||
return_content: true
|
||||
register: price
|
||||
changed_when: false
|
||||
- name: Check release identity and calculation
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- identity.json.version == expected_version
|
||||
- identity.json.commit == expected_commit
|
||||
- price.json.total | int == expected_total | int
|
||||
@@ -0,0 +1,3 @@
|
||||
[delivery]
|
||||
# Replace address and user; verify the SSH host key before first use.
|
||||
startup ansible_host=REPLACE_DROPLET_ADDRESS ansible_user=deploy
|
||||
@@ -0,0 +1,8 @@
|
||||
# Copy to a release-specific file and replace EVERY placeholder.
|
||||
target_env: staging
|
||||
release_image: gitea.example.edu/team/pricing@sha256:REPLACE_DIGEST
|
||||
expected_version: v1
|
||||
expected_commit: REPLACE_FULL_GIT_COMMIT
|
||||
expected_total: 30
|
||||
public_url: https://staging.example.edu
|
||||
proxy_network: REPLACE_EXISTING_PROXY_NETWORK
|
||||
@@ -0,0 +1,3 @@
|
||||
collections:
|
||||
- name: community.docker
|
||||
version: ">=4.8.0,<6.0.0"
|
||||
@@ -0,0 +1,19 @@
|
||||
services:
|
||||
app:
|
||||
image: "{{ release_image }}"
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
networks:
|
||||
edge:
|
||||
aliases:
|
||||
- "pricing-{{ target_env }}"
|
||||
networks:
|
||||
edge:
|
||||
external: true
|
||||
name: "{{ proxy_network }}"
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
scanner="a8-secret-${BUILD_NUMBER}"
|
||||
trap 'docker rm -f "$scanner" >/dev/null 2>&1 || true; rm -f secret-report.json' EXIT
|
||||
docker create --name "$scanner" aquasec/trivy@sha256:1c78ed1ef824ab8bb05b04359d186e4c1229d0b3e67005faacb54a7d71974f73 fs --quiet --scanners secret --exit-code 1 --format json /v1 >/dev/null
|
||||
tar -C secure-delivery --exclude=v1/.test-venv --exclude=v1/__pycache__ -cf - v1 | docker cp - "$scanner":/
|
||||
set +e
|
||||
docker start -a "$scanner" > secret-report.json
|
||||
result=$?
|
||||
set -e
|
||||
python3 -c 'import json; p=json.load(open("secret-report.json")); print("Secret findings:",sum(len(r.get("Secrets",[])) for r in p.get("Results",[])))'
|
||||
echo "Secret scanner exit status: $result"
|
||||
exit "$result"
|
||||
@@ -0,0 +1,4 @@
|
||||
__pycache__
|
||||
.venv
|
||||
.git
|
||||
*.pyc
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM python:3.13-alpine@sha256:7984cf56ceaddebe4fefeb75d64000b9f45d8b77b11a09b24524da6cdc3af0c8
|
||||
ARG APP_COMMIT=development
|
||||
ENV APP_COMMIT=$APP_COMMIT PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
RUN python -m pip uninstall -y pip && rm -rf /usr/local/lib/python3.13/ensurepip/_bundled
|
||||
COPY app.py .
|
||||
USER 10001:10001
|
||||
EXPOSE 8000
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2)"
|
||||
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "1", "--worker-tmp-dir", "/tmp", "app:app"]
|
||||
@@ -0,0 +1,33 @@
|
||||
import os
|
||||
from flask import Flask, jsonify, request
|
||||
|
||||
app = Flask(__name__)
|
||||
VERSION = "v1"
|
||||
UNIT_PRICE = 10
|
||||
COMMIT = os.environ.get("APP_COMMIT", "development")
|
||||
|
||||
|
||||
def total_price(quantity):
|
||||
if quantity < 1 or quantity > 1000:
|
||||
raise ValueError("quantity must be between 1 and 1000")
|
||||
return UNIT_PRICE * quantity
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index():
|
||||
return jsonify(service="Startup Pricing", version=VERSION, commit=COMMIT)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return jsonify(status="ok", version=VERSION)
|
||||
|
||||
|
||||
@app.get("/price")
|
||||
def price():
|
||||
try:
|
||||
quantity = int(request.args.get("quantity", "1"))
|
||||
total = total_price(quantity)
|
||||
except ValueError as error:
|
||||
return jsonify(error=str(error)), 400
|
||||
return jsonify(quantity=quantity, total=total, currency="USD")
|
||||
@@ -0,0 +1,9 @@
|
||||
blinker==1.9.0
|
||||
click==8.5.0
|
||||
Flask==3.1.3
|
||||
gunicorn==23.0.0
|
||||
itsdangerous==2.2.0
|
||||
Jinja2==3.1.6
|
||||
MarkupSafe==3.0.4
|
||||
packaging==26.3
|
||||
Werkzeug==3.1.9
|
||||
@@ -0,0 +1,25 @@
|
||||
import unittest
|
||||
from app import app, total_price
|
||||
|
||||
|
||||
class PricingTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = app.test_client()
|
||||
|
||||
def test_price(self):
|
||||
self.assertEqual(total_price(3), 30)
|
||||
response = self.client.get("/price?quantity=3")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json["total"], 30)
|
||||
|
||||
def test_invalid_quantity(self):
|
||||
for value in ["0", "-1", "1001", "abc", "1.5"]:
|
||||
self.assertEqual(self.client.get("/price?quantity=" + value).status_code, 400)
|
||||
|
||||
def test_release_identity(self):
|
||||
self.assertEqual(self.client.get("/").json["version"], "v1")
|
||||
self.assertEqual(self.client.get("/health").json["status"], "ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user