Skip to content
Open
Show file tree
Hide file tree
Changes from 7 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
8 changes: 8 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,6 +149,7 @@ jobs:
with:
context: ${{ matrix.context }}
file: ${{ matrix.dockerfile }}
target: ${{ matrix.target }}
platforms: linux/amd64,linux/arm64
push: false
build-args: |
Expand Down Expand Up @@ -185,20 +189,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 +334,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`.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ 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
FROM backend-runtime AS combined-runtime
Comment thread
seonghobae marked this conversation as resolved.
Outdated

ARG OCI_IMAGE_CREATED=""
ARG OCI_IMAGE_AUTHORS="Seongho Bae"
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"
)
64 changes: 64 additions & 0 deletions backend/tests/test_runtime_image_targets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""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

from pathlib import Path

import yaml


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


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

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]
2 changes: 1 addition & 1 deletion frontend/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:26-slim@sha256:4ebb5ace66f15a24c14c492e01a8beeed4fddf970a856109f5126e703e5fe503
FROM node:26-slim@sha256:4ebb5ace66f15a24c14c492e01a8beeed4fddf970a856109f5126e703e5fe503 AS frontend-runtime

ARG OCI_IMAGE_CREATED=""
ARG OCI_IMAGE_AUTHORS="Seongho Bae"
Expand Down Expand Up @@ -74,4 +74,4 @@
CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || '3000')).then((response) => { if (!response.ok) process.exit(1); }).catch(() => process.exit(1))"

# Render injects $PORT at runtime
CMD sh -c "exec ./node_modules/.bin/next start --hostname 0.0.0.0 --port ${PORT:-3000}"

Check warning on line 77 in frontend/Dockerfile

View workflow job for this annotation

GitHub Actions / validate frontend image

JSON arguments recommended for ENTRYPOINT/CMD to prevent unintended behavior related to OS signals

JSONArgsRecommended: JSON arguments recommended for CMD to prevent unintended behavior related to OS signals More info: https://docs.docker.com/go/dockerfile/rule/json-args-recommended/
Loading