← Back to Pull requests

Encode URL serialization policies in the type system #2711

Closed
zaniebot closed this pull request without merging on Oct 15, 2026 17:34 UTC
View on GitHub
zaniebot zaniebot commented on Oct 14, 2026 15:51 UTC
Author

SafeUrl currently serializes the full URL, so fields can persist credentials without an explicit choice. Add a type-level policy that defaults to Unserializable; Stripped removes sensitive userinfo while retaining the complete query, and Raw serializes the full parsed URL. Display and Debug remain redacted. Index URLs in pylock.toml and publish URLs in tool receipts use Stripped.

This is an alternative to astral-sh/uv#22356, astral-sh/uv#22357, and astral-sh/uv#22358, combined in #2712. Stripped and Raw follow the same serialization rules as PersistSafeUrl and CredentialPersistingUrl. Using SafeUrl<P> carries the policy through VerbatimUrl, stored fields, and transformations such as join; shared implementations are generic over the policy. The inherent serialize and serialize_internal methods prevent fallback through Deref; the latter requires Raw. The comparison stack also changes how DirectUrl metadata is parsed and written; this PR retains its string fields and existing behavior.

Stacked on #2721.

Diff: 935 lines (+725 / -210) across 30 files Reviewer: zanieb Review duration: 1543m
All Vouch review confidence checks passed
Residual risk 0.12 = Change Risk (0.72) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.72 · 935 lines diff across 30 files
0.72
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.72 · 5 substantive comment(s)
0.72
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
83%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Mass File Touch mass_file_touch
0.080
Real PR Conversation Timeline
7 items
zanieb zanieb commented on code on Oct 14, 2026 16:10 UTC
Code Review
crates/uv-configuration/src/proxy_url.rs:1
@@ -119,7 +120,9 @@ impl Serialize for ProxyUrl {
     where
         S: serde::ser::Serializer,
     {
-        serializer.serialize_str(self.as_url().as_str())
+        self.as_url()
+            .with_policy_ref(PreserveUrl)
+            .serialize(serializer)

Shouldn't this use SafeUrl<PreserveUrl> at ProxyUrl(DisplaySafeUrl); instead? We should be replacing DisplaySafeUrl entirely

codspeed[bot] codspeed[bot] commented on Oct 14, 2026 16:34 UTC
Bot

<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

Merging this PR will degrade performance by 13.01%

<details>
<summary>:warning: <b>8 benchmarks spent significant time in system calls</b></summary>

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

> Measurement and system calls

> - ` discover_workspace_from_all_members_with_excludes

- discover_workspace_from_all_members

- resolve_warm_jupyter

- run_python_version_synthetic_workspace

- install_wheel_many_files

- resolve_warm_airflow

- unpack_sdist_many_files

- resolve_warm_jupyter_universal

</details>
<details>
<summary>:warning: <b>Different runtime environments detected</b></summary>

Some benchmarks with significant performance changes were compared across different runtime environments,

which may affect the accuracy of the results.

> Open the report in CodSpeed to investigate

</details>

❌ 1 regressed benchmark
✅ 68 untouched benchmarks
⏩ 35 skipped benchmarks[^skipped]

[!WARNING]

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ❌ :warning: | Simulation |
discover_workspace_from_all_members_with_excludes | 142.7 ms | 164.1 ms | -13.01% |

[!TIP]

Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.

---

<sub>Comparing <code>zaniebot/safe-url-policies-20261014</code> (3dff9d7) with <code>zaniebot/safe-url-rename-20261014</code> (f85db54)</sub>

<a href="https://app.codspeed.io/astral-sh/uv-dev/branches/zaniebot%2Fsafe-url-policies-20261014?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>

[^skipped]: 35 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

astral-automations-bot[bot] astral-automations-bot[bot] commented on code on Oct 14, 2026 16:59 UTC
Code Review
crates/uv-redacted/src/lib.rs:1
@@ -240,32 +271,64 @@ impl DisplaySafeUrl {
     }
 }
 
-impl Deref for DisplaySafeUrl {
+impl SafeUrl<Raw> {
+    /// Serialize the complete URL using the internal representation of the `Url` struct.
+    ///
+    /// A field using this serializer must declare the [`Raw`] policy:
+    ///
+    /// ```compile_fail
+    /// use uv_redacted::{SafeUrl, policy::Raw};
+    ///
+    /// #[derive(serde::Serialize)]
+    /// struct CachedUrl {
+    ///     #[serde(serialize_with = "SafeUrl::<Raw>::serialize_internal")]
+    ///     url: SafeUrl,
+    /// }
+    /// ```
+    #[inline]
+    pub fn serialize_internal<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+    where
+        S: serde::Serializer,
+    {
+        self.0.serialize_internal(serializer)
+    }
+
+    /// Deserialize the internal representation of the `Url` struct.
+    #[inline]
+    pub fn deserialize_internal<'de, D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: serde::Deserializer<'de>,
+    {
+        Ok(Self(Url::deserialize_internal(deserializer)?, PhantomData))
+    }
+}
+
+impl<P: SerializationPolicy> Deref for SafeUrl<P> {
     type Target = Url;
 
     fn deref(&self) -> &Self::Target {
         &self.0

[P3] Guard serialization methods against implicit Deref fallback

With serde::Serialize in scope, SafeUrl<Unserializable>.serialize(serializer) still compiles: method lookup dereferences to Url::serialize and writes the complete URL. Likewise, serialize_internal falls through to Url for both Unserializable and Stripped. Consequently, accidentally removing the policy from a hand-written serializer such as ProxyUrl::serialize would silently retain raw persistence, although the derive-based compile-fail tests pass. Consider shadowing these methods with policy-bound inherent methods and adding compile-fail coverage for method-call syntax. This would require an explicit raw-URL conversion to bypass the policy.

zanieb zanieb commented on code on Oct 15, 2026 14:52 UTC
Code Review
crates/uv-distribution-types/src/index_url.rs:1
@@ -201,7 +202,7 @@ impl serde::ser::Serialize for IndexUrl {
     where
         S: serde::ser::Serializer,
     {
-        self.inner().without_credentials().serialize(serializer)
+        self.inner().serialize(serializer)

love to see it

zanieb zanieb commented on code on Oct 15, 2026 14:55 UTC
Code Review
crates/uv-pypi-types/src/direct_url.rs:1
@@ -2,22 +2,33 @@ use std::collections::BTreeMap;
 use std::path::{Path, PathBuf};
 
 use serde::{Deserialize, Serialize};
+use url::Url;
+use uv_redacted::policy::Stripped;
 use uv_redacted::{SafeUrl, SafeUrlError};
 
 use crate::{HashAlgorithm, Hashes};
 
 /// Metadata for a distribution that was installed via a direct URL.
 ///
 /// See: <https://packaging.python.org/en/latest/specifications/direct-url-data-structure/>
+pub type ParsedDirectUrl = DirectUrl<SafeUrl<Stripped>>;
+
+/// Direct URL metadata whose URL has not yet been parsed.
+#[derive(Deserialize)]
+#[serde(transparent)]
+// The unparsed URL may contain credentials, so this wrapper omits `Serialize` and `Debug`.
+pub struct DirectUrlMetadata(DirectUrl<String>);

Hm, not sure why this exist, need to look into it

astral-automations-bot[bot] astral-automations-bot[bot] commented on Oct 15, 2026 17:34 UTC
Bot

Promoted to #22600.

Reviewers
Assignees
zaniebot zaniebot
Labels
risk: low confidence: 83.7% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 71.5% (HIGH) · Higher = larger blast radius
71.5%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 83.7% · Lower = rushed or shallow review
83.7%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 11.7% · Safe to merge
11.7%