Skip to content
Draft
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
3dc8420
test(dav): reject ambiguous nested authorization encodings
seonghobae Aug 14, 2026
029c065
fix(dav): enforce single-decode authorization boundary
seonghobae Aug 14, 2026
532a0b4
test(dav): reproduce dropped normalized route path
seonghobae Aug 14, 2026
fae5b62
fix(dav): propagate canonical authorization path
seonghobae Aug 14, 2026
b0e530d
Merge branch 'develop' into fix/dav-single-decode-authorization
opencode-agent[bot] Aug 14, 2026
0a897db
test(dav): align route assertions with framework decoding
seonghobae Aug 14, 2026
9e82a88
Merge protected develop into DAV authorization fix
seonghobae Aug 14, 2026
f7abb82
Merge protected develop into DAV authorization fix
seonghobae Aug 14, 2026
b66af0d
test(security): reject unsafe local-provider address classes
seonghobae Aug 15, 2026
81c8890
fix(security): bound local LLM provider networks
seonghobae Aug 15, 2026
5b0a888
docs(security): record DAV and local-provider network boundaries
seonghobae Aug 15, 2026
60feaad
test(security): cover IPv6 local-provider network boundaries
seonghobae Aug 15, 2026
df2bf10
Merge protected develop into security fix lane
seonghobae Aug 15, 2026
d6a870d
test(data): reproduce cross-organization document access
seonghobae Aug 15, 2026
c05855f
test(data): inspect only document WHERE scope
seonghobae Aug 15, 2026
2b8a18f
fix(data): enforce document organization scope
seonghobae Aug 15, 2026
7cfa1bf
merge(develop): integrate current protected base
seonghobae Aug 15, 2026
17b3452
test(data): cover remaining document organization scopes
seonghobae Aug 15, 2026
0ca9624
test(data): use one api.data import style
seonghobae Aug 15, 2026
3a56fed
Merge branch 'develop' into fix/dav-single-decode-authorization
opencode-agent[bot] Aug 15, 2026
95f23c2
test(security): reject loopback DNS rebinding
seonghobae Aug 15, 2026
d73e9e4
fix(security): bind loopback access to local host identity
seonghobae Aug 15, 2026
7052b66
test(security): scope loopback opt-in to local identities
seonghobae Aug 15, 2026
76b5d16
test(dav): reject advertised unsupported capabilities
seonghobae Aug 16, 2026
a094523
fix(dav): expose only implemented protocol capabilities
seonghobae Aug 16, 2026
085aecf
Merge branch 'develop' into fix/dav-single-decode-authorization
seonghobae Aug 17, 2026
bde6998
Merge branch 'develop' into fix/dav-single-decode-authorization
seonghobae Aug 17, 2026
ff6e475
merge(develop): reconcile DAV/SSRF/tenant isolation onto current develop
cursoragent Aug 17, 2026
89d8850
Merge remote-tracking branch 'origin/develop' into HEAD
seonghobae Aug 20, 2026
07954b2
Merge branch 'develop' into fix/dav-single-decode-authorization
opencode-agent[bot] Aug 22, 2026
8c6a51e
Merge branch 'develop' into fix/dav-single-decode-authorization
seonghobae Aug 26, 2026
8146c56
Merge remote-tracking branch 'origin/develop' into codex/pr1345-repair
seonghobae Sep 5, 2026
9a01989
fix(dav): restore canonical LLM owner boundary
seonghobae Sep 6, 2026
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
73 changes: 62 additions & 11 deletions backend/api/dav.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging
from html import escape as escape_xml_text
from urllib.parse import unquote

from fastapi import APIRouter, Depends, HTTPException, Request, Response
from sqlalchemy.ext.asyncio import AsyncSession
Expand All @@ -13,15 +12,67 @@

router = APIRouter(prefix="/dav", tags=["dav"])

_DAV_AUTHORIZATION_PATH_MAX_CHARACTERS = 8192
_HEX_DIGITS = frozenset("0123456789abcdefABCDEF")
_DAV_STRUCTURAL_OCTETS = frozenset(
{*range(0x20), 0x2E, 0x2F, 0x5C, 0x7F}
)


def _residual_percent_octet(path: str, percent_index: int) -> int | None:
"""Return the octet exposed by another decode, following nested ``%25``."""

cursor = percent_index + 1
while cursor + 1 < len(path):
pair = path[cursor : cursor + 2]
if pair[0] not in _HEX_DIGITS or pair[1] not in _HEX_DIGITS:
return None
octet = int(pair, 16)
if octet != 0x25:
return octet
cursor += 2
return None


def _has_ambiguous_percent_encoding(path: str) -> bool:
"""Detect residual encodings that another decode would make structural."""

for index, character in enumerate(path):
if character != "%":
continue
octet = _residual_percent_octet(path, index)
if octet in _DAV_STRUCTURAL_OCTETS:
return True
return False
Comment thread
seonghobae marked this conversation as resolved.
Resolved


