Skip to content

Commit b79536f

Browse files
wan9chiGemini 4 Neon
andcommitted
feat(cache): validate remote cache URLs upfront and document env vars in CLI help
Fail fast on malformed remote cache endpoint URLs and surface remote cache environment variables in `vp run --help`: - Validate `cache.remote.url` in `vt_graph` and `VP_REMOTE_CACHE_URL` in `vt_plan` (requiring `http://` or `https://` with a host, without leaking URL credentials in errors; skipped when mode is `off`) - Add unit tests confirming unknown keys in `cache` and `cache.remote` are rejected - Document `VP_REMOTE_CACHE`, `VP_REMOTE_CACHE_URL`, and `VP_REMOTE_CACHE_HEADER_<NAME>` in `RunFlags::remote_cache` and `RunCommand` long help - Update plan/e2e snapshots and `CHANGELOG.md` Co-authored-by: Gemini 4 Neon <noreply@google.com>
1 parent b8a6dde commit b79536f

14 files changed

Lines changed: 245 additions & 106 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Changelog
22

3+
- **Changed** Invalid remote cache endpoint URLs in `cache.remote.url` or `VP_REMOTE_CACHE_URL` (such as missing schemes, non-`http`/`https` schemes, or missing hosts) now fail upfront during configuration and planning instead of warning per task during execution, and `vp run --help` now documents `VP_REMOTE_CACHE`, `VP_REMOTE_CACHE_URL`, and `VP_REMOTE_CACHE_HEADER_<NAME>` ([#???](https://github.com/voidzero-dev/vite-task/pull/???)).
34
- **Changed** Removed `NEXT_*`, `VERCEL`, `VERCEL_*`, `USE_OUTPUT_FOR_EDGE_FUNCTIONS`, `NOW_BUILDER`, `VC_MICROFRONTENDS_CONFIG_FILE_NAME`, `GITHUB_*`, `ACTIONS_ID_TOKEN_REQUEST_URL`, `DOCKER_*`, `BUILDKIT_*`, `COMPOSE_*`, and `*_TOKEN` from the default untracked environment variables passed to cached tasks. Tasks that need any of these variables should declare them explicitly in `cache.env` or `cache.untrackedEnv` ([#1044](https://github.com/voidzero-dev/vite-task/pull/1044)).
45
- **Changed** `VP_*` environment variables (including `VP_REMOTE_CACHE*` and `VP_RUN_*`) are no longer passed through to cached tasks by default; embedders can opt specific variables into default untracked passthrough via `SessionConfig::extra_untracked_env` ([#1043](https://github.com/voidzero-dev/vite-task/pull/1043)).
56
- **Added** Remote cache requests now support custom HTTP headers via `cache.remote.headers` in the workspace root's `vite.config.*` (`cache.remote.url` is now optional when `VP_REMOTE_CACHE_URL` is set) and `VP_REMOTE_CACHE_HEADER_<NAME>` environment variables (`_` maps to `-` and overrides matching configured headers). Non-`Authorization` headers compose with GitHub Actions OIDC on stores and are never sent on OIDC token requests, while setting `Authorization` in `cache.remote.headers` or `VP_REMOTE_CACHE_HEADER_AUTHORIZATION` turns off automatic GitHub OIDC ([#1037](https://github.com/voidzero-dev/vite-task/pull/1037), [#1038](https://github.com/voidzero-dev/vite-task/pull/1038), [#1039](https://github.com/voidzero-dev/vite-task/pull/1039), [#1040](https://github.com/voidzero-dev/vite-task/pull/1040)).

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/vt/src/cli/mod.rs‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,14 @@ pub struct RunFlags {
7171
#[clap(long, conflicts_with = "cache")]
7272
pub no_cache: bool,
7373

74-
/// How the remote cache is accessed.
74+
/// How the remote cache is accessed (`VP_REMOTE_CACHE`).
7575
///
76-
/// If you don't pass this flag, `VP_REMOTE_CACHE` selects the mode. If neither
77-
/// is set, the mode is `read` when an endpoint is configured, or `off` otherwise.
76+
/// Overrides `VP_REMOTE_CACHE`. When neither is set, defaults to `read` when
77+
/// an endpoint is configured (`cache.remote.url` or `VP_REMOTE_CACHE_URL`),
78+
/// or `off` otherwise.
79+
///
80+
/// Custom request headers can be configured via `cache.remote.headers` or
81+
/// `VP_REMOTE_CACHE_HEADER_<NAME>` environment variables (`_` maps to `-`).
7882
#[clap(long)]
7983
pub remote_cache: Option<RemoteCacheMode>,
8084

@@ -118,7 +122,10 @@ impl RunFlags {
118122
///
119123
/// See <https://github.com/voidzero-dev/vite-task/issues/285>.
120124
#[derive(Debug, clap::Parser)]
121-
#[command(trailing_var_arg = true)]
125+
#[command(
126+
trailing_var_arg = true,
127+
after_long_help = "Environment Variables:\n VP_REMOTE_CACHE Remote cache mode: off, read, or read-write\n VP_REMOTE_CACHE_URL Remote cache endpoint URL (overrides cache.remote.url)\n VP_REMOTE_CACHE_HEADER_<NAME> Extra HTTP header for remote cache requests (_ maps to -)"
128+
)]
122129
pub struct RunCommand {
123130
#[clap(flatten)]
124131
pub(crate) flags: RunFlags,
@@ -382,3 +389,19 @@ impl ResolvedRunCommand {
382389
))
383390
}
384391
}
392+
393+
#[cfg(test)]
394+
mod tests {
395+
use clap::CommandFactory as _;
396+
397+
use super::RunCommand;
398+
399+
#[test]
400+
fn run_help_documents_remote_cache_flag_and_env_vars() {
401+
let help = RunCommand::command().render_long_help().to_string();
402+
assert!(help.contains("--remote-cache"), "{help}");
403+
assert!(help.contains("VP_REMOTE_CACHE"), "{help}");
404+
assert!(help.contains("VP_REMOTE_CACHE_URL"), "{help}");
405+
assert!(help.contains("VP_REMOTE_CACHE_HEADER_<NAME>"), "{help}");
406+
}
407+
}

‎crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache/snapshots.toml‎

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -544,26 +544,7 @@ steps = [
544544
"VP_REMOTE_CACHE_URL",
545545
"cache.example/projects/test",
546546
],
547-
], comment = "The failed fetch is the miss reason, and the failed upload is a warning. The task succeeds." },
548-
{ argv = [
549-
"vt",
550-
"run",
551-
"--last-details",
552-
], comment = "The details include the underlying error." },
553-
{ argv = [
554-
"vt",
555-
"run",
556-
"build",
557-
], envs = [
558-
[
559-
"VP_REMOTE_CACHE",
560-
"read-write",
561-
],
562-
[
563-
"VP_REMOTE_CACHE_URL",
564-
"cache.example/projects/test",
565-
],
566-
], comment = "The local cache was updated. Hits never upload." },
547+
], comment = "An invalid remote cache URL fails before running tasks." },
567548
]
568549

