Skip to content

Save my work - #4

Open
Ahmed2003-Rav wants to merge 2 commits into
mainfrom
Ahmed
Open

Ahmed2003-Rav wants to merge 2 commits into
mainfrom
Ahmed

Conversation

@Ahmed2003-Rav

@Ahmed2003-Rav Ahmed2003-Rav commented May 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Added observability capabilities including metrics collection and structured logging
    • Added Swagger API documentation interface
    • Added health check and readiness endpoints
  • Chores

    • Added Docker containerization support
    • Added Kubernetes deployment configuration with Helm
    • Configured CI/CD pipeline with automated testing, building, and deployment
    • Enhanced build and deployment tooling with distributed services support
  • Tests

    • Added integration and unit test coverage for API endpoints and application initialization

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 17, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds a complete production-ready distributed services infrastructure to the repository. It includes observability instrumentation (OpenTelemetry, Prometheus, Winston), containerization (Dockerfile, docker-compose with Kafka), Kubernetes deployment via Helm charts, GitHub Actions CI/CD automation, and comprehensive test coverage spanning unit and integration endpoints.

Changes

Distributed Services Infrastructure

Layer / File(s) Summary
Root configuration and npm dependencies
.gitignore, distributed-services/.env.example, distributed-services/.gitignore, distributed-services/package.json
Root .gitignore updated with Yarn patterns; distributed-services initialized with environment config reference, and dependencies added for observability (OpenTelemetry, Prometheus, Winston, Swagger) and development tooling (Jest, ESLint, Supertest).
Application observability and API documentation
distributed-services/src/utils/logger.js, distributed-services/src/tracer.js, distributed-services/src/index.js, distributed-services/src/app.js
Winston logger and OpenTelemetry tracing configured; Express app instrumented with Prometheus metrics (/metrics endpoint), Swagger UI documentation (/docs), request duration histograms/counters, and structured error logging via logger instead of console.
Local development and containerization
distributed-services/Dockerfile, distributed-services/docker-compose.yml, distributed-services/ecosystem.config.js, distributed-services/prometheus.yml
Dockerfile and docker-compose provision containerized Node.js service with Zookeeper/Kafka for local distributed development; PM2 ecosystem defines cluster mode with 2 instances; Prometheus scrapes /metrics endpoint locally.
Helm chart values and configuration
distributed-services/helm/chart/Chart.yaml, distributed-services/helm/chart/values.yaml, distributed-services/helm/chart/templates/_helpers.tpl, distributed-services/helm/chart/templates/configmap.yaml
Helm chart metadata and default values established; helper templates compute chart name/fullname with override support; ConfigMap template injects environment variables into pods.
Kubernetes resource templates
distributed-services/helm/chart/templates/deployment.yaml, distributed-services/helm/chart/templates/service.yaml, distributed-services/helm/chart/templates/ingress.yaml
Deployment provisions 2 replicas with health probes, resource limits, and ConfigMap-sourced env vars; Service exposes on ClusterIP port 80; Ingress routes external HTTP traffic with NGINX rewrite rules.
GitHub Actions CI/CD pipeline
distributed-services/.github/workflows/ci-cd.yml
Multi-stage workflow: lint/build/test on all pushes and PRs; Docker image build/push to DockerHub on main; Helm chart deployment to cse474-prod namespace on main with kubeconfig from secrets.
Test suites
distributed-services/tests/unit/app.test.js, distributed-services/tests/integration/api.test.js
Unit tests verify app initialization, route presence, and middleware stack; integration tests validate /health, /ready, /metrics, and /docs endpoints with expected responses.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Express
  participant Metrics as prom-client<br/>Registry
  participant Logger as Winston
  participant Tracer as OpenTelemetry
  Client->>Express: HTTP request
  Express->>Tracer: auto-instrumented span
  Express->>Metrics: observe request duration<br/>(histogram)
  Express->>Metrics: increment request counter
  Express->>Logger: log success or error
  Express->>Client: HTTP response
  Note over Metrics: GET /metrics returns Prometheus text
Loading
flowchart LR
  trigger["Trigger: Push/<br/>PR to main"] --> lint["Job: Lint,<br/>Build, Test"]
  lint --> docker["Job: Build &amp;<br/>Push Docker<br/>(main only)"]
  docker --> deploy["Job: Helm Deploy<br/>to K8s<br/>(main only)"]
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 A distributed warren now springs to life,
With Prometheus metrics and OpenTelemetry light,
Docker and Helm charts chart the deployment flight,
From local Kafka kafka-nets to K8s heights—
Observability glows through each metric and log, quite a sight! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The pull request title 'Save my work' is vague and generic, failing to convey any meaningful information about the extensive changes made to the codebase. Replace the title with a descriptive summary of the main changes, such as 'Add distributed services infrastructure with Kubernetes, Docker, and observability stack' or similar to reflect the scope of the changeset.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch Ahmed

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Ahmed2003-Rav

Copy link
Copy Markdown
Collaborator Author

@copilot resolve the merge conflicts in this pull request

@Ahmed2003-Rav

Copy link
Copy Markdown
Collaborator Author