def _normalize_dav_authorization_path(path: str) -> str:
"""Validate the framework-decoded DAV path without decoding it again.

ASGI routing has already decoded the request-target path once. Authorization
therefore treats residual percent text as data unless another decode would
introduce a traversal dot, separator, backslash, or control octet. Literal
backslashes are normalized to separators for owner/traversal checks.
"""

if len(path) > _DAV_AUTHORIZATION_PATH_MAX_CHARACTERS:
raise HTTPException(
status_code=414,
detail="DAV path exceeds authorization length limit",
)
if any(ord(character) < 0x20 or ord(character) == 0x7F for character in path):
raise HTTPException(
status_code=400,
detail="DAV path contains control characters",
)

normalized_path = path.replace("\\", "/")
for _ in range(100):
decoded_path = unquote(normalized_path).replace("\\", "/")
if decoded_path == normalized_path:
return normalized_path
normalized_path = decoded_path
raise HTTPException(status_code=400, detail="DAV path decoding limit exceeded")
if _has_ambiguous_percent_encoding(normalized_path):
raise HTTPException(
status_code=400,
detail="DAV path contains ambiguous percent encoding",
)
return normalized_path
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


def _dav_path_owner_user_id(path: str) -> str | None:
Expand Down Expand Up @@ -173,8 +224,9 @@ async def dav_handler(
Provider-backed writeback stays fail-closed until source capability and
ETag/If-Match enforcement are available through signed writeback intents.
"""
_ensure_dav_owner_scope(path, auth_context)
safe_path = repr(path)[1:-1]
normalized_path = _normalize_dav_authorization_path(path)
_ensure_dav_owner_scope(normalized_path, auth_context)
safe_path = repr(normalized_path)[1:-1]
logger.info("DAV Request: %s /%s", request.method, safe_path)

if request.method == "OPTIONS":
Expand All @@ -190,14 +242,13 @@ async def dav_handler(
if request.method == "PROPFIND":
return await _handle_project_propfind(
request=request,
path=path,
path=normalized_path,
auth_context=auth_context,
db=db,
)

if request.method == "PUT":
body = await request.body()
safe_path = repr(path)[1:-1]
logger.info("DAV PUT received %s bytes at /%s", len(body), safe_path)
logger.warning(
"DAV PUT rejected at /%s: provider-backed DAV writeback is not "
Expand Down
145 changes: 114 additions & 31 deletions backend/tests/test_dav_api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import defusedxml.ElementTree as ET

import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient

from api.dav import _normalize_dav_authorization_path
from main import app
from services.webdav_service import webdav_service

Expand Down Expand Up @@ -94,6 +96,91 @@ def test_dav_rejects_ownerless_options_before_capability_discovery(
assert response.json()["detail"] == "DAV path must include an owner user"


def test_dav_authorization_path_preserves_literal_percent_data():
assert (
_normalize_dav_authorization_path("user123/projects/literal%25")
== "user123/projects/literal%25"
)
assert (
_normalize_dav_authorization_path("user123/projects/분석%zz")
== "user123/projects/분석%zz"
)


@pytest.mark.parametrize(
"path",
[
"user123/projects/%2e%2e/secret",
"user123/projects/%252e%252e/secret",
"user123/projects/%2fsecret",
"user123/projects/%5csecret",
"user123/projects/%00secret",
"user123/projects/%250asecret",
],
)
def test_dav_authorization_path_rejects_nested_structural_decoding(path):
with pytest.raises(HTTPException) as exc_info:
_normalize_dav_authorization_path(path)

assert exc_info.value.status_code == 400
assert exc_info.value.detail == "DAV path contains ambiguous percent encoding"


@pytest.mark.parametrize("control_character", ["\x00", "\x1f", "\x7f"])
def test_dav_authorization_path_rejects_decoded_controls(control_character):
with pytest.raises(HTTPException) as exc_info:
_normalize_dav_authorization_path(
f"user123/projects/report{control_character}name"
)

assert exc_info.value.status_code == 400
assert exc_info.value.detail == "DAV path contains control characters"


def test_dav_authorization_path_normalizes_literal_backslashes_once():
assert (
_normalize_dav_authorization_path(r"user123\projects\demo")
== "user123/projects/demo"
)


def test_dav_authorization_path_has_explicit_resource_boundary():
prefix = "user123/projects/"
boundary_path = prefix + ("x" * (8192 - len(prefix)))
assert _normalize_dav_authorization_path(boundary_path) == boundary_path

with pytest.raises(HTTPException) as exc_info:
_normalize_dav_authorization_path(boundary_path + "x")

assert exc_info.value.status_code == 414
assert exc_info.value.detail == "DAV path exceeds authorization length limit"


def test_dav_route_rejects_framework_decoded_nested_traversal(
dev_auth_dependency_overrides,
):
"""Reject traversal after ASGI exposes the nested encoding as a literal segment."""

with TestClient(app) as client:
response = client.options(
"/dav/user123/projects/%252e%252e/secret",
headers=AUTH_HEADERS,
)

assert response.status_code == 403
assert response.json()["detail"] == "DAV path must include an owner user"
Comment thread
seonghobae marked this conversation as resolved.
Resolved


def test_dav_route_preserves_encoded_percent_as_data(dev_auth_dependency_overrides):
with TestClient(app) as client:
response = client.options(
"/dav/user123/projects/literal%2525",
headers=AUTH_HEADERS,
)

assert response.status_code == 200


def test_dav_propfind(dev_auth_dependency_overrides, stub_dav_project_folders):
with TestClient(app) as client:
response = client.request(
Expand All @@ -114,6 +201,7 @@ def test_dav_propfind_escapes_path_values(
"PROPFIND", "/dav/user123/projects/x%26y%3Cz%3E", headers=AUTH_HEADERS
)
assert response.status_code == 207
assert "<D:multistatus" in response.text
assert "x&amp;y&lt;z&gt;" in response.text
assert "x&y<z>" not in response.text
ET.fromstring(response.text)
Expand Down Expand Up @@ -156,48 +244,43 @@ def test_dav_unsupported_method_logs_reason(dev_auth_dependency_overrides, caplo
for record in caplog.records
)


def test_dav_log_injection_prevention(dev_auth_dependency_overrides, caplog):
"""
Test that DAV handlers safely encode control characters in the requested path,
preventing log injection vulnerabilities.
"""
"""Reject decoded control characters before they can reach DAV request logs."""
import asyncio
import logging

caplog.set_level(logging.INFO)
malicious_path = "user123/projects/test\x1b[31minjected\n\r"

# Since HTTP clients block raw control chars and starlette unquotes but might reject it before reaching our route,
# we test the handler directly to ensure the logger is using repr().
import asyncio
from fastapi import Request

from api.auth import AuthContext
from api.dav import dav_handler

caplog.set_level(logging.INFO, logger="api.dav")
malicious_path = "user123/projects/test\x1b[31minjected\n\r"
scope = {
"type": "http",
"method": "OPTIONS",
"headers": [],
}

async def run_handler():
req = Request(scope)
from api.auth import AuthContext
auth_ctx = AuthContext(user_id="user123", organization_id="org1", role="user", group_ids=[], workspace_id="ws1")

from api.dav import dav_handler
await dav_handler(request=req, path=malicious_path, auth_context=auth_ctx)

asyncio.run(run_handler())

# In some fastapi versions, returning an unexpected path might return 404. Let's just assert the log was captured.
# The vulnerability is about the logger.
request = Request(scope)
auth_context = AuthContext(
user_id="user123",
organization_id="org1",
role="user",
group_ids=[],
workspace_id="ws1",
)
await dav_handler(
request=request,
path=malicious_path,
auth_context=auth_context,
)

# Assert that the raw ansi escape / newline was not logged, but encoded
raw_ansi = "\x1b[31m"
found_in_logs = False
for record in caplog.records:
if "DAV Request" in record.message:
assert raw_ansi not in record.message, "Raw ANSI escape sequence found in logs!"
assert "\n" not in record.message[12:], "Raw newline found in log message body!"
assert "\\x1b[31minjected\\n\\r" in record.message or "\\x1b[31minjected\\r\\n" in record.message, "Escaped characters missing from log message!"
found_in_logs = True
with pytest.raises(HTTPException) as exc_info:
asyncio.run(run_handler())

assert found_in_logs, "DAV Request log was not found"
assert exc_info.value.status_code == 400
assert exc_info.value.detail == "DAV path contains control characters"
assert not any("DAV Request" in record.getMessage() for record in caplog.records)
55 changes: 55 additions & 0 deletions backend/tests/test_dav_normalized_route.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Route-level regression coverage for canonical DAV authorization paths."""

import pytest
from fastapi.testclient import TestClient

from main import app
from services.webdav_service import webdav_service

AUTH_HEADERS = {
"X-User-Id": "user123",
"X-User-Role": "organization_admin",
"X-Organization-Id": "org-acme",
}


@pytest.fixture
def stub_dav_project_folder(monkeypatch):
"""Return one deterministic project folder through the production DAV service seam."""

async def fake_project_folders(db, user_id, organization_id, folder_uid=None):
assert user_id == "user123"
assert organization_id == "org-acme"
assert folder_uid == "demo"
return [
{
"folder_uid": "demo",
"project_name": "demo",
"webdav_path": "/projects/demo",
"owner_user_id": user_id,
"organization_id": organization_id,
}
]

monkeypatch.setattr(
webdav_service,
"get_project_folders_from_db",
fake_project_folders,
)


def test_propfind_routes_framework_decoded_backslashes_through_canonical_path(
dev_auth_dependency_overrides,
stub_dav_project_folder,
):
"""A once-decoded backslash path must reach the same project route as slashes."""

with TestClient(app) as client:
response = client.request(
"PROPFIND",
"/dav/user123%5Cprojects%5Cdemo",
headers=AUTH_HEADERS,
)

assert response.status_code == 207
assert "<D:displayname>demo</D:displayname>" in response.text
Loading