569550
[[e2e]]
@@ -717,14 +698,9 @@ steps = [
717698
], envs = [
718699
[
719700
"VP_REMOTE_CACHE_URL",
720-
"cache.example/projects/test",
701+
"ftp://cache.example/projects/test",
721702
],
722-
], comment = "The failed fetch is the miss reason. Read failures aren't warnings." },
723-
[
724-
"vt",
725-
"run",
726-
"--last-details",
727-
],
703+
], comment = "An unsupported URL scheme fails before running tasks." },
728704
]
729705

730706
[[e2e]]

‎crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache/snapshots/invalid_endpoint.md‎

Lines changed: 4 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -2,46 +2,11 @@
22

33
## `VP_REMOTE_CACHE=read-write VP_REMOTE_CACHE_URL=cache.example/projects/test vt run build`
44

5-
The failed fetch is the miss reason, and the failed upload is a warning. The task succeeds.
5+
An invalid remote cache URL fails before running tasks.
66

7-
```
8-
$ vtt write-file dist/output.txt built ○ cache miss: remote cache fetch failed, executing
9-
10-
---
11-
vt run: remote-cache#build not uploaded to the remote cache: invalid endpoint. (Run `vt run --last-details` for full details)
12-
```
13-
14-
## `vt run --last-details`
15-
16-
The details include the underlying error.
7+
**Exit code:** 1
178

189
```
19-
20-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
21-
Vite+ Task Runner • Execution Summary
22-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
23-
24-
Statistics: 1 task • 0 cache hits • 1 cache miss
25-
Performance: 0% cache hit rate
26-
27-
Task Details:
28-
────────────────────────────────────────────────
29-
[1] remote-cache#build: $ vtt write-file dist/output.txt built ✓
30-
→ Cache miss: remote cache fetch failed
31-
↳ invalid endpoint
32-
↳ relative URL without a base
33-
⚠ Not uploaded to the remote cache: invalid endpoint
34-
↳ relative URL without a base
35-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
36-
```
37-
38-
## `VP_REMOTE_CACHE=read-write VP_REMOTE_CACHE_URL=cache.example/projects/test vt run build`
39-
40-
The local cache was updated. Hits never upload.
41-
42-
```
43-
$ vtt write-file dist/output.txt built ◉ cache hit, replaying
44-
45-
---
46-
vt run: cache hit.
10+
error: Invalid value for VP_REMOTE_CACHE_URL
11+
* relative URL without a base
4712
```
Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,12 @@
11
# read_invalid_endpoint
22