@copilot resolve the merge conflicts in this pull request

Co-authored-by: Ahmed2003-Rav <196548487+Ahmed2003-Rav@users.noreply.github.com>

Copilot AI commented May 17, 2026 •

Copy link
Copy Markdown

@copilot resolve the merge conflicts in this pull request

Resolved in commit a60d24d. I merged origin/main into this branch, fixed the conflicts (including .gitignore), and completed the merge commit so the PR is now conflict-free.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • registry.npmmirror.com
    • Triggering command: /usr/local/bin/node node /usr/local/bin/npm ci (dns block)
    • Triggering command: /usr/local/bin/node node /usr/local/bin/npm install (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Copilot AI commented May 17, 2026

Copy link
Copy Markdown

@copilot resolve the merge conflicts in this pull request

The merge conflicts were already resolved in commit a60d24d from my previous response. The branch is currently up-to-date with origin/main with no conflicts. You may need to refresh your GitHub page to see the updated state.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🧹 Nitpick comments (1)
distributed-services/docker-compose.yml (1)

16-17: ⚡ Quick win

Gate dependent services on readiness, not just startup order.

The depends_on declarations at lines 16–17 (kafka), 38–39 (replication-worker), and 51–52 (rebalance-service) only control container start sequencing; they do not guarantee that services are healthy and ready to accept connections. This can cause race conditions where dependent services attempt to connect before Kafka or Zookeeper are fully initialized.

Recommended solution

Add healthchecks to Zookeeper and Kafka, and convert depends_on to the object syntax with condition: service_healthy:

   zookeeper:
     image: confluentinc/cp-zookeeper:latest
+    healthcheck:
+      test: ["CMD", "sh", "-c", "echo ruok | nc localhost 2181 | grep imok"]
+      interval: 10s
+      timeout: 5s
+      retries: 10

   kafka:
     image: confluentinc/cp-kafka:latest
     depends_on:
-      - zookeeper
+      zookeeper:
+        condition: service_healthy
+    healthcheck:
+      test: ["CMD", "bash", "-c", "kafka-topics --bootstrap-server localhost:9092 --list >/dev/null 2>&1"]
+      interval: 10s
+      timeout: 10s
+      retries: 10

   replication-worker:
     depends_on:
-      - kafka
+      kafka:
+        condition: service_healthy

   rebalance-service:
     depends_on:
-      - kafka
+      kafka:
+        condition: service_healthy
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/docker-compose.yml` around lines 16 - 17, The compose
file uses simple depends_on entries (e.g., for kafka, replication-worker,
rebalance-service) which only enforce start order, not readiness; add
healthchecks to the zookeeper and kafka service definitions and change the
depends_on entries to the object form with condition: service_healthy so
dependent services (replication-worker, rebalance-service, kafka) wait for
Zookeeper/Kafka to be healthy before starting; update the zookeeper and kafka
service blocks to include an appropriate healthcheck command, interval, timeout
and retries, and change depends_on for kafka, replication-worker and
rebalance-service to reference those services with condition: service_healthy.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@distributed-services/.github/workflows/ci-cd.yml`:
- Around line 21-22: The CI job "lint-build-test" assumes repository-root paths;
set a working-directory: distributed-services (as a default for that job) so
steps like the "Install dependencies" step that runs npm ci execute in the
correct folder, and update the Docker build step (the step that uses context "."
and Dockerfile) to use distributed-services/ as the build context and point to
distributed-services/Dockerfile, and update the Helm deploy step (the step
referencing ./helm/chart) to use distributed-services/helm/chart; these changes
ensure npm, Docker build, and Helm chart paths resolve correctly when the
workflow file sits in the distributed-services directory.

In `@distributed-services/docker-compose.yml`:
- Line 5: The docker-compose uses floating image tags which is
non-reproducible—replace the two occurrences of "image:
confluentinc/cp-zookeeper:latest" and "image: confluentinc/cp-kafka:latest" with
specific, tested Confluent versions (e.g., a pinned tag like 7.x.y or 8.x.y) to
ensure reproducible builds; update both image lines to the same chosen stable
tag and, if present, align any configuration (ports/compatibility/env vars) that
depend on that Confluent release.

In `@distributed-services/Dockerfile`:
- Around line 1-17: The container runs the app as root; create and use a
non-root user: add a RUN line to create a user/group (e.g., addgroup -S app &&
adduser -S app -G app), ensure the app directory ownership is set (chown -R
app:app /app or use COPY --chown=app:app for copied files), and switch to that
user before CMD using USER app so npm start runs without root privileges; keep
WORKDIR /app and the existing RUN npm install but run npm install as the
non-root user or adjust ownership accordingly.

In `@distributed-services/helm/chart/templates/ingress.yaml`:
- Around line 6-13: Remove the nginx.ingress.kubernetes.io/rewrite-target
annotation so incoming request paths are not rewritten to /. Specifically,
delete the annotations entry for nginx.ingress.kubernetes.io/rewrite-target and
leave the spec.rules -> paths -> path: / with pathType: Prefix intact (so path
matching like /health and /ready is preserved); only reintroduce the
rewrite-target if you intentionally need to rewrite matched paths to /.

In `@distributed-services/helm/chart/values.yaml`:
- Around line 4-6: Replace the placeholder image repository and the floating
"latest" tag in the Helm values by setting a real, immutable image reference:
update the repository field (currently
"ghcr.io/yourusername/distributed-services") to your actual image
registry/organization and set the tag field (currently "latest") to a specific
immutable version (e.g., a semver or build SHA). Ensure pullPolicy remains
appropriate (IfNotPresent or Always depending on tag strategy) and update any
CI/CD that publishes the image to match the chosen repository and tag naming
convention.

In `@distributed-services/package.json`:
- Around line 17-21: Add the missing OpenTelemetry auto-instrumentation package
to dependencies so the import in distributed-services/src/tracer.js resolves at
runtime: update package.json to include
"`@opentelemetry/auto-instrumentations-node`" with a compatible version (e.g.
"^0.48.0" to match "`@opentelemetry/sdk-node`"), then run your package manager to
install the new dependency so the import in tracer.js succeeds.

In `@distributed-services/prometheus.yml`:
- Line 9: Prometheus scrape target is wrong: replace the single target
"localhost:3000" in the scrape config (the line with - targets:
['localhost:3000']) with the actual service instance addresses used by this
stack (e.g. include ['host.docker.internal:3021','host.docker.internal:3022']
for a containerized Prometheus or the service DNS names/port 3021 and 3022 if
running in Kubernetes), or switch to Kubernetes service discovery in the
scrape_config if appropriate; update the targets list accordingly so Prometheus
scrapes the actual app instances on ports 3021 and 3022 instead of
localhost:3000.

In `@distributed-services/src/app.js`:
- Around line 40-43: The async route handler for app.get('/metrics') can produce
unhandled promise rejections in Express 4.x; update the handler signature to
(req, res, next) and wrap the await register.metrics() call in a try/catch,
calling next(err) on error so the error middleware receives failures; ensure you
still set Content-Type and res.end on success and reference the existing
register and app symbols (the '/metrics' route) when making the change.

In `@distributed-services/src/tracer.js`:
- Around line 16-20: The SIGTERM handler in process.on('SIGTERM') calls
sdk.shutdown().finally(() => process.exit(0)) which force-exits the process and
prevents the app's graceful shutdown in src/index.js; refactor by removing the
hard process.exit call, export a new shutdownTracer() function that performs and
returns sdk.shutdown() (including its then/catch logging) and delete the SIGTERM
handler here, then call shutdownTracer() from src/index.js as part of the
existing graceful shutdown flow so tracer shutdown is awaited without forcing
process termination.

In `@distributed-services/tests/unit/app.test.js`:
- Around line 8-22: Tests in app.test.js are asserting against the private
Express internals (app._router.stack) in the "should have a metrics endpoint",
"should have a docs endpoint" and "should handle JSON body parsing" tests;
replace those fragile checks with integration-style HTTP requests using the same
pattern as api.test.js (use request(app) from supertest): make GET requests to
'/metrics' and '/docs' and assert expected status codes (e.g., 200), and for
JSON parsing make a POST to a real endpoint on the app (or a lightweight
test-only route) with .send({ ... }) and assert it does not return a 400 and
parses the body correctly; ensure tests are async and import/use request(app)
rather than inspecting app._router.stack or other private properties.
- Around line 24-28: The current test only looks for any '<anonymous>'
middleware; instead, update the test to (1) locate the jsonParser layer in
app._router.stack and assert the next layer is the request ID middleware by
comparing its layer.handle or layer.name to your requestId middleware function
(e.g., requestIdMiddleware) to verify ordering, and (2) add an integration
assertion that the middleware actually sets a request ID by making a request
against the app (e.g., await request(app).get('/health')) and asserting
response.headers['x-request-id'] is defined and is a string to verify
functionality.

---

Nitpick comments:
In `@distributed-services/docker-compose.yml`:
- Around line 16-17: The compose file uses simple depends_on entries (e.g., for
kafka, replication-worker, rebalance-service) which only enforce start order,
not readiness; add healthchecks to the zookeeper and kafka service definitions
and change the depends_on entries to the object form with condition:
service_healthy so dependent services (replication-worker, rebalance-service,
kafka) wait for Zookeeper/Kafka to be healthy before starting; update the
zookeeper and kafka service blocks to include an appropriate healthcheck
command, interval, timeout and retries, and change depends_on for kafka,
replication-worker and rebalance-service to reference those services with
condition: service_healthy.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 568967ec-a6fb-41cd-a148-56fb75219497

📥 Commits

Reviewing files that changed from the base of the PR and between 562b30e and a60d24d.

⛔ Files ignored due to path filters (1)
  • distributed-services/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (22)
  • .gitignore
  • distributed-services/.env.example
  • distributed-services/.github/workflows/ci-cd.yml
  • distributed-services/.gitignore
  • distributed-services/Dockerfile
  • distributed-services/docker-compose.yml
  • distributed-services/ecosystem.config.js
  • distributed-services/helm/chart/Chart.yaml
  • distributed-services/helm/chart/templates/_helpers.tpl
  • distributed-services/helm/chart/templates/configmap.yaml
  • distributed-services/helm/chart/templates/deployment.yaml
  • distributed-services/helm/chart/templates/ingress.yaml
  • distributed-services/helm/chart/templates/service.yaml
  • distributed-services/helm/chart/values.yaml
  • distributed-services/package.json
  • distributed-services/prometheus.yml
  • distributed-services/src/app.js
  • distributed-services/src/index.js
  • distributed-services/src/tracer.js
  • distributed-services/src/utils/logger.js
  • distributed-services/tests/integration/api.test.js
  • distributed-services/tests/unit/app.test.js

Comment on lines +21 to +22
- name: Install dependencies
run: npm ci

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify service assets are under distributed-services and not root.
set -euo pipefail

echo "== package manifests =="
fd -HI '^package\.json$' .

echo "== Dockerfiles =="
fd -HI '^Dockerfile$' .

echo "== Helm charts =="
fd -HI '^Chart\.yaml$' .

echo "== workflow references =="
rg -n 'npm ci|context:|helm upgrade --install|working-directory' distributed-services/.github/workflows/ci-cd.yml

Repository: BasantAwad/File-Storage-platform

Length of output: 1175


🏁 Script executed:

cat -n distributed-services/.github/workflows/ci-cd.yml | head -100

Repository: BasantAwad/File-Storage-platform

Length of output: 2325


🏁 Script executed:

# Check for root-level package.json
ls -la package.json 2>/dev/null || echo "No root package.json found"

Repository: BasantAwad/File-Storage-platform

Length of output: 103


Fix repository-root path assumptions in CI/CD jobs.

The workflow is located in distributed-services/.github/workflows/ci-cd.yml but references root-level paths that don't exist or are incorrect:

  • Line 22: npm ci has no working directory context and will fail (no root package.json exists; only distributed-services/package.json)
  • Line 50: Docker build context is . but Dockerfile is at distributed-services/Dockerfile
  • Line 74: Helm deploy references ./helm/chart but the service chart is at ./distributed-services/helm/chart

Add a working-directory: distributed-services default to the lint-build-test job, and update Docker and Helm paths to use explicit distributed-services/ prefixes.

Suggested fix
 jobs:
   lint-build-test:
     runs-on: ubuntu-latest
+    defaults:
+      run:
+        working-directory: distributed-services
     steps:
@@
       - name: Install dependencies
         run: npm ci
@@
   docker-build-push:
@@
       - name: Build and push Docker image
         uses: docker/build-push-action@v4
         with:
-          context: .
+          context: ./distributed-services
+          file: ./distributed-services/Dockerfile
           push: true
           tags: ${{ secrets.DOCKER_USERNAME }}/distributed-services:latest
@@
   deploy:
@@
       - name: Deploy to Kubernetes
-        run: helm upgrade --install cse474 ./helm/chart --namespace cse474-prod --create-namespace
+        run: helm upgrade --install cse474 ./distributed-services/helm/chart --namespace cse474-prod --create-namespace
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/.github/workflows/ci-cd.yml` around lines 21 - 22, The
CI job "lint-build-test" assumes repository-root paths; set a working-directory:
distributed-services (as a default for that job) so steps like the "Install
dependencies" step that runs npm ci execute in the correct folder, and update
the Docker build step (the step that uses context "." and Dockerfile) to use
distributed-services/ as the build context and point to
distributed-services/Dockerfile, and update the Helm deploy step (the step
referencing ./helm/chart) to use distributed-services/helm/chart; these changes
ensure npm, Docker build, and Helm chart paths resolve correctly when the
workflow file sits in the distributed-services directory.


services:
zookeeper:
image: confluentinc/cp-zookeeper:latest

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify floating image tags in compose config
rg -n '^\s*image:\s*[^[:space:]]+:latest\s*$' distributed-services/docker-compose.yml

Repository: BasantAwad/File-Storage-platform

Length of output: 165


🏁 Script executed:

cat -n distributed-services/docker-compose.yml

Repository: BasantAwad/File-Storage-platform

Length of output: 1741


🌐 Web query:

Confluent Kafka Zookeeper 7.6.1 release version stable

💡 Result:

Confluent Platform 7.6.1 is a stable patch release that includes ZooKeeper version 3.8.3 [1][2]. While ZooKeeper remains a functional component in version 7.6.1, it is considered deprecated for new deployments in favor of KRaft (Kafka Raft metadata mode) [3]. Key points regarding ZooKeeper in Confluent Platform 7.6.1: - Stability and Support: ZooKeeper 3.8.3 is the version bundled with Confluent Platform 7.6.x [1][2]. It is stable and supported within this release series [2]. - Migration: Confluent Platform 7.6.1 introduced general availability for ZooKeeper to KRaft migrations for existing clusters [1]. - Future Outlook: ZooKeeper is being phased out of the Confluent Platform. It is no longer included starting with Confluent Platform 8.0 [4][5]. Confluent provides a defined support lifecycle for ZooKeeper deployments based on subscription tiers following the release of the final version that includes it (7.9.x) [5]. For production environments, Confluent recommends transitioning to KRaft mode [3]. If you are currently using ZooKeeper, you should plan your migration to KRaft to align with the platform's long-term roadmap [4][5].

Citations:


Pin Kafka/Zookeeper image versions instead of latest.

Lines 5 and 15 use floating tags, making this stack non-reproducible and vulnerable to unexpected upstream changes. Pin to a specific stable version:

Suggested fix
-    image: confluentinc/cp-zookeeper:latest
+    image: confluentinc/cp-zookeeper:7.6.1
...
-    image: confluentinc/cp-kafka:latest
+    image: confluentinc/cp-kafka:7.6.1
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/docker-compose.yml` at line 5, The docker-compose uses
floating image tags which is non-reproducible—replace the two occurrences of
"image: confluentinc/cp-zookeeper:latest" and "image:
confluentinc/cp-kafka:latest" with specific, tested Confluent versions (e.g., a
pinned tag like 7.x.y or 8.x.y) to ensure reproducible builds; update both image
lines to the same chosen stable tag and, if present, align any configuration
(ports/compatibility/env vars) that depend on that Confluent release.

