Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.git
**/.venv
.next
node_modules
frontend/.next
Expand Down
9 changes: 9 additions & 0 deletions .github/workflows/docker-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,23 @@ jobs:
- component: backend
image: ai_email_client-backend
dockerfile: Dockerfile
target: backend-runtime
base_dockerfile: Dockerfile
context: .
build_args: |
BUILDKIT_INLINE_CACHE=1
- component: naruon
image: naruon
dockerfile: Dockerfile
target: combined-runtime
base_dockerfile: Dockerfile
context: .
build_args: |
BUILDKIT_INLINE_CACHE=1
- component: frontend
image: ai_email_client-frontend
dockerfile: frontend/Dockerfile
target: frontend-runtime
base_dockerfile: frontend/Dockerfile
context: .
build_args: |
Expand Down Expand Up @@ -146,8 +149,10 @@ jobs:
with:
context: ${{ matrix.context }}
file: ${{ matrix.dockerfile }}
target: ${{ matrix.target }}
platforms: linux/amd64,linux/arm64
push: false
outputs: type=cacheonly
build-args: |
${{ matrix.build_args }}
OCI_IMAGE_CREATED=${{ steps.oci.outputs.created }}
Expand Down Expand Up @@ -185,20 +190,23 @@ jobs:
- component: backend
image: ai_email_client-backend
dockerfile: Dockerfile
target: backend-runtime
base_dockerfile: Dockerfile
context: .
build_args: |
BUILDKIT_INLINE_CACHE=1
- component: naruon
image: naruon
dockerfile: Dockerfile
target: combined-runtime
base_dockerfile: Dockerfile
context: .
build_args: |
BUILDKIT_INLINE_CACHE=1
- component: frontend
image: ai_email_client-frontend
dockerfile: frontend/Dockerfile
target: frontend-runtime
base_dockerfile: frontend/Dockerfile
context: .
build_args: |
Expand Down Expand Up @@ -327,6 +335,7 @@ jobs:
with:
context: ${{ matrix.context }}
file: ${{ matrix.dockerfile }}
target: ${{ matrix.target }}
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
Expand Down
5 changes: 5 additions & 0 deletions .jules/sentinel.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,8 @@
**Vulnerability:** The `in_reply_to` and `references` fields on the `SendEmailRequest` model lacked explicit validation, opening up an opportunity for header injection by appending `\r\n`.
**Learning:** While the email service internally checks some headers, relying on the API boundary's Pydantic model ensures bad input is stopped early and consistently. Pydantic regex patterns aren't sufficient on their own for all string contexts due to encoding/decoding inconsistencies.
**Prevention:** Always use `@field_validator` with explicit `mode="before"` string matching to reject `chr(10)` and `chr(13)` across all user-controlled email header fields. Use `isinstance(value, str)` before string operations to prevent runtime errors if input is missing or malformed.

## 2026-08-05 - [Prevent Path Traversal via Backslashes in Attachment Parser]
**Vulnerability:** The `_safe_filename` function in `backend/services/attachment_parser.py` used `pathlib.Path().name` to strip directory components from attachment filenames, but failed to normalize backslashes beforehand. This allowed attackers to use Windows-style path separators (e.g., `..\..\upload`) to bypass path validation on POSIX systems.
**Learning:** Checking for traversal sequences using `pathlib.Path().name` may leave the result vulnerable if the input path can contain Windows-style path separators but the program interprets it dynamically or decodes payloads using backslashes, because POSIX `pathlib` treats backslashes as valid filename characters, not separators.
**Prevention:** Always convert backslashes to forward slashes before parsing filenames using `pathlib.Path().name`.
68 changes: 37 additions & 31 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,41 +16,14 @@ COPY VERSION /app/VERSION
COPY backend /app/

RUN groupadd --system --gid 10001 appuser \
&& useradd --system --create-home --home-dir /home/appuser --uid 10001 --gid appuser --shell /usr/sbin/nologin appuser \
&& useradd --system --create-home --home-dir /home/appuser --key SYS_UID_MAX=10001 --uid 10001 --gid appuser --shell /usr/sbin/nologin appuser \
&& chown -R appuser:appuser /app
USER appuser

EXPOSE 8000

CMD ["python", "scripts/start_backend.py", "--host", "0.0.0.0", "--port", "8000"]

# Stage 2: Build Frontend
FROM node:26-slim@sha256:4ebb5ace66f15a24c14c492e01a8beeed4fddf970a856109f5126e703e5fe503 AS frontend-builder
WORKDIR /app
ENV NPM_CONFIG_UPDATE_NOTIFIER=false
ENV PNPM_VERSION=11.5.3
ENV PNPM_INTEGRITY=sha512-esHJGTQcITo03A0Cr7cUPFwmrCbujEeC3uqCG4rGTSE0oIH9iUHa5uKbu0j1jfwrf7zuzMB8svCdIZ00Kklp7Q==
RUN node -e "const crypto=require('node:crypto');const fs=require('node:fs');const https=require('node:https');const url='https://registry.npmjs.org/pnpm/-/pnpm-'+process.env.PNPM_VERSION+'.tgz';https.get(url,(res)=>{if(res.statusCode!==200){throw new Error('pnpm download failed: '+res.statusCode)}const chunks=[];res.on('data',(chunk)=>chunks.push(chunk));res.on('end',()=>{const data=Buffer.concat(chunks);const digest='sha512-'+crypto.createHash('sha512').update(data).digest('base64');if(digest!==process.env.PNPM_INTEGRITY){throw new Error('pnpm integrity mismatch')}fs.writeFileSync('/tmp/pnpm.tgz',data);});}).on('error',(error)=>{throw error;});"
RUN mkdir -p /opt/pnpm \
&& tar -xzf /tmp/pnpm.tgz -C /opt/pnpm --strip-components=1 \
&& chmod +x /opt/pnpm/bin/pnpm.cjs /opt/pnpm/bin/pnpx.cjs \
&& ln -sf /opt/pnpm/bin/pnpm.cjs /usr/local/bin/pnpm \
&& ln -sf /opt/pnpm/bin/pnpx.cjs /usr/local/bin/pnpx \
&& rm /tmp/pnpm.tgz
COPY frontend/package.json frontend/pnpm-lock.yaml frontend/pnpm-workspace.yaml frontend/.pnpmfile.cjs ./
COPY frontend/patches ./patches
RUN pnpm install --frozen-lockfile
COPY frontend ./
ENV NEXT_TELEMETRY_DISABLED=1
ENV POSTCSS_WORKERS=1
ENV DISABLE_POSTCSS_WORKERS=true
RUN pnpm run build

# Stage 3: Combined image (Python + Node.js)
# backend-runtime ends with USER appuser (non-root). Stage 3 inherits that
# non-root context, so no root elevation is needed here.
FROM backend-runtime

ARG OCI_IMAGE_CREATED=""
ARG OCI_IMAGE_AUTHORS="Seongho Bae"
ARG OCI_IMAGE_URL="https://github.com/Seongho-Bae/naruon"
Expand All @@ -61,12 +34,13 @@ ARG OCI_IMAGE_REVISION=""
ARG OCI_IMAGE_VENDOR="Seongho-Bae"
ARG OCI_IMAGE_LICENSES="LicenseRef-Naruon-Proprietary"
ARG OCI_IMAGE_REF_NAME=""
ARG OCI_IMAGE_TITLE="naruon"
ARG OCI_IMAGE_DESCRIPTION="Naruon combined FastAPI and Next.js runtime image"
ARG OCI_IMAGE_TITLE="naruon backend"
ARG OCI_IMAGE_DESCRIPTION="Naruon FastAPI backend runtime image"
ARG OCI_IMAGE_BASE_DIGEST="sha256:a7fb1e634c4a578f9e0bd6327f11a3cde11b7a9395f48e24360c0988bcc5c2bc"
ARG OCI_IMAGE_BASE_NAME="docker.io/library/python:3.14-slim@sha256:a7fb1e634c4a578f9e0bd6327f11a3cde11b7a9395f48e24360c0988bcc5c2bc"

# Defaults keep local builds provenance-complete. The publishing workflow derives
# Defaults identify the base image for local backend and combined builds; they
# do not attest source revision or release provenance. The workflow derives
# and overrides both values from the exact first FROM instruction, while
# repository governance tests prevent the reviewed defaults from drifting.
RUN test -n "$OCI_IMAGE_BASE_DIGEST" && test -n "$OCI_IMAGE_BASE_NAME"
Expand All @@ -86,6 +60,38 @@ LABEL org.opencontainers.image.created="${OCI_IMAGE_CREATED}" \
org.opencontainers.image.base.digest="${OCI_IMAGE_BASE_DIGEST}" \
org.opencontainers.image.base.name="${OCI_IMAGE_BASE_NAME}"

# Stage 2: Build Frontend
FROM node:26-slim@sha256:4ebb5ace66f15a24c14c492e01a8beeed4fddf970a856109f5126e703e5fe503 AS frontend-builder
WORKDIR /app
ENV NPM_CONFIG_UPDATE_NOTIFIER=false
ENV PNPM_VERSION=11.5.3
ENV PNPM_INTEGRITY=sha512-esHJGTQcITo03A0Cr7cUPFwmrCbujEeC3uqCG4rGTSE0oIH9iUHa5uKbu0j1jfwrf7zuzMB8svCdIZ00Kklp7Q==
RUN node -e "const crypto=require('node:crypto');const fs=require('node:fs');const https=require('node:https');const url='https://registry.npmjs.org/pnpm/-/pnpm-'+process.env.PNPM_VERSION+'.tgz';https.get(url,(res)=>{if(res.statusCode!==200){throw new Error('pnpm download failed: '+res.statusCode)}const chunks=[];res.on('data',(chunk)=>chunks.push(chunk));res.on('end',()=>{const data=Buffer.concat(chunks);const digest='sha512-'+crypto.createHash('sha512').update(data).digest('base64');if(digest!==process.env.PNPM_INTEGRITY){throw new Error('pnpm integrity mismatch')}fs.writeFileSync('/tmp/pnpm.tgz',data);});}).on('error',(error)=>{throw error;});"
RUN mkdir -p /opt/pnpm \
&& tar -xzf /tmp/pnpm.tgz -C /opt/pnpm --strip-components=1 \
&& chmod +x /opt/pnpm/bin/pnpm.cjs /opt/pnpm/bin/pnpx.cjs \
&& ln -sf /opt/pnpm/bin/pnpm.cjs /usr/local/bin/pnpm \
&& ln -sf /opt/pnpm/bin/pnpx.cjs /usr/local/bin/pnpx \
&& rm /tmp/pnpm.tgz
COPY frontend/package.json frontend/pnpm-lock.yaml frontend/pnpm-workspace.yaml frontend/.pnpmfile.cjs ./
COPY frontend/patches ./patches
RUN pnpm install --frozen-lockfile
COPY frontend ./
ENV NEXT_TELEMETRY_DISABLED=1
ENV POSTCSS_WORKERS=1
ENV DISABLE_POSTCSS_WORKERS=true
RUN pnpm run build

# Stage 3: Combined image (Python + Node.js)
# backend-runtime ends with USER appuser (non-root). Stage 3 inherits that
# non-root context, so no root elevation is needed here.
FROM backend-runtime AS combined-runtime

ARG OCI_IMAGE_TITLE="naruon"
ARG OCI_IMAGE_DESCRIPTION="Naruon combined FastAPI and Next.js runtime image"
LABEL org.opencontainers.image.title="${OCI_IMAGE_TITLE}" \
org.opencontainers.image.description="${OCI_IMAGE_DESCRIPTION}"

# Runtime Node is copied into an app-owned directory so that no root elevation
# is required. /app is owned by appuser (set in stage 1) so appuser can write
# here directly.
Expand Down
17 changes: 15 additions & 2 deletions backend/services/attachment_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from urllib.parse import unquote

from .text_safety import strip_html_markup

Expand All @@ -16,6 +17,7 @@
}
MAX_ATTACHMENT_PARSE_SOURCE_CHARS = 1_000_000
MAX_ATTACHMENT_PARSE_SOURCE_BYTES = 20 * 1024 * 1024
MAX_ATTACHMENT_FILENAME_DECODE_ROUNDS = 3


@dataclass(frozen=True)
Expand Down Expand Up @@ -266,8 +268,19 @@ def _parser_key_for(parse_content_type: str, parse_status: str) -> str:

def _safe_filename(filename: str | None) -> str:
"""Return a basename-only attachment display filename."""
display_filename = strip_html_markup(_sanitize_nul(filename or "attachment"))
display_filename = Path(display_filename).name.strip()
display_filename = filename or "attachment"
for _ in range(MAX_ATTACHMENT_FILENAME_DECODE_ROUNDS):
decoded_filename = unquote(display_filename)
if decoded_filename == display_filename:
break
display_filename = decoded_filename
# Entity-encoded percent escapes (for example ``%2e``) only become
# literal ``%`` sequences during markup decoding, so the residual-encoding
# guard must run after ``strip_html_markup`` to stay fail-closed.
display_filename = strip_html_markup(_sanitize_nul(display_filename))
if unquote(display_filename) != display_filename:
return "attachment"
display_filename = Path(display_filename.replace("\\", "/")).name.strip()
if display_filename in {"", ".", ".."}:
return "attachment"
return display_filename
Expand Down
26 changes: 26 additions & 0 deletions backend/tests/test_attachment_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pytest

from services.attachment_parser import (
_safe_filename,
MAX_ATTACHMENT_PARSE_SOURCE_BYTES,
MAX_ATTACHMENT_PARSE_SOURCE_CHARS,
decode_deferred_attachment_payload,
Expand Down Expand Up @@ -255,3 +256,28 @@ def test_deferred_pdf_decoder_rejects_non_pdf_and_oversized_payloads(monkeypatch
oversized = base64.b64encode(b"%PDF-1.7").decode("ascii")
with pytest.raises(ValueError, match="size limit"):
decode_deferred_attachment_payload(oversized)


def test_safe_filename_handles_windows_path_traversal():
assert _safe_filename("..\\..\\upload.txt") == "upload.txt"
assert _safe_filename("C:\\mail\\report.pdf") == "report.pdf"
assert _safe_filename("%5c%2e%2e%5csecret.txt") == "secret.txt"
assert _safe_filename("%252e%252e%252fsecret.txt") == "secret.txt"
assert _safe_filename("%252525252e%252525252e%252525252fsecret.txt") == "attachment"


def test_safe_filename_fails_closed_after_entity_decoding():
"""Entity-encoded percent escapes must trip the residual guard post-decode."""
assert _safe_filename("%2e%2e%2fsecret.txt") == "attachment"


def test_safe_filename_plain_percent_encoded_traversal_still_decodes_to_basename():
"""Single percent-encoded traversal still decodes in-round to its basename."""
assert _safe_filename("%2e%2e%2fsecret.txt") == "secret.txt"


def test_safe_filename_benign_name_survives_unchanged():
assert _safe_filename("annual-report-2026.pdf") == "annual-report-2026.pdf"
assert _safe_filename("quarterly report & notes.pdf") == (
"quarterly report & notes.pdf"
)
12 changes: 11 additions & 1 deletion backend/tests/test_release_governance.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,18 @@ def test_container_images_cover_all_oci_predefined_image_annotations() -> None:
root_dockerfile = read_repo_text("Dockerfile")
frontend_dockerfile = read_repo_text("frontend/Dockerfile")
docker_publish_workflow = read_repo_text(".github/workflows/docker-publish.yml")
backend_stage = root_dockerfile.split("\nFROM ", 2)[1]
combined_stage = root_dockerfile.split("FROM backend-runtime AS combined-runtime", 1)[1]
assert 'ARG OCI_IMAGE_TITLE="naruon backend"' in backend_stage
assert 'ARG OCI_IMAGE_DESCRIPTION="Naruon FastAPI backend runtime image"' in backend_stage
assert 'ARG OCI_IMAGE_TITLE="naruon"' in combined_stage
assert 'ARG OCI_IMAGE_DESCRIPTION="Naruon combined FastAPI and Next.js runtime image"' in combined_stage
assert 'org.opencontainers.image.title="${OCI_IMAGE_TITLE}"' in combined_stage
assert 'org.opencontainers.image.description="${OCI_IMAGE_DESCRIPTION}"' in combined_stage

for annotation_key in OCI_PREDEFINED_IMAGE_ANNOTATION_KEYS:
assert annotation_key in root_dockerfile
assert annotation_key in backend_stage
assert annotation_key in frontend_dockerfile
assert annotation_key in docker_publish_workflow

Expand Down Expand Up @@ -762,7 +771,7 @@ def test_frontend_dockerfile_builds_and_starts_production_artifact() -> None:
assert "ENV POSTCSS_WORKERS=1" in dockerfile
assert "ENV DISABLE_POSTCSS_WORKERS=true" in dockerfile
assert (
'CMD sh -c "exec ./node_modules/.bin/next start --hostname 0.0.0.0 --port ${PORT:-3000}"'
r'CMD ["sh", "-c", "exec ./node_modules/.bin/next start --hostname 0.0.0.0 --port \"${PORT:-3000}\""]'
in dockerfile
)
assert "HEALTHCHECK --interval=30s --timeout=5s" in dockerfile
Expand Down Expand Up @@ -845,6 +854,7 @@ def test_backend_dockerfile_uses_modern_env_syntax() -> None:
assert "http://127.0.0.1:8000/" in dockerfile
assert "http://127.0.0.1:3000/" in dockerfile
assert "useradd --system --create-home --home-dir /home/appuser" in dockerfile
assert "--key SYS_UID_MAX=10001 --uid 10001 --gid appuser --shell /usr/sbin/nologin" in dockerfile
backend_cmd = 'CMD ["python", "scripts/start_backend.py", "--host", "0.0.0.0", "--port", "8000"]'
assert dockerfile.find("USER appuser") < dockerfile.find(backend_cmd)
assert dockerfile.rfind("USER appuser") < dockerfile.find(
Expand Down
92 changes: 92 additions & 0 deletions backend/tests/test_runtime_image_targets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Regression contracts for independently deployable OCI runtime images.

The release workflow publishes three compatibility surfaces: a backend image, a
frontend image, and the legacy combined ``naruon`` image. Each matrix entry must
select an explicit Docker build target so a future Dockerfile stage reorder
cannot silently turn the backend artifact back into the combined runtime.
"""

from __future__ import annotations

import json
from pathlib import Path

import yaml


REPO_ROOT = Path(__file__).resolve().parents[2]
DOCKER_PUBLISH_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "docker-publish.yml"


def test_image_context_excludes_project_virtual_environments() -> None:
"""Keep local host packages out of backend COPY and image build contexts."""
ignore_patterns = (REPO_ROOT / ".dockerignore").read_text(encoding="utf-8").splitlines()
assert "**/.venv" in ignore_patterns


def _component_entry(workflow: dict[object, object], job_name: str, component: str) -> dict[str, object]:
"""Return one named image-matrix entry from a release workflow job."""
jobs = workflow["jobs"]
assert isinstance(jobs, dict)
job = jobs[job_name]
assert isinstance(job, dict)
strategy = job["strategy"]
assert isinstance(strategy, dict)
matrix = strategy["matrix"]
assert isinstance(matrix, dict)
entries = matrix["include"]
assert isinstance(entries, list)
matches = [entry for entry in entries if entry.get("component") == component]
assert len(matches) == 1, f"expected exactly one {component!r} matrix entry"
entry = matches[0]
assert isinstance(entry, dict)
return entry


def test_release_workflow_selects_explicit_independent_runtime_targets() -> None:
"""Publish backend/frontend artifacts from explicit independent stages."""
workflow_text = DOCKER_PUBLISH_WORKFLOW.read_text(encoding="utf-8")
workflow = yaml.safe_load(workflow_text)
assert isinstance(workflow, dict)

for job_name in ("pull_request_image_validation", "publish_images"):
backend = _component_entry(workflow, job_name, "backend")
frontend = _component_entry(workflow, job_name, "frontend")
combined = _component_entry(workflow, job_name, "naruon")

assert backend["dockerfile"] == "Dockerfile"
assert backend["target"] == "backend-runtime"
assert frontend["dockerfile"] == "frontend/Dockerfile"
assert frontend["target"] == "frontend-runtime"
assert combined["dockerfile"] == "Dockerfile"
assert combined["target"] == "combined-runtime"

assert workflow_text.count("target: ${{ matrix.target }}") == 2

validation_steps = workflow["jobs"]["pull_request_image_validation"]["steps"]
build_inputs = next(step["with"] for step in validation_steps if step.get("id") == "build")
assert build_inputs["outputs"] == "type=cacheonly"
assert build_inputs["push"] is False
assert build_inputs["platforms"] == "linux/amd64,linux/arm64"

root_dockerfile = (REPO_ROOT / "Dockerfile").read_text(encoding="utf-8")
frontend_dockerfile = (REPO_ROOT / "frontend" / "Dockerfile").read_text(
encoding="utf-8"
)
assert "FROM backend-runtime AS combined-runtime" in root_dockerfile
assert " AS frontend-runtime" in frontend_dockerfile.splitlines()[0]


def test_frontend_command_executes_next_without_an_outer_shell() -> None:
"""Keep runtime PORT expansion while replacing the sole shell with Next."""
frontend_dockerfile = (REPO_ROOT / "frontend" / "Dockerfile").read_text(
encoding="utf-8"
)
command_lines = [line for line in frontend_dockerfile.splitlines() if line.startswith("CMD ")]
assert len(command_lines) == 1
command_args = json.loads(command_lines[0].removeprefix("CMD "))
assert command_args == [
"sh",
"-c",
'exec ./node_modules/.bin/next start --hostname 0.0.0.0 --port "${PORT:-3000}"',
]
Loading
Loading