3-
## `VP_REMOTE_CACHE_URL=cache.example/projects/test vt run build`
3+
## `VP_REMOTE_CACHE_URL=ftp://cache.example/projects/test vt run build`
44

5-
The failed fetch is the miss reason. Read failures aren't warnings.
5+
An unsupported URL scheme fails before running tasks.
66

7-
```
8-
$ vtt write-file dist/output.txt built ○ cache miss: remote cache fetch failed, executing
9-
```
10-
11-
## `vt run --last-details`
7+
**Exit code:** 1
128

139
```
14-
15-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
16-
Vite+ Task Runner • Execution Summary
17-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
18-
19-
Statistics: 1 task • 0 cache hits • 1 cache miss
20-
Performance: 0% cache hit rate
21-
22-
Task Details:
23-
────────────────────────────────────────────────
24-
[1] remote-cache#build: $ vtt write-file dist/output.txt built ✓
25-
→ Cache miss: remote cache fetch failed
26-
↳ invalid endpoint
27-
↳ relative URL without a base
28-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
10+
error: Invalid value for VP_REMOTE_CACHE_URL
11+
* URL scheme must be http or https
2912
```

‎crates/vt_graph/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ serde_json = { workspace = true }
2222
thiserror = { workspace = true }
2323
tokio = { workspace = true, features = ["sync"] }
2424
tracing = { workspace = true }
25+
url = { workspace = true }
2526
vec1 = { workspace = true, features = ["serde"] }
2627
vt_path = { workspace = true }
2728
vt_str = { workspace = true }

‎crates/vt_graph/src/config/remote_cache.rs‎

Lines changed: 101 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -206,11 +206,43 @@ pub fn validate_header_value(raw: &str) -> Result<Secret, InvalidHeaderValueErro
206206
Ok(Secret::new(Arc::from(raw)))
207207
}
208208