Comment on lines +1 to +17
FROM node:20-alpine

# Set working directory
WORKDIR /app

# Copy package files and install dependencies
COPY package*.json ./
RUN npm install

# Copy application source code
COPY . .

# Expose ports that might be used by the services
EXPOSE 3021 3022

# Start the application using npm start
CMD ["npm", "start"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Drop root privileges for the runtime process.

Line 1 through Line 17 never switches users, so the app runs as root inside the container. That unnecessarily increases blast radius for any app-level compromise.

🔧 Suggested fix
 FROM node:20-alpine

 # Set working directory
 WORKDIR /app

 # Copy package files and install dependencies
-COPY package*.json ./
+COPY --chown=node:node package*.json ./
 RUN npm install

 # Copy application source code
-COPY . .
+COPY --chown=node:node . .
+
+# Run as non-root user
+USER node

 # Expose ports that might be used by the services
 EXPOSE 3021 3022
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
FROM node:20-alpine
# Set working directory
WORKDIR /app
# Copy package files and install dependencies
COPY package*.json ./
RUN npm install
# Copy application source code
COPY . .
# Expose ports that might be used by the services
EXPOSE 3021 3022
# Start the application using npm start
CMD ["npm", "start"]
FROM node:20-alpine
# Set working directory
WORKDIR /app
# Copy package files and install dependencies
COPY --chown=node:node package*.json ./
RUN npm install
# Copy application source code
COPY --chown=node:node . .
# Run as non-root user
USER node
# Expose ports that might be used by the services
EXPOSE 3021 3022
# Start the application using npm start
CMD ["npm", "start"]
🧰 Tools
🪛 Trivy (0.69.3)

[error] 1-1: Image user should not be 'root'

Specify at least 1 USER command in Dockerfile with non-root user as argument

Rule: DS-0002

Learn more

(IaC/Dockerfile)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/Dockerfile` around lines 1 - 17, The container runs the
app as root; create and use a non-root user: add a RUN line to create a
user/group (e.g., addgroup -S app && adduser -S app -G app), ensure the app
directory ownership is set (chown -R app:app /app or use COPY --chown=app:app
for copied files), and switch to that user before CMD using USER app so npm
start runs without root privileges; keep WORKDIR /app and the existing RUN npm
install but run npm install as the non-root user or adjust ownership
accordingly.

Comment on lines +6 to +13
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- http:
paths:
- path: /
pathType: Prefix

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

For NGINX Ingress Controller, what is the effect of using annotation nginx.ingress.kubernetes.io/rewrite-target: /withpath: /andpathType: Prefix? Does it rewrite all incoming paths to root?

💡 Result:

When you use the annotation nginx.ingress.kubernetes.io/rewrite-target: / in conjunction with path: / and pathType: Prefix, the NGINX Ingress Controller will rewrite all incoming request paths to the root path (/) before forwarding them to the backend service [1][2]. The effect is that every request, regardless of the original path (e.g., /api/users, /images/logo.png, or /about), will be transformed into a request for / when it reaches your application [1][2]. Key technical implications include: 1. Path Normalization: Because the rewrite target is explicitly set to /, the controller discards the original request URI and replaces it with / [1]. 2. Implicit Regex Conversion: The use of the rewrite-target annotation automatically enables regular expression matching for the Ingress rules, even if you do not explicitly set nginx.ingress.kubernetes.io/use-regex: "true" [3][2]. This can have side effects on how other paths are matched within the same host, potentially causing unexpected behavior or routing conflicts [4][2]. 3. Loss of Path Information: Since the entire path is rewritten to /, your backend application will lose the context of the original requested path [1]. If your application relies on the URL path to determine which resource to serve, this configuration will likely break that functionality unless the application is specifically designed to handle requests only at the root [1]. If your goal is to strip a specific prefix while preserving the remainder of the path, you must use capture groups in your path definition and reference them in the rewrite-target annotation (e.g., path: /api/(.*) and rewrite-target: /$1) [1][5]. Using a static / as the target without capture groups will always result in a total rewrite to the root [1][2].

Citations:


🏁 Script executed:

# First, let's look at the full ingress.yaml file to understand the complete configuration
cat -n distributed-services/helm/chart/templates/ingress.yaml

Repository: BasantAwad/File-Storage-platform

Length of output: 669


🏁 Script executed:

# Let's also check if there are other related configuration files in the chart
fd -e yaml -e yml . distributed-services/helm/chart/templates/ | head -20

Repository: BasantAwad/File-Storage-platform

Length of output: 301


🏁 Script executed:

# Search for any services or documentation that might explain this ingress configuration
find distributed-services/helm/chart -type f \( -name "*.yaml" -o -name "*.yml" -o -name "*.md" \) | xargs grep -l "service\|rewrite" 2>/dev/null || echo "No matches found"

Repository: BasantAwad/File-Storage-platform

Length of output: 273


🏁 Script executed:

# Check the deployment to understand what service is running and if it needs path information
cat -n distributed-services/helm/chart/templates/deployment.yaml | head -50

Repository: BasantAwad/File-Storage-platform

Length of output: 1796


🏁 Script executed:

# Also check the values.yaml to see if there are any clues about the service configuration
cat -n distributed-services/helm/chart/values.yaml

Repository: BasantAwad/File-Storage-platform

Length of output: 568


Remove the unnecessary rewrite-target annotation that collapses all request paths to /.

The path: / with pathType: Prefix already matches all incoming requests. Adding nginx.ingress.kubernetes.io/rewrite-target: / is redundant and will rewrite every request to the root path, breaking any path-specific handling in your backend service (including endpoints like /health and /ready if accessed through the ingress). Remove this annotation unless path rewriting is explicitly required.

Suggested fix
 metadata:
   name: {{ include "cse474.fullname" . }}
   namespace: {{ .Values.namespace }}
-  annotations:
-    nginx.ingress.kubernetes.io/rewrite-target: /
 spec:
   rules:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/helm/chart/templates/ingress.yaml` around lines 6 - 13,
Remove the nginx.ingress.kubernetes.io/rewrite-target annotation so incoming
request paths are not rewritten to /. Specifically, delete the annotations entry
for nginx.ingress.kubernetes.io/rewrite-target and leave the spec.rules -> paths
-> path: / with pathType: Prefix intact (so path matching like /health and
/ready is preserved); only reintroduce the rewrite-target if you intentionally
need to rewrite matched paths to /.

Comment on lines +4 to +6
repository: ghcr.io/yourusername/distributed-services
pullPolicy: IfNotPresent
tag: "latest"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify placeholder repo and floating tag in Helm values
rg -n 'repository:\s*ghcr\.io/yourusername/distributed-services|tag:\s*"latest"' distributed-services/helm/chart/values.yaml

Repository: BasantAwad/File-Storage-platform

Length of output: 152


Replace placeholder repository and floating tag in image configuration.

Lines 4 and 6 contain a placeholder repository (yourusername) and the latest tag, both of which compromise release safety and prevent reproducible deployments and rollbacks.

Suggested fix
 image:
-  repository: ghcr.io/yourusername/distributed-services
+  repository: ghcr.io/<your-org-or-user>/distributed-services
   pullPolicy: IfNotPresent
-  tag: "latest"
+  tag: "1.0.0"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
repository: ghcr.io/yourusername/distributed-services
pullPolicy: IfNotPresent
tag: "latest"
image:
repository: ghcr.io/<your-org-or-user>/distributed-services
pullPolicy: IfNotPresent
tag: "1.0.0"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/helm/chart/values.yaml` around lines 4 - 6, Replace the
placeholder image repository and the floating "latest" tag in the Helm values by
setting a real, immutable image reference: update the repository field
(currently "ghcr.io/yourusername/distributed-services") to your actual image
registry/organization and set the tag field (currently "latest") to a specific
immutable version (e.g., a semver or build SHA). Ensure pullPolicy remains
appropriate (IfNotPresent or Always depending on tag strategy) and update any
CI/CD that publishes the image to match the chosen repository and tag naming
convention.

- job_name: 'distributed-services'
metrics_path: '/metrics'
static_configs:
- targets: ['localhost:3000'] # Update with actual deployed address or k8s discovery

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Prometheus target is misaligned with this deployment setup.

Line 9 points to localhost:3000, but this stack defines service instances on 3021 and 3022. If Prometheus runs in a container, localhost also resolves to Prometheus itself.

🔧 Suggested fix
-      - targets: ['localhost:3000'] # Update with actual deployed address or k8s discovery
+      - targets: ['replication-worker:3021', 'rebalance-service:3022']
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- targets: ['localhost:3000'] # Update with actual deployed address or k8s discovery
- targets: ['replication-worker:3021', 'rebalance-service:3022']
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/prometheus.yml` at line 9, Prometheus scrape target is
wrong: replace the single target "localhost:3000" in the scrape config (the line
with - targets: ['localhost:3000']) with the actual service instance addresses
used by this stack (e.g. include
['host.docker.internal:3021','host.docker.internal:3022'] for a containerized
Prometheus or the service DNS names/port 3021 and 3022 if running in
Kubernetes), or switch to Kubernetes service discovery in the scrape_config if
appropriate; update the targets list accordingly so Prometheus scrapes the
actual app instances on ports 3021 and 3022 instead of localhost:3000.

Comment on lines +40 to +43
app.get('/metrics', async (req, res) => {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

In Express 4.x, are rejected promises from async route handlers automatically forwarded to error middleware, or must errors be passed to next(err)?

💡 Result:

In Express 4.x, rejected promises from async route handlers and middleware are not automatically forwarded to error-handling middleware [1][2]. Express 4 does not natively support or await promises returned by route handlers, meaning any rejection will result in an unhandled promise rejection, which can cause the application to crash or leave the request hanging [3][4]. To handle errors in async route handlers in Express 4.x, you must explicitly pass errors to the next function [1][4]. This is commonly achieved using one of the following patterns: 1. Try/Catch Blocks: Wrap the contents of your async handler in a try/catch block and pass the caught error to next [4]. app.get('/user/:id', async (req, res, next) => { try { const user = await getUserById(req.params.id); res.send(user); } catch (err) { next(err); } }); 2. Async Wrapper Function: Use a higher-order function to wrap your async handlers, which automatically catches rejections and passes them to next [5][6]. const asyncHandler = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; app.get('/user/:id', asyncHandler(async (req, res) => { const user = await getUserById(req.params.id); res.send(user); })); Automatic handling of rejected promises was introduced in Express 5.x [1][2]. If you are using Express 4.x, you must continue to use one of the manual approaches above [1][4].

Citations:


🏁 Script executed:

#!/bin/bash
# Locate and verify the file
find . -name "app.js" -path "*/distributed-services/src/*" 2>/dev/null

# Check if the specific file exists
if [ -f "./distributed-services/src/app.js" ]; then
  echo "=== File exists. Reading lines 40-43 ==="
  sed -n '40,43p' ./distributed-services/src/app.js
  echo ""
  echo "=== Context around lines 40-43 ==="
  sed -n '35,48p' ./distributed-services/src/app.js
fi

# Find package.json to check Express version
echo ""
echo "=== Looking for package.json files ==="
find . -name "package.json" -type f 2>/dev/null | head -20

# Check the main/root package.json for Express version
if [ -f "./package.json" ]; then
  echo ""
  echo "=== Express version from root package.json ==="
  jq '.dependencies.express // .devDependencies.express // "not found"' ./package.json
fi

# Also check in distributed-services directory
if [ -f "./distributed-services/package.json" ]; then
  echo ""
  echo "=== Express version from distributed-services/package.json ==="
  jq '.dependencies.express // .devDependencies.express // "not found"' ./distributed-services/package.json
fi

Repository: BasantAwad/File-Storage-platform

Length of output: 1254


Handle /metrics async errors explicitly for Express 4.x.

In Express 4.19.2, rejected promises from async handlers are not automatically forwarded to error middleware. Wrap the handler with try/catch and call next(err) to ensure errors reach the error middleware instead of causing unhandled rejections.

🔧 Proposed fix
-app.get('/metrics', async (req, res) => {
-  res.set('Content-Type', register.contentType);
-  res.end(await register.metrics());
-});
+app.get('/metrics', async (req, res, next) => {
+  try {
+    res.set('Content-Type', register.contentType);
+    res.end(await register.metrics());
+  } catch (err) {
+    next(err);
+  }
+});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
app.get('/metrics', async (req, res) => {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
});
app.get('/metrics', async (req, res, next) => {
try {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
} catch (err) {
next(err);
}
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/src/app.js` around lines 40 - 43, The async route
handler for app.get('/metrics') can produce unhandled promise rejections in
Express 4.x; update the handler signature to (req, res, next) and wrap the await
register.metrics() call in a try/catch, calling next(err) on error so the error
middleware receives failures; ensure you still set Content-Type and res.end on
success and reference the existing register and app symbols (the '/metrics'
route) when making the change.

Comment on lines +16 to +20
process.on('SIGTERM', () => {
sdk.shutdown()
.then(() => console.log('Tracing terminated'))
.catch((error) => console.log('Error terminating tracing', error))
.finally(() => process.exit(0));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Signal handlers in source:"
rg -n -C2 "process\\.on\\('SIG(INT|TERM)'" distributed-services/src

Repository: BasantAwad/File-Storage-platform

Length of output: 757


🏁 Script executed:

cat -n distributed-services/src/tracer.js

Repository: BasantAwad/File-Storage-platform

Length of output: 876


🏁 Script executed:

cat -n distributed-services/src/index.js

Repository: BasantAwad/File-Storage-platform

Length of output: 733


🏁 Script executed:

rg -n "require.*tracer|shutdownTracer|SIGTERM|SIGINT" distributed-services/src --type js

Repository: BasantAwad/File-Storage-platform

Length of output: 378


🏁 Script executed:

fd -type f -name "*.js" distributed-services/src | xargs wc -l | tail -1

Repository: BasantAwad/File-Storage-platform

Length of output: 267


Avoid hard process exit from the tracer SIGTERM hook.

Calling process.exit(0) here immediately terminates the process, preventing the graceful server shutdown in src/index.js from running. In containerized environments (Docker, Kubernetes, PM2), SIGTERM is the standard shutdown signal, so this handler fires before in-flight requests can complete.

Export shutdownTracer() as a callable function and let src/index.js orchestrate the shutdown sequence by calling it as part of its graceful server close flow.

🔧 Refactor direction
- process.on('SIGTERM', () => {
-   sdk.shutdown()
-     .then(() => console.log('Tracing terminated'))
-     .catch((error) => console.log('Error terminating tracing', error))
-     .finally(() => process.exit(0));
- });
+async function shutdownTracer() {
+  try {
+    await sdk.shutdown();
+    console.log('Tracing terminated');
+  } catch (error) {
+    console.log('Error terminating tracing', error);
+  }
+}
+
+module.exports = { shutdownTracer };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/src/tracer.js` around lines 16 - 20, The SIGTERM handler
in process.on('SIGTERM') calls sdk.shutdown().finally(() => process.exit(0))
which force-exits the process and prevents the app's graceful shutdown in
src/index.js; refactor by removing the hard process.exit call, export a new
shutdownTracer() function that performs and returns sdk.shutdown() (including
its then/catch logging) and delete the SIGTERM handler here, then call
shutdownTracer() from src/index.js as part of the existing graceful shutdown
flow so tracer shutdown is awaited without forcing process termination.

Comment on lines +8 to +22
it('should have a metrics endpoint', () => {
const route = app._router.stack.find(s => s.route && s.route.path === '/metrics');
expect(route).toBeDefined();
expect(route.route.methods.get).toBeTruthy();
});

it('should have a docs endpoint', () => {
const route = app._router.stack.find(s => s.regexp && s.regexp.source.includes('^\\/docs\\/?(?=\\/|$)'));
expect(route).toBeDefined();
});

it('should handle JSON body parsing', () => {
const jsonParser = app._router.stack.find(s => s.name === 'jsonParser');
expect(jsonParser).toBeDefined();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Avoid testing private Express internals; prefer integration tests.

These tests access the private app._router.stack property to verify routes and middleware. This approach is fragile and can break across Express versions, as the internal router structure is not part of Express's public API.

Instead, verify this behavior through integration tests that exercise the actual HTTP endpoints (similar to api.test.js), which test the public contract and are more resilient to internal implementation changes.

🔄 Recommended approach: integration tests

Replace these internal checks with HTTP requests that verify actual behavior:

// Instead of checking app._router.stack for /metrics route:
const response = await request(app).get('/metrics');
expect(response.status).toBe(200);

// Instead of checking app._router.stack for /docs route:
const docsResponse = await request(app).get('/docs');
expect(docsResponse.status).toBe(200);

// For JSON parsing, verify the app accepts JSON payloads:
const jsonResponse = await request(app)
  .post('/some-endpoint')
  .send({ test: 'data' });
expect(jsonResponse.status).not.toBe(400); // Should parse successfully
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/tests/unit/app.test.js` around lines 8 - 22, Tests in
app.test.js are asserting against the private Express internals
(app._router.stack) in the "should have a metrics endpoint", "should have a docs
endpoint" and "should handle JSON body parsing" tests; replace those fragile
checks with integration-style HTTP requests using the same pattern as
api.test.js (use request(app) from supertest): make GET requests to '/metrics'
and '/docs' and assert expected status codes (e.g., 200), and for JSON parsing
make a POST to a real endpoint on the app (or a lightweight test-only route)
with .send({ ... }) and assert it does not return a 400 and parses the body
correctly; ensure tests are async and import/use request(app) rather than
inspecting app._router.stack or other private properties.

Comment on lines +24 to +28
it('should handle request ID middleware', () => {
// Check if there is an anonymous middleware right after jsonParser
const middleware = app._router.stack.find(s => s.name === '<anonymous>');
expect(middleware).toBeDefined();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Test doesn't verify correct middleware or ordering.

This test finds any middleware named <anonymous> but doesn't verify:

  1. It's positioned "right after jsonParser" (as the comment claims)
  2. It's actually the request ID middleware
  3. It performs request ID functionality

The test will pass if any anonymous middleware exists in the stack, making it ineffective.

✅ Suggested fix: verify request ID functionality via integration test

Test that request IDs are actually added to responses:

it('should add request ID to responses', async () => {
  const response = await request(app).get('/health');
  expect(response.headers['x-request-id']).toBeDefined();
  expect(typeof response.headers['x-request-id']).toBe('string');
});

Or verify it appears in logs/trace context, depending on how your request ID middleware is implemented.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@distributed-services/tests/unit/app.test.js` around lines 24 - 28, The
current test only looks for any '<anonymous>' middleware; instead, update the
test to (1) locate the jsonParser layer in app._router.stack and assert the next
layer is the request ID middleware by comparing its layer.handle or layer.name
to your requestId middleware function (e.g., requestIdMiddleware) to verify
ordering, and (2) add an integration assertion that the middleware actually sets
a request ID by making a request against the app (e.g., await
request(app).get('/health')) and asserting response.headers['x-request-id'] is
defined and is a string to verify functionality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants