Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

feature/Sign-publicurl-virtual-hosted · L-260925-94110e (#1260)

Louis Choquel4f535ec56245
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6c3ba9e5f..d6ace9365 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,10 @@
### Fixed
+- **S3 links name the bucket's own host (Breaking)**: the S3 storage provider now signs links, and reads and writes objects, on the bucket's regional host `<bucket>.s3.<region>.amazonaws.com` instead of the region's shared endpoint `s3.<region>.amazonaws.com`, so a content security policy can allow one bucket's links without allowing every bucket in the region. A legacy bucket name that cannot be a hostname, one with uppercase letters or an underscore, keeps the path-style form on the regional endpoint, for signed and unsigned links alike, where an unsigned link used to name a virtual host that could not serve it; the configuration still refuses a bucket name containing a dot. A self-hosted deployment whose egress rules allow S3 by hostname must allow `*.s3.<region>.amazonaws.com`.
+- **Image and document inputs carry a `public_url` whatever form their url takes**: an input given as a `pipelex-storage://` reference now gets a link signed through the storage provider, replacing any link it carried, which may have expired, and an input given as an `http(s)` URL gets that URL as its `public_url` unless it names another. This holds for an image or document passed alone, in a list or in a structured field, so a template writing `{{ image.public_url }}` no longer renders `None` for one uploaded to storage or passed by URL, and a reference the storage provider refuses as a key is reported as an input error before the run starts.
+- **A NUL byte in an input's path or storage reference is an input error**: a local file path, or a `pipelex-storage://` reference on local storage, holding a NUL byte used to escape as an internal error; it is now reported as an input error before the run starts.
+- **Unsigned storage links percent-encode their key**: the S3 and GCS providers' unsigned links now encode a key holding a space, `+`, `#` or `?` as a signed link does, instead of naming a path the URL cuts short.
- **A log call before `log.configure` no longer raises**: it goes to the stdlib's default handling at the stdlib's default level, so a library that logs before Pipelex boots, or a boot that logs while it configures, cannot crash on the log line itself. Between `log.configure` and the sink's arrival at boot, every record is held and replayed through the selected sink in order, so a boot's own lines are rendered by the sink the configuration chose, and a boot that dies before the sink arrives sends all of them to stderr rather than only a warning or worse: each one passed the level the configuration set, and a failed boot is when that trail is worth most.
- **A log call never raises on a value the record or JSON refuses**: a field named like an attribute the `LogRecord` class owns (`__class__`, `__dict__`, `getMessage`) is prefixed like any other collision instead of raising `TypeError` or shadowing the method every formatter calls, and a content `json` refuses, a circular reference or a mapping with a non-string key, is rendered as its `repr` with no `data` instead of raising `ValueError` or `TypeError` out of `log.info`. A non-finite float nested inside a pydantic model is spelled as text like one at the top level, so a single `NaN` costs that one float its type and no other value on the line its structure. On the `console` sink the same promise needed the stdlib's own guard put back: Rich overrides `emit` without it, so a message carrying a tag-shaped span — `list[int]` in a type complaint, or a bracketed path, which Rich reads as a closing tag — raised `MarkupError` out of the log call and replaced the failure being reported with itself. Such a line now costs at most its own rendering, and an error assembled from an exception is rendered verbatim rather than read as markup, so the brackets and the type names in it reach the terminal as they were written.
- **A field named `_pipelex_forwarded` no longer deletes its own record**: the name the holding handler stamps on a record it has already forwarded was treated as unspellable because it starts with an underscore, but a fresh record does not carry it, so a caller's `fields={"_pipelex_forwarded": ...}` landed unprefixed and had the record rejected from every sink by the guard that exists to stop a double delivery. Such an entry is now carried under the `field_` prefix like any other collision, and the line is delivered.
diff --git a/docs/building-methods/concepts/native-concepts.md b/docs/building-methods/concepts/native-concepts.md
index 532bf81ed..348246474 100644
--- a/docs/building-methods/concepts/native-concepts.md
+++ b/docs/building-methods/concepts/native-concepts.md
@@ -76,7 +76,7 @@ class ImageContent(StuffContent):
**Fields:**
- `url`: Location of the image (a storage URI, an HTTP(S) URL, or a base64 data URL)
-- `public_url`: Optional public-facing URL (when `url` is a private/internal reference)
+- `public_url`: A URL a viewer can open, which the runtime fills for every image input it normalizes, passed alone, in a list or in a structured field: the storage provider's link for a stored file (a `pipelex-storage://` reference, a `data:` URL or an uploaded local file), and the URL itself for an `http(s)` one unless the input names another. A stored file's link is signed when signed URLs are configured, so it expires: a template writing `{{ image.public_url }}` into HTML produces a report that stops showing the image once the link has expired.
- `source_prompt` / `source_negative_prompt`: The prompts used to generate the image (if applicable)
- `caption`: Descriptive text for the image
- `mime_type`: Optional MIME type of the image
@@ -102,7 +102,7 @@ class DocumentContent(StuffContent):
**Fields:**
- `url`: Location of the document file, storage URL, or web page URL
-- `public_url`: Optional public-facing URL (when `url` is a private/internal reference)
+- `public_url`: A URL a viewer can open, filled by the runtime for every document input it normalizes, exactly as for `ImageContent`: the storage provider's link for a stored file, which expires when signed URLs are configured, and the URL itself for an `http(s)` one
- `mime_type`: Optional MIME type of the document (e.g., "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
- `filename`: Optional filename of the document
- `title`: Optional title of the document or source
diff --git a/docs/features/cloud-storage.md b/docs/features/cloud-storage.md
index c01244942..4308ff3f8 100644
--- a/docs/features/cloud-storage.md
+++ b/docs/features/cloud-storage.md
@@ -23,6 +23,14 @@ Pipelex can automatically upload generated artifacts — images, extracted pages
- **Public URLs** — Directly accessible URLs for public content
- **Signed URLs** — Time-limited secure URLs for private content, with configurable lifespan
+### The host an S3 link names
+
+An S3 link, signed or not, is virtual-hosted on the bucket's own regional host: `https://<bucket>.s3.<region>.amazonaws.com/<key>`. The runtime's own reads and writes go to that host too. A page that shows the runtime's links under a content security policy therefore allows that one origin, which covers your bucket and no one else's, where the region's shared endpoint `https://s3.<region>.amazonaws.com` would cover every bucket in the region.
+
+The exception is a legacy bucket name that cannot be a hostname, one with uppercase letters or an underscore. Its links are path-style on the regional endpoint, `https://s3.<region>.amazonaws.com/<bucket>/<key>`, so a policy must allow the shared endpoint for it. Name a bucket with lowercase letters, digits and hyphens only if its links have to be allowed on their own. A bucket name containing a dot is refused by the storage configuration; it could not be virtual-hosted over HTTPS anyway, because it breaks the `*.s3.<region>.amazonaws.com` wildcard certificate.
+
+A deployment whose egress rules allow S3 by hostname must allow `*.s3.<region>.amazonaws.com`, not only `s3.<region>.amazonaws.com`.
+
## Configuration
Storage is configured in `pipelex.toml` under `[runtime.storage]`. Set `method` to `local`, `in_memory`, `s3`, or `gcp`, then provide provider-specific settings such as `bucket_name`, `region`, or `project_id` in the matching subsection.
diff --git a/pipelex/pipeline/exceptions.py b/pipelex/pipeline/exceptions.py
index c34ef83c2..f0bf271f7 100644
--- a/pipelex/pipeline/exceptions.py
+++ b/pipelex/pipeline/exceptions.py
@@ -233,13 +233,14 @@ class PipelineInputContentError(PipelexError):
"""A pipeline input's content reference (url) is unusable.
Raised by the input normalizer when an Image/Document input carries a local
- path that cannot be read. The caller supplied the value — INPUT domain, so
- API servers answer 422, never a sanitized 500 (a blank url used to surface
- as IsADirectoryError('.') → 500).
+ path that cannot be read, or a pipelex-storage:// reference the storage
+ provider refuses as a key (a path escaping local storage, for one). The
+ caller supplied the value — INPUT domain, so API servers answer 422, never
+ a sanitized 500 (a blank url used to surface as IsADirectoryError('.') → 500).
Deliberately NOT caller-facing: the message names the resolved path and the
- ``OSError`` subclass that rejected it, which are server-side filesystem
- facts. Surviving STRICT disclosure would turn the report into an
+ ``OSError`` subclass that rejected it, or the storage provider's reason for
+ refusing a key, which are server-side storage facts. Surviving STRICT disclosure would turn the report into an
existence/permission oracle over the runner's filesystem for any
authenticated caller — ``PermissionError`` on a path that exists reads
differently from ``FileNotFoundError`` on one that does not. The
diff --git a/pipelex/pipeline/execution_seams.py b/pipelex/pipeline/execution_seams.py
index 9189f6329..65ad67641 100644
--- a/pipelex/pipeline/execution_seams.py
+++ b/pipelex/pipeline/execution_seams.py
@@ -283,7 +283,7 @@ async def prepare_pipe_job(
)
)
- # Normalize data URLs to pipelex-storage:// URIs if configured.
+ # Normalize data URLs to pipelex-storage:// URIs, and give every image and document input a public_url, if configured.
if working_memory and execution_config.is_normalize_data_urls_to_storage and not execution_config.is_mock_inputs:
working_memory = await normalize_data_urls_to_storage(working_memory, storage_scope=storage_scope)
diff --git a/pipelex/pipeline/input_normalizer.py b/pipelex/pipeline/input_normalizer.py
index 03233e758..f77ce02a8 100644
--- a/pipelex/pipeline/input_normalizer.py
+++ b/pipelex/pipeline/input_normalizer.py
@@ -2,7 +2,8 @@
This module provides functions to scan WorkingMemory and convert any ImageContent
or DocumentContent with data URLs (data:...;base64,...) or local file paths to
-pipelex-storage:// URIs for more efficient pipeline processing.
+pipelex-storage:// URIs for more efficient pipeline processing, and to give every
+such input a public_url a template can render, whichever form its url took.
"""
import base64
@@ -22,8 +23,9 @@ from pipelex.runtime_hub import get_storage_provider
from pipelex.tools.misc.file_utils import load_binary_async
from pipelex.tools.misc.filetype_utils import detect_file_type_from_bytes
from pipelex.tools.misc.http_utils import validate_http_url_syntax
+from pipelex.tools.storage.exceptions import StorageInvalidUriError
from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract
-from pipelex.tools.uri.resolved_uri import ResolvedBase64DataUrl, ResolvedHttpUrl, ResolvedLocalPath
+from pipelex.tools.uri.resolved_uri import ResolvedBase64DataUrl, ResolvedHttpUrl, ResolvedPipelexStorage
from pipelex.tools.uri.uri_resolver import resolve_uri
# Type alias for content types that can have their URLs normalized
@@ -31,10 +33,13 @@ NormalizableContent = ImageContent | DocumentContent
async def normalize_data_urls_to_storage(working_memory: WorkingMemory, *, storage_scope: str) -> WorkingMemory:
- """Convert all data URLs in ImageContent and DocumentContent to pipelex-storage:// URIs.
+ """Convert data URLs and local files in ImageContent and DocumentContent to pipelex-storage:// URIs, and fill their public_url.
Scans all stuffs in working memory and for any ImageContent or DocumentContent with
- a data:...;base64,... URL, stores the data and replaces the URL with a pipelex-storage:// URI.
+ a data:...;base64,... URL, or a local path when local uploads are enabled, stores the
+ data and replaces the URL with a pipelex-storage:// URI. Every such content also comes
+ out with a public_url: a link signed through the storage provider for a stored file,
+ the URL itself for an http(s) one. See `_normalize_url_content` for each form.
This handles:
@@ -42,6 +47,8 @@ async def normalize_data_urls_to_storage(working_memory: WorkingMemory, *, stora
- ListContent containing ImageContent or DocumentContent items
- StructuredContent with nested ImageContent or DocumentContent fields (recursive)
+ The images inside a TextAndImagesContent are not reached, and keep their url and public_url as given.
+
Args:
working_memory: The working memory to normalize.
storage_scope: The run's opaque storage prefix. Normalized bytes land
@@ -207,7 +214,15 @@ async def _normalize_url_content(
storage: StorageProviderAbstract,
storage_scope: str,
) -> NormalizableContent:
- """Normalize ImageContent or DocumentContent by converting data URLs to storage URIs.
+ """Normalize ImageContent or DocumentContent to a storage reference and give it a public_url.
+
+ Each form of url comes out with a `public_url` a template can render:
+
+ - A `data:` URL is stored, and its url becomes the storage reference, signed as its `public_url`.
+ - A local path is stored the same way when local uploads are enabled, and kept unchanged otherwise.
+ - A `pipelex-storage://` reference is signed as its `public_url`, replacing any link it carried,
+ which may have expired; a provider that cannot link one leaves the carried link.
+ - An `http(s)` URL is already public: it becomes its own `public_url` unless the input names one.
Args:
content: The image or document content to normalize.
@@ -217,7 +232,13 @@ async def _normalize_url_content(
Returns:
The original content if no normalization needed, or a new instance
- with the normalized URL.
+ with the normalized url and its public_url.
+
+ Raises:
+ PipelineInputUrlMissingError: If the url is blank.
+ PipelineInputUrlInvalidError: If an http(s) url does not parse as one.
+ PipelineInputContentError: If a local path cannot be read, or the storage
+ provider refuses a pipelex-storage:// reference as a key.
"""
if not content.url.strip():
msg = f"{type(content).__name__} input has a blank url — provide https://, data:, pipelex-storage://, or a local file path."
@@ -233,7 +254,21 @@ async def _normalize_url_content(
except ValueError as exc:
msg = f"{type(content).__name__} input: {exc}"
raise PipelineInputUrlInvalidError(msg) from exc
- return content
+ if content.public_url is not None:
+ return content
+ return content.model_copy(update={"public_url": content.url})
+
+ if isinstance(resolved_uri, ResolvedPipelexStorage):
+ # The reference is the durable fact and the link a derivative with an expiry, so the link is
+ # always signed afresh: an input carrying both is usually a previous run's output passed back in.
+ try:
+ public_url = await storage.public_url(uri=resolved_uri.storage_uri)
+ except StorageInvalidUriError as exc:
+ msg = f"{type(content).__name__} input: the storage reference '{content.url}' cannot be linked ({exc})"
+ raise PipelineInputContentError(msg) from exc
+ if public_url is None:
+ return content
+ return content.model_copy(update={"public_url": public_url})
if isinstance(resolved_uri, ResolvedBase64DataUrl):
# Decode base64 data and store
@@ -257,31 +292,30 @@ async def _normalize_url_content(
"mime_type": mime_type,
}
)
- elif isinstance(resolved_uri, ResolvedLocalPath):
- if not get_config().runtime.storage.is_upload_local_content_enabled:
- return content
-
- # Read local file, detect type, upload to storage. OSError covers
- # the whole caller-controllable failure surface (FileNotFoundError,
- # IsADirectoryError, PermissionError, name-too-long, ...) — all of
- # them mean the supplied path is unusable, an INPUT fault.
- try:
- raw_bytes = await load_binary_async(Path(resolved_uri.path))
- except OSError as exc:
- msg = f"Input file cannot be read: '{resolved_uri.path}' ({type(exc).__name__})"
- raise PipelineInputContentError(msg) from exc
- file_type = detect_file_type_from_bytes(raw_bytes)
- key = f"{storage_scope}/assets/{shortuuid.uuid()}.{file_type.extension}"
- storage_uri = await storage.store(data=raw_bytes, key=key, content_type=file_type.mime)
- public_url = await storage.public_url(uri=storage_uri)
- return content.model_copy(
- update={
- "url": storage_uri,
- "public_url": public_url,
- "mime_type": file_type.mime,
- }
- )
- else:
- # Other URI types (HTTP URLs, pipelex-storage://) are kept unchanged
+ # The one form left is a local path
+ if not get_config().runtime.storage.is_upload_local_content_enabled:
return content
+
+ # Read local file, detect type, upload to storage. OSError covers
+ # the caller-controllable failure surface (FileNotFoundError,
+ # IsADirectoryError, PermissionError, name-too-long, ...) and ValueError
+ # the one left, a NUL byte in the path — all of them mean the supplied
+ # path is unusable, an INPUT fault.
+ try:
+ raw_bytes = await load_binary_async(Path(resolved_uri.path))
+ except (OSError, ValueError) as exc:
+ msg = f"Input file cannot be read: '{resolved_uri.path}' ({type(exc).__name__})"
+ raise PipelineInputContentError(msg) from exc
+ file_type = detect_file_type_from_bytes(raw_bytes)
+ key = f"{storage_scope}/assets/{shortuuid.uuid()}.{file_type.extension}"
+ storage_uri = await storage.store(data=raw_bytes, key=key, content_type=file_type.mime)
+ public_url = await storage.public_url(uri=storage_uri)
+
+ return content.model_copy(
+ update={
+ "url": storage_uri,
+ "public_url": public_url,
+ "mime_type": file_type.mime,
+ }
+ )
diff --git a/pipelex/tools/storage/gcp_storage_provider.py b/pipelex/tools/storage/gcp_storage_provider.py
index 4abc446a0..8d085a20f 100644
--- a/pipelex/tools/storage/gcp_storage_provider.py
+++ b/pipelex/tools/storage/gcp_storage_provider.py
@@ -3,6 +3,7 @@ import importlib.util
from datetime import timedelta
from pathlib import Path
from typing import Any
+from urllib.parse import quote
from typing_extensions import override
@@ -172,13 +173,16 @@ class GcpStorageProvider(StorageProviderAbstract):
def _make_public_url(self, key: str) -> str:
"""Build a public URL for a GCS object.
+ The key is percent-encoded as GCS signs it, since a caller's own upload can name a key holding
+ a space, a `#` or a `?`, which a raw URL would misread.
+
Args:
key: Storage key (without scheme prefix).
Returns:
Public URL for the object.
"""
- return f"https://storage.googleapis.com/{self._bucket_name}/{key}"
+ return f"https://storage.googleapis.com/{self._bucket_name}/{quote(key, safe='/~')}"
def _generate_signed_url_sync(self, key: str) -> str | None:
"""Synchronous implementation of signed URL generation for use with to_thread.
diff --git a/pipelex/tools/storage/local_storage_provider.py b/pipelex/tools/storage/local_storage_provider.py
index a38f29161..aa0c5bf80 100644
--- a/pipelex/tools/storage/local_storage_provider.py
+++ b/pipelex/tools/storage/local_storage_provider.py
@@ -33,7 +33,7 @@ class LocalStorageProvider(StorageProviderAbstract):
The resolved absolute path.
Raises:
- StorageInvalidUriError: If the key is invalid (absolute path or path traversal).
+ StorageInvalidUriError: If the key is invalid (a NUL byte, an absolute path or path traversal).
"""
relative_path = Path(key)
@@ -41,6 +41,11 @@ class LocalStorageProvider(StorageProviderAbstract):
msg = f"Invalid key '{key}': absolute paths are not allowed"
raise StorageInvalidUriError(msg)
+ # A NUL byte cannot name a file, and resolve() rejects it with a bare ValueError
+ if "\x00" in key:
+ msg = f"Invalid key {key!r}: a null byte is not allowed"
+ raise StorageInvalidUriError(msg)
+
resolved_path = (self._root_path / relative_path).resolve()
# Check for path traversal attempts
diff --git a/pipelex/tools/storage/s3_storage_provider.py b/pipelex/tools/storage/s3_storage_provider.py
index c0d21ce54..6e72202e4 100644
--- a/pipelex/tools/storage/s3_storage_provider.py
+++ b/pipelex/tools/storage/s3_storage_provider.py
@@ -1,6 +1,7 @@
import importlib.util
import inspect
from typing import Any
+from urllib.parse import quote
from typing_extensions import override
@@ -76,7 +77,11 @@ class S3StorageProvider(StorageProviderAbstract):
from botocore.config import Config # ruff: ignore[import-outside-top-level] - optional dependency, lazy import
endpoint_url = f"https://s3.{self._region}.amazonaws.com"
- config = Config(signature_version="s3v4") # pyright: ignore[reportUnknownArgumentType]
+ # botocore addresses path-style whenever an endpoint is given, which puts every link on the region's
+ # shared host. A content security policy can allow a bucket only by its own host, so pin the virtual
+ # style: `<bucket>.s3.<region>.amazonaws.com`. botocore still falls back to path-style for a bucket
+ # name that cannot be a hostname, a dotted one included.
+ config = Config(signature_version="s3v4", s3={"addressing_style": "virtual"}) # pyright: ignore[reportUnknownArgumentType]
return {
"service_name": "s3",
@@ -174,7 +179,14 @@ class S3StorageProvider(StorageProviderAbstract):
raise StorageS3Error(msg) from exc
def _make_public_url(self, key: str) -> str:
- """Build a public URL for an S3 object.
+ """Build an unsigned public URL for an S3 object, on the same host and path a signed one would name.
+
+ The URL is virtual-hosted on the bucket's regional host, except for a bucket name that cannot be a
+ hostname: a dotted name breaks the `*.s3.<region>.amazonaws.com` wildcard certificate over HTTPS, and a
+ legacy name with uppercase letters or an underscore is no hostname at all, so its URL is path-style on
+ the regional host. botocore's own test decides, so the two forms cannot disagree. The key is
+ percent-encoded as botocore signs it, since a caller's own upload can name a key holding a space,
+ a `#` or a `?`.
Args:
key: Storage key (without scheme prefix).
@@ -182,7 +194,12 @@ class S3StorageProvider(StorageProviderAbstract):
Returns:
Public URL for the object.
"""
- return f"https://{self._bucket_name}.s3.{self._region}.amazonaws.com/{key}"
+ from botocore.utils import check_dns_name # ruff: ignore[import-outside-top-level] - optional dependency, lazy import
+
+ encoded_key = quote(key, safe="/~")
+ if check_dns_name(self._bucket_name):
+ return f"https://{self._bucket_name}.s3.{self._region}.amazonaws.com/{encoded_key}"
+ return f"https://s3.{self._region}.amazonaws.com/{self._bucket_name}/{encoded_key}"
@override
async def public_url(self, uri: str) -> str | None:
diff --git a/tests/integration/pipelex/tools/storage/test_user_provided_image_storage.py b/tests/integration/pipelex/tools/storage/test_user_provided_image_storage.py
index ca9f4354b..dd5d81bc7 100644
--- a/tests/integration/pipelex/tools/storage/test_user_provided_image_storage.py
+++ b/tests/integration/pipelex/tools/storage/test_user_provided_image_storage.py
@@ -102,7 +102,8 @@ class TestUserProvidedImageStorage:
"""Test that HTTP URLs are passed through when fetch is disabled.
When is_fetch_remote_content_enabled=False, HTTP URLs should not be
- fetched and stored. They should be passed through unchanged.
+ fetched and stored. They should be passed through unchanged, the URL
+ becoming the image's own public_url.
"""
# Create ImageContent with HTTP URL
http_url = URLs.png_example_1
@@ -121,6 +122,7 @@ class TestUserProvidedImageStorage:
normalized_stuff = normalized_memory.get_stuff("remote_image")
assert isinstance(normalized_stuff.content, ImageContent)
assert normalized_stuff.content.url == http_url
+ assert normalized_stuff.content.public_url == http_url
@pytest.mark.usefixtures("mock_upload_local_content_enabled")
async def test_user_image_local_file_to_storage_when_upload_enabled(self) -> None:
diff --git a/tests/unit/pipelex/pipeline/test_input_normalizer.py b/tests/unit/pipelex/pipeline/test_input_normalizer.py
index da11b73cc..781388c89 100644
--- a/tests/unit/pipelex/pipeline/test_input_normalizer.py
+++ b/tests/unit/pipelex/pipeline/test_input_normalizer.py
@@ -70,7 +70,7 @@ class TestInputNormalizerUrlGuards:
assert "not a valid http(s) URL" in strict["message"]
async def test_well_formed_http_url_passes_through_unchanged(self, mocker: MockerFixture) -> None:
- """A well-formed http(s) url is not fetched or probed at shaping time."""
+ """A well-formed http(s) url is not fetched or probed at shaping time, and it becomes its own public_url."""
_patch_storage_and_config(mocker)
mock_get = mocker.patch("httpx.AsyncClient.get")
@@ -79,6 +79,7 @@ class TestInputNormalizerUrlGuards:
content = memory.get_stuff("document").content
assert isinstance(content, DocumentContent)
assert content.url == "https://example.com/file.pdf"
+ assert content.public_url == "https://example.com/file.pdf"
mock_get.assert_not_called()
async def test_blank_url_message_survives_strict_disclosure(self, mocker: MockerFixture) -> None:
@@ -126,6 +127,13 @@ class TestInputNormalizerUrlGuards:
with pytest.raises(PipelineInputContentError, match="cannot be read"):
await normalize_data_urls_to_storage(_memory_with_document(str(tmp_path)), storage_scope="test/scope")
+ async def test_path_with_null_byte_raises_input_error(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """A NUL byte makes the path unusable: the read raises ValueError, not OSError, and it must still be an input error."""
+ _patch_storage_and_config(mocker)
+
+ with pytest.raises(PipelineInputContentError, match="cannot be read"):
+ await normalize_data_urls_to_storage(_memory_with_document(f"{tmp_path}/a\x00b.pdf"), storage_scope="test/scope")
+
async def test_missing_file_raises_input_error(self, mocker: MockerFixture, tmp_path: Path) -> None:
_patch_storage_and_config(mocker)
diff --git a/tests/unit/pipelex/pipeline/test_input_normalizer_public_url.py b/tests/unit/pipelex/pipeline/test_input_normalizer_public_url.py
new file mode 100644
index 000000000..3e447e577
--- /dev/null
+++ b/tests/unit/pipelex/pipeline/test_input_normalizer_public_url.py
@@ -0,0 +1,119 @@
+from typing import Any
+
+import pytest
+from pytest_mock import MockerFixture
+
+from pipelex.core.concepts.concept_factory import ConceptFactory
+from pipelex.core.concepts.native.concept_native import NativeConceptCode
+from pipelex.core.memory.working_memory import WorkingMemory
+from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory
+from pipelex.core.stuffs.document_content import DocumentContent
+from pipelex.core.stuffs.image_content import ImageContent
+from pipelex.core.stuffs.stuff_factory import StuffFactory
+from pipelex.pipeline.exceptions import PipelineInputContentError
+from pipelex.pipeline.input_normalizer import NormalizableContent, normalize_data_urls_to_storage
+from pipelex.tools.storage.exceptions import StorageInvalidUriError
+from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract
+
+STORED_INPUT_URI = "pipelex-storage://org/uploads/moodboard.png"
+FRESH_SIGNED_URL = "https://pipelex-app-dev.s3.us-west-2.amazonaws.com/org/uploads/moodboard.png?X-Amz-Signature=fresh"
+STALE_SIGNED_URL = "https://pipelex-app-dev.s3.us-west-2.amazonaws.com/org/uploads/moodboard.png?X-Amz-Signature=expired"
+HTTP_INPUT_URL = "https://example.com/moodboard.png"
+CALLER_PUBLIC_URL = "https://cdn.example.com/moodboard.png"
+
+CONTENT_CLASSES = [ImageContent, DocumentContent]
+
+
+def _memory_with_content(content: NormalizableContent) -> WorkingMemory:
+ native_concept_code = NativeConceptCode.IMAGE if isinstance(content, ImageContent) else NativeConceptCode.DOCUMENT
+ stuff = StuffFactory.make_stuff(
+ concept=ConceptFactory.make_native_concept(native_concept_code=native_concept_code),
+ content=content,
+ name="visual",
+ )
+ return WorkingMemoryFactory.make_from_single_stuff(stuff)
+
+
+async def _normalized_content(content: NormalizableContent) -> Any:
+ memory = await normalize_data_urls_to_storage(_memory_with_content(content), storage_scope="test/scope")
+ return memory.get_stuff("visual").content
+
+
[email protected](loop_scope="class")
+class TestInputNormalizerPublicUrl:
+ @pytest.fixture
+ def mock_storage(self, mocker: MockerFixture) -> Any:
+ """A storage provider whose signing returns a fresh link, installed where the normalizer looks it up."""
+ storage = mocker.Mock(spec=StorageProviderAbstract)
+ storage.public_url = mocker.AsyncMock(return_value=FRESH_SIGNED_URL)
+ mocker.patch("pipelex.pipeline.input_normalizer.get_storage_provider", return_value=storage)
+ return storage
+
+ @pytest.mark.parametrize("content_class", CONTENT_CLASSES)
+ async def test_stored_reference_gets_a_signed_public_url(self, mock_storage: Any, content_class: type[NormalizableContent]) -> None:
+ """A pipelex-storage:// input is signed through the storage provider, and its url stays the durable reference."""
+ normalized = await _normalized_content(content_class(url=STORED_INPUT_URI))
+
+ assert isinstance(normalized, content_class)
+ assert normalized.url == STORED_INPUT_URI
+ assert normalized.public_url == FRESH_SIGNED_URL
+ mock_storage.public_url.assert_awaited_once_with(uri=STORED_INPUT_URI)
+ mock_storage.store.assert_not_called()
+
+ @pytest.mark.parametrize("content_class", CONTENT_CLASSES)
+ @pytest.mark.usefixtures("mock_storage")
+ async def test_stored_reference_replaces_a_carried_public_url(self, content_class: type[NormalizableContent]) -> None:
+ """A link carried beside a reference, as a previous run's output passed back in carries one, may have expired: it is re-signed."""
+ normalized = await _normalized_content(content_class(url=STORED_INPUT_URI, public_url=STALE_SIGNED_URL))
+
+ assert normalized.url == STORED_INPUT_URI
+ assert normalized.public_url == FRESH_SIGNED_URL
+
+ @pytest.mark.parametrize("content_class", CONTENT_CLASSES)
+ async def test_stored_reference_keeps_its_link_when_the_provider_has_none(
+ self,
+ mock_storage: Any,
+ content_class: type[NormalizableContent],
+ ) -> None:
+ """A provider that cannot link, in-memory storage for one, leaves whatever link the input carried."""
+ mock_storage.public_url.return_value = None
+
+ carrying = await _normalized_content(content_class(url=STORED_INPUT_URI, public_url=STALE_SIGNED_URL))
+ bare = await _normalized_content(content_class(url=STORED_INPUT_URI))
+
+ assert carrying.public_url == STALE_SIGNED_URL
+ assert bare.public_url is None
+
+ @pytest.mark.parametrize("content_class", CONTENT_CLASSES)
+ async def test_stored_reference_the_provider_refuses_is_an_input_error(
+ self,
+ mock_storage: Any,
+ content_class: type[NormalizableContent],
+ ) -> None:
+ """A reference the provider refuses as a key, a path escaping local storage for one, is the caller's input fault."""
+ mock_storage.public_url.side_effect = StorageInvalidUriError("Invalid key '../../etc/passwd': path traversal detected")
+
+ with pytest.raises(PipelineInputContentError, match="cannot be linked") as exc_info:
+ await _normalized_content(content_class(url="pipelex-storage://../../etc/passwd"))
+
+ assert isinstance(exc_info.value.__cause__, StorageInvalidUriError)
+
+ @pytest.mark.parametrize("content_class", CONTENT_CLASSES)
+ async def test_http_url_is_its_own_public_url(self, mock_storage: Any, content_class: type[NormalizableContent]) -> None:
+ """An http(s) input with no public_url is already public: the url itself becomes the link, with no storage call."""
+ normalized = await _normalized_content(content_class(url=HTTP_INPUT_URL))
+
+ assert isinstance(normalized, content_class)
+ assert normalized.url == HTTP_INPUT_URL
+ assert normalized.public_url == HTTP_INPUT_URL
+ mock_storage.public_url.assert_not_called()
+ mock_storage.store.assert_not_called()
+
+ @pytest.mark.parametrize("content_class", CONTENT_CLASSES)
+ @pytest.mark.usefixtures("mock_storage")
+ async def test_http_url_keeps_a_caller_supplied_public_url(self, content_class: type[NormalizableContent]) -> None:
+ """A caller who names a different public link for an http(s) input keeps it."""
+ normalized = await _normalized_content(content_class(url=HTTP_INPUT_URL, public_url=CALLER_PUBLIC_URL))
+
+ assert normalized.url == HTTP_INPUT_URL
+ assert normalized.public_url == CALLER_PUBLIC_URL
diff --git a/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py b/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py
index 7c1e3f6a5..187771213 100644
--- a/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py
+++ b/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py
@@ -191,6 +191,18 @@ class TestGcpStorageProvider:
expected_url = f"https://storage.googleapis.com/{gcp_bucket_name}/{key}"
assert display == expected_url
+ async def test_public_url_percent_encodes_the_key_when_signed_urls_disabled(
+ self,
+ gcp_provider_no_signed_urls: GcpStorageProvider,
+ gcp_bucket_name: str,
+ ) -> None:
+ """A key holding a space, '+', '#' or '?' is percent-encoded as GCS signs it, so the link names the object and not a fragment or query."""
+ uri = f"{PIPELEX_STORAGE_SCHEME}org/uploads/My Photo+#1?.png"
+
+ display = await gcp_provider_no_signed_urls.public_url(uri=uri)
+
+ assert display == f"https://storage.googleapis.com/{gcp_bucket_name}/org/uploads/My%20Photo%2B%231%3F.png"
+
async def test_public_url_returns_signed_url_when_signed_urls_enabled(
self,
gcp_provider_with_signed_urls: GcpStorageProvider,
diff --git a/tests/unit/pipelex/tools/storage/test_local_storage_provider.py b/tests/unit/pipelex/tools/storage/test_local_storage_provider.py
index 78a966724..dfdd585c3 100644
--- a/tests/unit/pipelex/tools/storage/test_local_storage_provider.py
+++ b/tests/unit/pipelex/tools/storage/test_local_storage_provider.py
@@ -117,6 +117,20 @@ class TestLocalStorageProvider:
assert "path traversal" in str(exc_info.value).lower()
+ async def test_key_with_null_byte_raises_invalid_uri(self, tmp_path: Path) -> None:
+ """A key holding a NUL byte cannot name a file, so it is refused like any other invalid key.
+
+ `Path.resolve()` raises a bare ValueError on it, which would otherwise escape a
+ caller-supplied storage reference as an internal error.
+ """
+ provider = LocalStorageProvider(root_path=tmp_path)
+ uri = f"{PIPELEX_STORAGE_SCHEME}a\x00b.png"
+
+ with pytest.raises(StorageInvalidUriError, match="null byte"):
+ await provider.public_url(uri=uri)
+ with pytest.raises(StorageInvalidUriError, match="null byte"):
+ await provider.load(uri=uri)
+
async def test_store_empty_bytes(self, tmp_path: Path) -> None:
"""Test storing and loading empty bytes."""
provider = LocalStorageProvider(root_path=tmp_path)
diff --git a/tests/unit/pipelex/tools/storage/test_s3_storage_provider_url_form.py b/tests/unit/pipelex/tools/storage/test_s3_storage_provider_url_form.py
new file mode 100644
index 000000000..74a4c3375
--- /dev/null
+++ b/tests/unit/pipelex/tools/storage/test_s3_storage_provider_url_form.py
@@ -0,0 +1,113 @@
+from pathlib import Path
+from urllib.parse import urlsplit
+
+import pytest
+
+from pipelex.tools.storage.s3_storage_provider import S3StorageProvider
+from pipelex.tools.storage.storage_provider_abstract import PIPELEX_STORAGE_SCHEME
+
+# botocore reads these at session creation; any of them set on the developer's machine could change the addressing
+_AWS_ENV_VARS_TO_CLEAR = (
+ "AWS_PROFILE",
+ "AWS_DEFAULT_PROFILE",
+ "AWS_SESSION_TOKEN",
+ "AWS_SECURITY_TOKEN",
+ "AWS_DEFAULT_REGION",
+ "AWS_REGION",
+ "AWS_ENDPOINT_URL",
+ "AWS_ENDPOINT_URL_S3",
+ "AWS_USE_DUALSTACK_ENDPOINT",
+ "AWS_USE_FIPS_ENDPOINT",
+ "AWS_S3_US_EAST_1_REGIONAL_ENDPOINT",
+)
+URL_FORM_TEST_REGION = "us-west-2"
+URL_FORM_PLAIN_BUCKET = "pipelex-app-dev"
+URL_FORM_DOTTED_BUCKET = "my.dotted.bucket"
+# Only a legacy us-east-1 bucket can carry uppercase letters or an underscore; botocore signs it path-style
+URL_FORM_LEGACY_BUCKET = "Legacy_Bucket"
+URL_FORM_PLAIN_KEY = "runs/abc/moodboard.png"
+# A caller's own upload can name its key freely: botocore percent-encodes what a URL would misread
+URL_FORM_SPECIAL_KEY = "org/uploads/My Photo+#1?.png"
+
+
[email protected](loop_scope="class")
+class TestS3StorageProviderUrlForm:
+ """The host a link names, presigned through real botocore rather than a mock.
+
+ Presigning is computed locally and makes no network call, so dummy credentials are enough.
+ A content security policy names an origin, so the host is the contract: a bucket's own host
+ can be allowed alone, the shared regional endpoint cannot.
+ """
+
+ @pytest.fixture
+ def isolated_aws_environment(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """Give botocore dummy credentials and keep the developer's own AWS configuration out of the test."""
+ for env_var in _AWS_ENV_VARS_TO_CLEAR:
+ monkeypatch.delenv(env_var, raising=False)
+ empty_aws_file = tmp_path / "empty_aws_file"
+ empty_aws_file.write_text("")
+ monkeypatch.setenv("AWS_CONFIG_FILE", str(empty_aws_file))
+ monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", str(empty_aws_file))
+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIDEXAMPLE")
+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "dummy-secret-for-local-presigning")
+
+ @classmethod
+ def _make_provider(cls, *, bucket_name: str, signed_urls_lifespan: int | None) -> S3StorageProvider:
+ return S3StorageProvider(
+ bucket_name=bucket_name,
+ region=URL_FORM_TEST_REGION,
+ signed_urls_lifespan=signed_urls_lifespan,
+ )
+
+ @pytest.mark.usefixtures("isolated_aws_environment")
+ async def test_signed_url_is_on_the_bucket_regional_host(self) -> None:
+ """A presigned link names the bucket's own regional host, not the region's shared endpoint."""
+ key = "runs/abc/moodboard.png"
+ provider = self._make_provider(bucket_name=URL_FORM_PLAIN_BUCKET, signed_urls_lifespan=3600)
+
+ signed_url = await provider.public_url(uri=f"{PIPELEX_STORAGE_SCHEME}{key}")
+
+ assert signed_url is not None
+ parsed = urlsplit(signed_url)
+ assert parsed.scheme == "https"
+ assert parsed.netloc == f"{URL_FORM_PLAIN_BUCKET}.s3.{URL_FORM_TEST_REGION}.amazonaws.com"
+ assert parsed.path == f"/{key}"
+ assert "X-Amz-Signature=" in parsed.query
+
+ @pytest.mark.usefixtures("isolated_aws_environment")
+ async def test_signed_url_for_a_dotted_bucket_is_path_style_on_the_regional_host(self) -> None:
+ """A dotted bucket name breaks the wildcard certificate, so its link stays path-style on the regional host."""
+ key = "runs/abc/moodboard.png"
+ provider = self._make_provider(bucket_name=URL_FORM_DOTTED_BUCKET, signed_urls_lifespan=3600)
+
+ signed_url = await provider.public_url(uri=f"{PIPELEX_STORAGE_SCHEME}{key}")
+
+ assert signed_url is not None
+ parsed = urlsplit(signed_url)
+ assert parsed.scheme == "https"
+ assert parsed.netloc == f"s3.{URL_FORM_TEST_REGION}.amazonaws.com"
+ assert parsed.path == f"/{URL_FORM_DOTTED_BUCKET}/{key}"
+
+ @pytest.mark.parametrize("bucket_name", [URL_FORM_PLAIN_BUCKET, URL_FORM_DOTTED_BUCKET, URL_FORM_LEGACY_BUCKET])
+ @pytest.mark.parametrize("key", [URL_FORM_PLAIN_KEY, URL_FORM_SPECIAL_KEY])
+ @pytest.mark.usefixtures("isolated_aws_environment")
+ async def test_signed_and_unsigned_urls_name_the_same_host_and_path(self, bucket_name: str, key: str) -> None:
+ """An unsigned link never names a host or a path the signed link would not."""
+ uri = f"{PIPELEX_STORAGE_SCHEME}{key}"
+ signing_provider = self._make_provider(bucket_name=bucket_name, signed_urls_lifespan=3600)
+ unsigned_provider = self._make_provider(bucket_name=bucket_name, signed_urls_lifespan=None)
+
+ signed_url = await signing_provider.public_url(uri=uri)
+ unsigned_url = await unsigned_provider.public_url(uri=uri)
+
+ assert signed_url is not None
+ assert unsigned_url is not None
+ parsed_signed = urlsplit(signed_url)
+ parsed_unsigned = urlsplit(unsigned_url)
+ assert (parsed_unsigned.scheme, parsed_unsigned.netloc, parsed_unsigned.path) == (
+ parsed_signed.scheme,
+ parsed_signed.netloc,
+ parsed_signed.path,
+ )
+ assert parsed_unsigned.query == ""
+ assert parsed_unsigned.fragment == ""
diff --git a/wip/sign-publicurl-virtual-hosted/design.md b/wip/sign-publicurl-virtual-hosted/design.md
new file mode 100644
index 000000000..bc5c04148
--- /dev/null
+++ b/wip/sign-publicurl-virtual-hosted/design.md
@@ -0,0 +1,76 @@
+---
+status: active
+item: L-260925-94110e
+---
+
+# Sign `public_url` virtual-hosted, and give every normalized input a `public_url`
+
+## The problem, verified
+
+The item's claim holds. `S3StorageProvider._get_client_config` (`pipelex/tools/storage/s3_storage_provider.py:70-86`) builds every client with an explicit `endpoint_url = https://s3.<region>.amazonaws.com` and a `Config(signature_version="s3v4")` that names no addressing style. With an endpoint given and no style, botocore signs path-style, so every presigned `public_url` lands on the region's shared host, `https://s3.<region>.amazonaws.com/<bucket>/<key>?X-Amz-…`. A content security policy source is an origin, that origin is shared by every bucket in the region, and the MCP hosts drop the path from a path-scoped source, so no view can allow the runtime's links without allowing every bucket anyone owns in the region.
+
+The endpoint pin has been there since the S3 provider first landed (the v0.18.0 release commit, `f069d185b`), with no recorded reason.
+
+The measurement below was taken in this repo's venv (botocore 1.40.61, aioboto3 15.5.0), presigning `get_object` with dummy credentials; presigning makes no network call.
+
+| Client configuration | Bucket `pipelex-app-dev` | Bucket `my.dotted.bucket` |
+| --- | --- | --- |
+| Today: regional endpoint, no style | `s3.us-west-2.amazonaws.com/pipelex-app-dev/…` | `s3.us-west-2.amazonaws.com/my.dotted.bucket/…` |
+| Regional endpoint, `addressing_style: virtual` | `pipelex-app-dev.s3.us-west-2.amazonaws.com/…` | `s3.us-west-2.amazonaws.com/my.dotted.bucket/…` |
+| No endpoint, no style | `pipelex-app-dev.s3.amazonaws.com/…` | `s3.us-west-2.amazonaws.com/my.dotted.bucket/…` |
+| No endpoint, `addressing_style: virtual` | `pipelex-app-dev.s3.us-west-2.amazonaws.com/…` | `s3.us-west-2.amazonaws.com/my.dotted.bucket/…` |
+
+Two facts come out of it. Adding the virtual style to the existing configuration yields the bucket's own regional host, which the hosted console's views already allow (`RUN_OUTPUT_SOURCES` in `pipelex-mcp/packages/console/src/hosted/app-buckets.ts:45` names both the global and the regional virtual-hosted origin of each app bucket). And a bucket name containing a dot can never be virtual-hosted over HTTPS, because the name breaks the `*.s3.<region>.amazonaws.com` wildcard certificate, so botocore falls back to path-style for it whatever the style says.
+
+The unsigned fallback, `_make_public_url` (`s3_storage_provider.py:176-185`), already builds the virtual-hosted form, so today the signed and unsigned links disagree. It would build that form for a dotted bucket too, where it fails the TLS handshake, but the storage configuration refuses a bucket name containing a dot before the provider is built, so only a provider constructed directly can meet one; the fallback below covers that case anyway.
+
+## Nothing depends on the path-style form
+
+The workspace was swept for consumers of the runtime's link shape:
+
+- **pipelex-mcp** refuses the path-style host on purpose and allows both virtual-hosted forms (`app-buckets.ts`, with a test asserting the regional form is allowed). Its comments in `app-buckets.ts`, `packages/core/src/capabilities/run.ts` and `packages/console/src/views/run-results.ts` describe the runtime as signing path-style; they go stale once the hosted plane runs this fix, which is a follow-up for that repo.
+- **pipelex-app** proxies whatever URL the platform resolves (`/api/assets`) and parses none; its tests use path-style URLs only as opaque fixtures.
+- **pipelex-server** signs its own links independently, with boto3's default endpoint (the global virtual-hosted form), and never parses the runtime's. Its storage-resolution doc already shows the regional virtual-hosted form in an example.
+- **The hosted plane's network rules** were checked, and none of them depends on the S3 hostname, so moving the runtime's own `get_object` and `put_object` calls to the bucket's host changes nothing there.
+- **Bucket policies and CORS rules** apply to a bucket regardless of the addressing style a request used.
+
+## Decisions
+
+### One client form: virtual-hosted on the bucket's regional host
+
+`_get_client_config` keeps its regional endpoint and adds `s3={"addressing_style": "virtual"}` to its `Config`. Every call the provider makes, the reads, the writes and the presigning, then addresses `https://<bucket>.s3.<region>.amazonaws.com`.
+
+Two alternatives were weighed and rejected. Dropping the endpoint pin without a style would sign on the global host, `<bucket>.s3.amazonaws.com`, the platform's form, which the console also allows; but the global host reaches a bucket outside `us-east-1` only through DNS that AWS warns can answer with a temporary redirect for a newly created bucket, and the regional host has no such caveat. Applying the virtual style only to the presigning client would keep the runtime's own traffic on the shared host and limit the change to the link, at the price of two client configurations for one bucket; with nothing on the hosted plane depending on the hostname, the smaller surface wins, and virtual-hosted is AWS's recommended addressing in any case.
+
+The risk this accepts is a self-hosted deployment whose egress proxy allows only `s3.<region>.amazonaws.com`: its reads and writes would start failing. The changelog entry names it, so an operator can widen the rule to `*.s3.<region>.amazonaws.com`.
+
+### Signed and unsigned links follow one rule
+
+Both forms are virtual-hosted on the bucket's regional host, except for a bucket name that cannot be a hostname, which falls back to path-style on the regional host: a legacy name with uppercase letters or an underscore, which the configuration accepts, and a dotted one, which it refuses before the provider is built. botocore applies that rule to the signed form by itself; `_make_public_url` applies it through botocore's own `check_dns_name`, so an unsigned link never names a host the signed link would not. The unsigned form percent-encodes the key as botocore does, since a caller's own upload can name a key holding a space, a `#` or a `?`, and the GCS provider's unsigned form gets the same encoding. A test pins the two forms to the same host and path for a plain, a dotted and a legacy bucket name, with a plain key and one holding those characters.
+
+### Every normalized input carries a `public_url`
+
+The item's second observation, the moodboard rendering as `src="None"`, traces to the runtime, not the method. `_normalize_url_content` (`pipelex/pipeline/input_normalizer.py:204`) fills `public_url` for two of the four input forms, the `data:` URL and the local path, each of which it stores and then signs. It passes an `http(s)` URL and a `pipelex-storage://` reference through untouched (`input_normalizer.py:286`), so their `public_url` stays `None`, and Jinja renders `{{ moodboard.public_url }}` as the string `None`. A method author cannot know which form a caller used, and the hosted console's upload grant produces exactly the `pipelex-storage://` form, so the fallback cannot be left to each method.
+
+The normalizer therefore fills `public_url` for the two remaining forms, mirroring what `GeneratedContentFactory` already does for produced images (`pipelex/cogt/content_generation/generated_content_factory.py:181-205`):
+
+- **A `pipelex-storage://` reference** gets a link signed through the storage provider, always, even when the input already carries a `public_url`. The reference is the durable fact and the link a derivative with an expiry, and the usual way an input arrives with both is a previous run's output passed back in, whose link may have expired.
+- **An `http(s)` URL** gets `public_url = url` when the input carries none, since that URL is already the public one; a caller-supplied `public_url` is kept.
+
+Signing a reference is no wider than reading it, which the operators consuming the input already do. On the hosted plane the platform refuses, before any run starts, a `pipelex-storage://` reference outside the caller's organization, so no link to another tenant's file can be minted this way.
+
+A run with `is_normalize_data_urls_to_storage` off, or with mock inputs, skips normalization entirely and keeps today's behaviour; that switch governs the whole normalizer and this change does not widen it.
+
+`DocumentContent` goes through the same function and gets the same treatment.
+
+## What this does not fix
+
+- **A report reopened after the link's lifespan.** A baked link still expires (`signed_urls_lifespan_seconds = 3600`, `pipelex/pipelex.toml:23`). Durable references in HTML markup and a renderer that resolves them are L-260918-4fd772 in this repo, with the rendering side in `mthds-form` and the console.
+- **The webapp.** The item says a virtual-hosted link fixes a fresh render "on every surface"; it does not reach `app.pipelex.com`. The webapp's CSP allows images only from `'self'`, `data:` and `blob:` (`pipelex-app/src/lib/csp.ts:61`), and an HTML output renders in a `srcdoc` frame (`mthds-form/src/react/html-preview.tsx:214`), which inherits that policy, so an S3 image inside an HTML output is blocked there in either addressing form. The fix reaches the MCP console's views and every surface with no CSP: a saved HTML file, an email, a terminal.
+- **Jinja's rendering of `None` as `None`.** Once every normalized input carries a `public_url`, the case stops arising for inputs, and a template author who wants a fallback writes one.
+
+## Shipping and acceptance
+
+The change ships as a `pipelex` release. The hosted plane runs it once the pins move: `pipelex-api` pins `pipelex`, and `pipelex-server` pins both `pipelex-api` (`api-hosted/pyproject.toml`) and `pipelex` itself (`temporal/pyproject.toml`, `daytona-sandbox/pyproject.toml`). Those moves ride the ordinary release train.
+
+In this repo, acceptance is the unit test that presigns through real botocore and asserts the host, which a revert of the one-line style change turns red. On the hosted plane, acceptance is a fresh run of the catalog method "Fashion designer" on the dev console once the pins carry the release: every `<img src>` in its `inner_html` sits on `https://pipelex-app-dev.s3.us-west-2.amazonaws.com`, the moodboard's included, and claude.ai paints every picture. That check, and the stale comments, belong to the pipelex-mcp follow-up filed with this design.
diff --git a/wip/sign-publicurl-virtual-hosted/plan.md b/wip/sign-publicurl-virtual-hosted/plan.md
new file mode 100644
index 000000000..17b7c6cca
--- /dev/null
+++ b/wip/sign-publicurl-virtual-hosted/plan.md
@@ -0,0 +1,89 @@
+---
+status: active
+item: L-260925-94110e
+---
+
+# Plan: sign `public_url` virtual-hosted, and give every normalized input a `public_url`
+
+The decisions and their evidence are in [`design.md`](design.md). One branch, one pull request, two phases with a checkpoint at the end. The work is test-first: each phase writes its failing tests, watches them fail for the right reason, then changes the code.
+
+## Phase 1 — The S3 provider signs on the bucket's own host
+
+Tests, in a new module `tests/unit/pipelex/tools/storage/test_s3_storage_provider_url_form.py` (the repo allows one test class per module), as a class that does not use the `mock_aioboto3` fixture, because the point is to exercise botocore's real addressing logic:
+
+- [x] Presigning through a real aioboto3 session, with dummy credentials set through `monkeypatch` and `AWS_CONFIG_FILE` and `AWS_SHARED_CREDENTIALS_FILE` pointed at an empty file so the developer's own AWS configuration cannot leak in, yields a link whose host is `<bucket>.s3.<region>.amazonaws.com` and whose path is `/<key>`. Presigning makes no network call, so this stays a unit test.
+- [x] The same presigning for a dotted bucket name yields the path-style link on `s3.<region>.amazonaws.com`.
+- [x] For both kinds of bucket name, the signed link and the unsigned one (`signed_urls_lifespan=None`) name the same host and the same path.
+- [x] Mutation check: remove the style from `_get_client_config` and watch the first test go red; restore the dotted-name branch of `_make_public_url` to the plain form and watch the third go red. Restore by editing, never with `git checkout`.
+
+Code, in `pipelex/tools/storage/s3_storage_provider.py`:
+
+- [x] `_get_client_config` adds `s3={"addressing_style": "virtual"}` to its `Config`, with a comment saying why the style is pinned: a CSP can name a bucket only by its own host, and botocore signs path-style whenever an endpoint is given.
+- [x] `_make_public_url` builds the path-style regional form for a bucket name containing a dot and the virtual-hosted regional form otherwise, with a comment naming the wildcard certificate as the reason.
+- [x] The existing mocked fixtures that fake a presigned link (`tests/unit/…/test_s3_storage_provider.py:38`, `tests/integration/pipelex/tools/storage/conftest.py:71`) already use the virtual-hosted regional form; confirm and leave them.
+
+Documentation:
+
+- [x] `docs/features/cloud-storage.md` says which URL form S3 links take, virtual-hosted on the bucket's regional host with the dotted-name exception, so an author writing a CSP knows the origin to allow.
+- [x] `CHANGELOG.md` under Unreleased: the S3 provider signs and fetches on the bucket's own regional host instead of the shared regional endpoint, and a self-hosted deployment whose egress rules name only `s3.<region>.amazonaws.com` must allow `*.s3.<region>.amazonaws.com`.
+
+Gates:
+
+- [x] `make agent-check`, with the changes staged first so the drift digest sees them; handle any drift contract the storage files trigger with `make drift-plan` and `make drift-ack`.
+
+## Phase 2 — Every normalized input carries a `public_url`
+
+Tests, in a new module `tests/unit/pipelex/pipeline/test_input_normalizer_public_url.py` beside `test_input_normalizer.py` (one test class per module), with the storage provider mocked as that module already does:
+
+- [x] An image input whose `url` is a `pipelex-storage://` reference comes out with the provider's signed link as `public_url` and its `url` unchanged.
+- [x] The same input already carrying a `public_url` comes out with the freshly signed link instead.
+- [x] An `http(s)` input with no `public_url` comes out with `public_url` equal to its `url`; one carrying a `public_url` keeps it.
+- [x] A `DocumentContent` input gets the same treatment, one case for each form.
+- [x] Update `test_well_formed_http_url_passes_through_unchanged` so it still asserts no network call and an unchanged `url`, and now asserts the filled `public_url`; do the same for `test_user_image_http_url_passthrough_when_fetch_disabled` in `tests/integration/pipelex/tools/storage/test_user_provided_image_storage.py`.
+- [x] Mutation check: drop each new branch in turn and watch its test go red.
+
+Code, in `pipelex/pipeline/input_normalizer.py`:
+
+- [x] The `ResolvedHttpUrl` branch of `_normalize_url_content` returns a copy with `public_url = url` when the input has none, after the syntax check it already runs.
+- [x] A `ResolvedPipelexStorage` branch replaces the pass-through at line 286: it signs through `storage.public_url(uri=content.url)` and returns a copy carrying the link.
+- [x] The function's docstring and the pass-through comment say what each form now gets.
+
+Knock-on checks:
+
+- [x] Run the tests that pretty-print `TextAndImagesContent` and structured inputs. The premise turned out wrong for `TextAndImagesContent`: the normalizer never reaches its images (see the deferral below), so its rendering does not change; the structured-input and rendering tests passed unchanged.
+- [x] Run the tests that snapshot a run's inputs or graph, since normalized inputs now carry one more field.
+
+Documentation:
+
+- [x] `docs/building-methods/concepts/native-concepts.md:79` and `:105` say the runtime fills `public_url` for every input it normalizes, a signed and therefore expiring link for a stored file and the URL itself for an `http(s)` one, and that a template baking it into HTML produces a report that stops loading once the link expires.
+- [x] `CHANGELOG.md` under Unreleased: inputs given as a `pipelex-storage://` reference or an `http(s)` URL now carry a `public_url`, so a template writing `{{ image.public_url }}` no longer renders `None`.
+
+## Checkpoint — ready for review
+
+- [x] `make agent-check` clean.
+- [x] `make agent-test` green.
+- [x] `/rev`, at the depth `ledger review-profile` derives: round 1 at profile 3 (cubic, Codex review, the official code-review at `low`), then round 2 at the `defects` bar over round 1's fixes, both recorded on the item.
+- [x] Record here what was decided during the build, any open question, and the last reviewed commit.
+
+### Decisions taken during the build
+
+- **Each new test class has its own module**, `test_s3_storage_provider_url_form.py` and `test_input_normalizer_public_url.py`, because the repo's test standard allows one test class per module.
+- **A provider that cannot link a stored reference leaves the link the input carried.** In-memory storage returns no link at all; erasing a carried link the runtime cannot replace would lose information for nothing.
+- **A reference the storage provider refuses as a key is an input error at normalization.** Signing now happens before the run, so the local provider's refusal of a path escaping its root surfaces there; it is raised as `PipelineInputContentError`, INPUT domain and not caller-facing, rather than as a bare storage error.
+- **The unsigned S3 link uses botocore's own `check_dns_name`** instead of a hand-written dot test, so a legacy bucket name with uppercase letters or an underscore falls back to path-style exactly as the signed link does. Both unsigned builders, S3 and GCS, percent-encode the key as their signed forms do. Both came out of review round 1.
+- **A NUL byte in a local input path or a local storage key is an input error.** `Path` rejects it with a bare `ValueError` rather than an `OSError`, so the local provider refuses such a key as `StorageInvalidUriError` and the normalizer's local-path branch catches `ValueError` beside `OSError`. The storage-reference branch made the first reachable before the run; the second predates this branch. Both came out of review round 2.
+- **The public design describes the hosted plane's network and tenancy checks by role.** `pipelex` is a public repository, so the specifics sit on the ledger item instead, and the commit that added this design was rewritten before any pull request so that no commit carries them.
+
+### Deferred
+
+- **The normalizer does not reach the images inside a `TextAndImagesContent`**, nor those in a `PageContent`'s `text_and_images`: `_normalize_value` recurses only into `StructuredContent`, `ListContent` and lists, and `TextAndImagesContent` is a plain `StuffContent`. Their `data:` URLs are left unstored and their `public_url` unfilled. The gap predates this branch; review round 1 confirmed it, and the changelog and docs now say which placements are reached. Reaching them is a recursion branch in `_normalize_value` and its tests.
+- **The storage configuration refuses a dotted bucket name**, for S3 and GCS alike, so the S3 provider's path-style fallback for one is reachable only by a provider constructed directly. Review round 2 proposed accepting dotted names; that is a feature choice, and one the shared GCS check would need too, so the docs and changelog now say the configuration refuses them, and the fallback stays as a defensive measure.
+- **The design still names a few paths inside internal repositories**: the webapp's CSP source file and the hosted plane's member manifests. Review round 2 raised it; nothing named is secret, and rewording them by role is hygiene rather than a defect at that round's bar.
+
+### Last reviewed commit
+
+Round 1 reviewed the branch at the commit titled "Mark the campaign active and tick the built phases", and round 2 at the commit titled "Unsigned storage links encode their key and match botocore's host rule", each before its round's fixes.
+
+## After the merge
+
+`/ledger-land` closes this item on the merge. The hosted acceptance, a fresh "Fashion designer" run on the dev console painting every picture from the bucket's regional host, waits for the release train to carry the change into `pipelex-api` and `pipelex-server`, and is recorded on the pipelex-mcp follow-up along with the comments there that still call the runtime's link path-style.