209+
/// Why a remote cache endpoint URL was rejected.
210+
///
211+
/// Messages never include the URL itself, since it may contain credentials.
212+
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
213+
pub enum InvalidEndpointUrlError {
214+
#[error(transparent)]
215+
Parse(#[from] url::ParseError),
216+
#[error("URL scheme must be http or https")]
217+
UnsupportedScheme,
218+
#[error("URL must include a host")]
219+
MissingHost,
220+
}
221+
222+
/// Validate a remote cache endpoint URL.
223+
///
224+
/// Requires a valid `http://` or `https://` URL with a host whose path can hold
225+
/// route segments (`/fetch`, `/store`, `/blob/...`).
226+
///
227+
/// # Errors
228+
///
229+
/// Returns [`InvalidEndpointUrlError`] without echoing the URL.
230+
pub fn validate_endpoint_url(raw: &str) -> Result<Arc<str>, InvalidEndpointUrlError> {
231+
let parsed = url::Url::parse(raw)?;
232+
if !matches!(parsed.scheme(), "http" | "https") {
233+
return Err(InvalidEndpointUrlError::UnsupportedScheme);
234+
}
235+
if parsed.cannot_be_a_base() || !parsed.has_host() {
236+
return Err(InvalidEndpointUrlError::MissingHost);
237+
}
238+
Ok(Arc::from(raw))
239+
}
240+
209241
/// Resolved remote cache configuration from the workspace root's `cache.remote`.
210242
#[derive(Debug, Clone, Default)]
211243
pub struct ResolvedGlobalRemoteCacheConfig {
212-
/// Remote cache endpoint from `cache.remote.url`, if configured. Planning
213-
/// uses `VP_REMOTE_CACHE_URL` instead when it's set.
244+
/// Validated remote cache endpoint from `cache.remote.url`, if configured.
245+
/// Planning uses `VP_REMOTE_CACHE_URL` instead when it's set.
214246
pub url: Option<Arc<str>>,
215247
/// Custom HTTP headers from `cache.remote.headers`, sorted by canonical
216248
/// lowercase header name.
@@ -222,11 +254,19 @@ impl ResolvedGlobalRemoteCacheConfig {
222254
///
223255
/// # Errors
224256
///
225-
/// Returns [`ResolveGlobalCacheConfigError`] if any header name or value is
226-
/// invalid or duplicated.
257+
/// Returns [`ResolveGlobalCacheConfigError`] if the URL is invalid or any
258+
/// header name or value is invalid or duplicated.
227259
pub(crate) fn resolve_from(
228260
config: &UserRemoteCacheConfig,
229261
) -> Result<Self, ResolveGlobalCacheConfigError> {
262+
let url = match config.url.as_deref() {
263+
None | Some("") => None,
264+
Some(raw) => Some(
265+
validate_endpoint_url(raw)
266+
.map_err(|error| ResolveGlobalCacheConfigError::InvalidUrl { error })?,
267+
),
268+
};
269+
230270
let mut resolved_headers = BTreeMap::<HeaderName, (Str, Secret)>::new();
231271

232272
if let Some(raw_headers) = &config.headers {
@@ -263,7 +303,7 @@ impl ResolvedGlobalRemoteCacheConfig {
263303
let headers: Arc<[(HeaderName, Secret)]> =
264304
resolved_headers.into_iter().map(|(header, (_, value))| (header, value)).collect();
265305

266-
Ok(Self { url: config.url.clone(), headers })
306+
Ok(Self { url, headers })
267307
}
268308
}
269309

@@ -284,6 +324,12 @@ pub fn strip_header_env_prefix_case_insensitive(name: &str) -> Option<&str> {
284324
/// Errors resolving the workspace root's global `cache` configuration.
285325
#[derive(Debug, thiserror::Error)]
286326
pub enum ResolveGlobalCacheConfigError {
327+
/// The URL isn't shown, since it may contain credentials.
328+
#[error("invalid remote cache URL in cache.remote.url")]
329+
InvalidUrl {
330+
#[source]
331+
error: InvalidEndpointUrlError,
332+
},
287333
#[error("invalid remote cache header name '{name}'")]
288334
InvalidHeaderName {
289335
name: Str,
@@ -504,4 +550,54 @@ mod tests {
504550
let too_long = "a".repeat(MAX_HEADER_NAME_LEN + 1);
505551
assert_eq!(HeaderName::parse(&too_long), Err(InvalidHeaderNameError::TooLong));
506552
}
553+
554+
#[test]
555+
fn validates_remote_cache_url_and_redacts_errors() {
556+
for valid in [
557+
"http://127.0.0.1:8080/projects/test",
558+
"https://cache.example.com/projects/my-app",
559+
"https://cache.example.com",
560+
] {
561+
let resolved = resolve_remote(&json!({ "url": valid })).unwrap();
562+
assert_eq!(resolved.url.as_deref(), Some(valid));
563+
}
564+
565+
// Empty url counts as unset.
566+
let empty = resolve_remote(&json!({ "url": "" })).unwrap();
567+
assert!(empty.url.is_none());
568+
569+
for bad in [
570+
"notaurl?token=super-secret",
571+
"cache.example/projects/test?token=super-secret",
572+
"ftp://user:super-secret@cache.example/projects/test",
573+
"https://",
574+
] {
575+
let err = resolve_remote(&json!({ "url": bad })).unwrap_err();
576+
assert!(
577+
matches!(err, ResolveGlobalCacheConfigError::InvalidUrl { .. }),
578+
"{bad}: {err:?}"
579+
);
580+
let combined = vt_str::format!("{err} {err:?}");
581+
assert!(!combined.contains("super-secret"), "{combined}");
582+
}
583+
}
584+
585+
#[test]
586+
fn rejects_unknown_keys_in_cache_and_remote_config() {
587+
let err = serde_json::from_value::<UserGlobalCacheConfig>(json!({
588+
"scripts": true,
589+
"bogus": 1,
590+
}))
591+
.unwrap_err();
592+
assert!(err.to_string().contains("unknown field `bogus`"), "{err}");
593+
594+
let err = serde_json::from_value::<UserGlobalCacheConfig>(json!({
595+
"remote": {
596+
"url": "https://cache.example/projects/app",
597+
"mode": "read-write",
598+
}
599+
}))
600+
.unwrap_err();
601+
assert!(err.to_string().contains("unknown field `mode`"), "{err}");
602+
}
507603
}

‎crates/vt_plan/src/error.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,8 +178,16 @@ pub enum Error {
178178
#[error("Invalid value for VP_REMOTE_CACHE: {0:?}, expected off, read, or read-write")]
179179
InvalidRemoteCacheModeEnv(Arc<OsStr>),
180180

181-
#[error("Invalid value for VP_REMOTE_CACHE_URL: {0:?}")]
182-
InvalidRemoteCacheUrlEnv(Arc<OsStr>),
181+
/// The value isn't shown, since it may contain credentials.
182+
#[error("Invalid value for VP_REMOTE_CACHE_URL: not valid UTF-8")]
183+
NonUtf8RemoteCacheUrlEnv,
184+
185+
/// The value isn't shown, since it may contain credentials.
186+
#[error("Invalid value for VP_REMOTE_CACHE_URL")]
187+
InvalidRemoteCacheUrlEnv {
188+
#[source]
189+
error: vt_graph::config::remote_cache::InvalidEndpointUrlError,
190+
},
183191

184192
#[error("Remote caching requires cache.remote.url or VP_REMOTE_CACHE_URL")]
185193
MissingRemoteCacheEndpoint,

0 commit comments

Comments
 (0)