dev_container: Respect readonly mounts (#66071)

## Summary

Closes #65567

Dev container mounts kept only source, target and type, so `readonly`
was silently dropped and read-only bind mounts ended up writable. All
three mount parsers (`mounts`, `workspaceMount`, image metadata) had
this.

This replaces them with one `MountDefinition::parse` that follows
Docker's `--mount` syntax. Other options are passed to `docker run
--mount` unchanged, like the devcontainers CLI does. Compose gets
`read_only: true`; other options still aren't mapped there, same as the
reference CLI.

Quoting now follows Docker's CSV rules too, so a project path containing
`,` or `"` gets the right workspace mount, and an unquoted
`source=/path/a,b` is rejected by Docker as it is with the devcontainers
CLI.

## Testing

- Added tests for parsing, the `docker run` arguments and the Compose
override. They fail on `main` and pass with this change.
- Built Zed locally, used "Open in Container" with a `readonly` bind
mount and tried writing to it. Before: the write succeeded. After:
"Read-only file system", for both image and Compose configs. Normal
mounts stay writable.

```
$ echo probe > /ro/probe.txt
sh: can't create /ro/probe.txt: Read-only file system
```

To test: create a `data` folder, add `"mounts":
["source=${localWorkspaceFolder}/data,target=/data,type=bind,readonly"]`
to devcontainer.json, open it in a container and run `touch /data/x`.

## Self-review

- [x] I've reviewed my diff for quality, security, reliability, and
performance.
- [ ] UI changes follow the
[checklist](https://zed.dev/docs/development/ui-checklist).
- [x] Tests cover the new or changed behavior.

Release Notes:

- Fixed dev container `mounts` ignoring `readonly`, which made read-only
bind mounts writable. Existing dev containers must be removed (for
example, `docker rm -f <container>`) to get read-only mounts.
This commit is contained in:
Mason Liu
2026-11-25 21:14:10 +00:00
committed by GitHub
parent 6ba65ce3be
commit 8aeb64f744
4 changed files with 308 additions and 92 deletions
+201 -57
View File
@@ -1,6 +1,7 @@
use std::{collections::HashMap, fmt::Display, path::Path, sync::Arc};
use crate::{command_json::CommandRunner, devcontainer_api::DevContainerError};
use anyhow::Context as _;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json_lenient::Value;
use util::command::Command;
@@ -64,7 +65,7 @@ pub(crate) enum ShutdownAction {
StopCompose,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub(crate) struct MountDefinition {
#[serde(default)]
@@ -72,6 +73,60 @@ pub(crate) struct MountDefinition {
pub(crate) target: String,
#[serde(rename = "type")]
pub(crate) mount_type: Option<String>,
#[serde(
default,
rename = "read_only",
skip_serializing_if = "std::ops::Not::not"
)]
pub(crate) read_only: bool,
/// Other `docker run --mount` options, kept verbatim.
#[serde(skip)]
pub(crate) options: Vec<String>,
}
impl MountDefinition {
/// Parses a `docker run --mount` value.
pub(crate) fn parse(value: &str) -> anyhow::Result<Self> {
let mut mount = Self::default();
let mut target = None;
let mut quoted = false;
for part in value
.split(|character| {
if character == '"' {
quoted = !quoted;
}
character == ',' && !quoted
})
.map(str::trim)
.filter(|part| !part.is_empty())
{
let field = part
.strip_prefix('"')
.and_then(|part| part.strip_suffix('"'))
.map(|part| part.replace("\"\"", "\""));
let field = field.as_deref().unwrap_or(part);
let (key, value) = match field.split_once('=') {
Some((key, value)) => (key.trim(), Some(value.trim())),
None => (field, None),
};
match (key.to_ascii_lowercase().as_str(), value) {
("source" | "src", Some(value)) => mount.source = Some(value.to_string()),
("target" | "dst" | "destination", Some(value)) => target = Some(value.to_string()),
("type", Some(value)) => mount.mount_type = Some(value.to_string()),
// Go's `strconv.ParseBool` false values, which Docker accepted before v29.2.1.
("readonly" | "ro", value) => {
mount.read_only =
!matches!(value, Some("0" | "f" | "F" | "false" | "False" | "FALSE"))
}
_ => mount.options.push(part.to_string()),
}
}
anyhow::ensure!(!quoted, "mount string has an unbalanced quote: {value}");
mount.target = target.with_context(|| format!("mount string missing 'target': {value}"))?;
Ok(mount)
}
}
impl Display for MountDefinition {
@@ -89,10 +144,34 @@ impl Display for MountDefinition {
"volume".to_string()
});
write!(f, "type={}", mount_type)?;
if let Some(source) = &self.source {
write!(f, ",source={}", source)?;
for (key, value) in [
("source", self.source.as_deref()),
("target", Some(self.target.as_str())),
] {
if let Some(value) = value {
let field = format!("{key}={value}");
if field.contains([',', '"', '\n', '\r']) {
write!(f, ",\"{}\"", field.replace('"', "\"\""))?;
} else {
write!(f, ",{field}")?;
}
}
}
write!(f, ",target={},consistency=cached", self.target)
if self.read_only {
write!(f, ",readonly")?;
}
for option in &self.options {
write!(f, ",{option}")?;
}
if !self.options.iter().any(|option| {
option
.trim_matches('"')
.split_once('=')
.is_some_and(|(key, _)| key.trim().eq_ignore_ascii_case("consistency"))
}) {
write!(f, ",consistency=cached")?;
}
Ok(())
}
}
@@ -504,32 +583,7 @@ where
let mount = match item {
MountItem::Object(mount) => mount,
MountItem::String(s) => {
let mut source = None;
let mut target = None;
let mut mount_type = None;
for part in s.split(',') {
let part = part.trim();
if let Some((key, value)) = part.split_once('=') {
match key.trim() {
"source" => source = Some(value.trim().to_string()),
"target" => target = Some(value.trim().to_string()),
"type" => mount_type = Some(value.trim().to_string()),
_ => {} // Ignore unknown keys
}
}
}
let target = target
.ok_or_else(|| D::Error::custom(format!("mount string missing 'target': {}", s)))?;
MountDefinition {
source,
target,
mount_type,
}
}
MountItem::String(s) => MountDefinition::parse(&s).map_err(D::Error::custom)?,
};
Ok(Some(mount))
@@ -558,31 +612,7 @@ where
match item {
MountItem::Object(mount) => mounts.push(mount),
MountItem::String(s) => {
let mut source = None;
let mut target = None;
let mut mount_type = None;
for part in s.split(',') {
let part = part.trim();
if let Some((key, value)) = part.split_once('=') {
match key.trim() {
"source" => source = Some(value.trim().to_string()),
"target" => target = Some(value.trim().to_string()),
"type" => mount_type = Some(value.trim().to_string()),
_ => {} // Ignore unknown keys
}
}
}
let target = target.ok_or_else(|| {
D::Error::custom(format!("mount string missing 'target': {}", s))
})?;
mounts.push(MountDefinition {
source,
target,
mount_type,
});
mounts.push(MountDefinition::parse(&s).map_err(D::Error::custom)?)
}
}
}
@@ -1007,6 +1037,7 @@ mod test {
source: Some("/localfolder/app".to_string()),
target: "/workspaces/app".to_string(),
mount_type: Some("volume".to_string()),
..Default::default()
}]),
run_args: Some(vec!["-c".to_string(), "some_command".to_string()]),
shutdown_action: Some(ShutdownAction::StopContainer),
@@ -1015,7 +1046,9 @@ mod test {
workspace_mount: Some(MountDefinition {
source: Some("/app".to_string()),
target: "/workspaces/app".to_string(),
mount_type: Some("bind".to_string())
mount_type: Some("bind".to_string()),
options: vec!["consistency=cached".to_string()],
..Default::default()
}),
customizations: Some(ZedCustomizationsWrapper {
zed: ZedCustomization {
@@ -1473,11 +1506,13 @@ mod test {
source: Some("/localfolder/app".to_string()),
target: "/workspaces/app".to_string(),
mount_type: Some("volume".to_string()),
..Default::default()
},
MountDefinition {
source: Some("dev-containers-cli-bashhistory".to_string()),
target: "/home/node/commandhistory".to_string(),
mount_type: None,
..Default::default()
}
]),
run_args: Some(vec!["-c".to_string(), "some_command".to_string()]),
@@ -1487,7 +1522,9 @@ mod test {
workspace_mount: Some(MountDefinition {
source: Some("/folder".to_string()),
target: "/workspace".to_string(),
mount_type: Some("bind".to_string())
mount_type: Some("bind".to_string()),
options: vec!["consistency=cached".to_string()],
..Default::default()
}),
build: Some(ContainerBuild {
dockerfile: "DockerFile".to_string(),
@@ -1555,6 +1592,7 @@ mod test {
source: Some("/home/user/project".to_string()),
target: "/workspaces/project".to_string(),
mount_type: None,
..Default::default()
};
let rendered = mount.to_string();
@@ -1571,6 +1609,7 @@ mod test {
source: Some("\\\\server\\share\\project".to_string()),
target: "/workspaces/project".to_string(),
mount_type: None,
..Default::default()
};
let rendered = mount.to_string();
@@ -1587,6 +1626,7 @@ mod test {
source: Some("C:\\Users\\mrg\\cli".to_string()),
target: "/workspaces/cli".to_string(),
mount_type: None,
..Default::default()
};
let rendered = mount.to_string();
@@ -1603,6 +1643,7 @@ mod test {
source: None,
target: "/tmp".to_string(),
mount_type: Some("tmpfs".to_string()),
..Default::default()
};
let rendered = mount.to_string();
@@ -1610,6 +1651,109 @@ mod test {
assert_eq!(rendered, "type=tmpfs,target=/tmp,consistency=cached");
}
#[test]
fn should_keep_readonly_and_other_options_in_string_mounts() {
let devcontainer = deserialize_devcontainer_json(
r#"{
"image": "ubuntu",
"workspaceMount": "source=/app,target=/workspaces/app,type=bind,readonly",
"mounts": [
"source=/a,target=/a,type=bind,readonly",
"source=/b,target=/b,type=bind,ro",
"source=/c,target=/c,type=bind,readonly=true",
"source=/d,target=/d,type=bind,readonly=false",
"source=/e,target=/e,type=bind,consistency=delegated,bind-propagation=rslave"
]
}"#,
)
.unwrap();
assert_eq!(
devcontainer.workspace_mount.unwrap().to_string(),
"type=bind,source=/app,target=/workspaces/app,readonly,consistency=cached"
);
assert_eq!(
devcontainer
.mounts
.unwrap()
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>(),
vec![
"type=bind,source=/a,target=/a,readonly,consistency=cached",
"type=bind,source=/b,target=/b,readonly,consistency=cached",
"type=bind,source=/c,target=/c,readonly,consistency=cached",
"type=bind,source=/d,target=/d,consistency=cached",
"type=bind,source=/e,target=/e,consistency=delegated,bind-propagation=rslave",
]
);
}
#[test]
fn should_preserve_readonly_with_case_and_csv_quoting() {
for (options, read_only) in [
("READONLY=false,readonly", true),
("ro=false,RO", true),
("\"readonly\"", true),
("\"readonly=false\",readonly", true),
("readonly=1", true),
("readonly,readonly=0", false),
("ro,readonly=f", false),
("readonly=F", false),
("readonly=False", false),
("readonly=FALSE", false),
] {
let value = format!("type=bind,src=/host,dst=/data,{options}");
let mount = MountDefinition::parse(&value).unwrap();
assert_eq!(mount.read_only, read_only, "{value}");
assert_eq!(
mount.to_string(),
format!(
"type=bind,source=/host,target=/data{},consistency=cached",
if read_only { ",readonly" } else { "" }
),
"{value}"
);
}
let mount = MountDefinition::parse(
r#"type=bind,"source=/host/with,readonly=false,commas",target=/data,readonly,"consistency=delegated""#,
)
.unwrap();
assert!(mount.read_only);
assert_eq!(
mount.source.as_deref(),
Some("/host/with,readonly=false,commas")
);
assert_eq!(
mount.to_string(),
r#"type=bind,"source=/host/with,readonly=false,commas",target=/data,readonly,"consistency=delegated""#
);
let value = r#"type=bind,"source=C:\with,""quotes""",target=/data,ro"#;
let mount = MountDefinition::parse(value).unwrap();
assert_eq!(mount.source.as_deref(), Some("C:\\with,\"quotes\""));
assert_eq!(
mount.to_string(),
r#"type=bind,"source=C:\with,""quotes""",target=/data,readonly,consistency=cached"#
);
}
#[test]
fn should_report_unbalanced_quote_in_mount_string() {
let error = MountDefinition::parse(r#"type=bind,source=/a"b,target=/data"#).unwrap_err();
assert_eq!(
error.to_string(),
r#"mount string has an unbalanced quote: type=bind,source=/a"b,target=/data"#
);
let error = MountDefinition::parse("type=bind,source=/a").unwrap_err();
assert_eq!(
error.to_string(),
"mount string missing 'target': type=bind,source=/a"
);
}
#[test]
fn should_deserialize_port_attributes_with_missing_optional_fields() {
let json = r#"
+102 -34
View File
@@ -1420,15 +1420,7 @@ RUN sed -i -E 's/((^|\s)PATH=)([^\$]*)$/\1\${{PATH:-\3}}/g' /etc/profile || true
})
.collect();
let volumes: Vec<MountDefinition> = resources
.additional_mounts
.iter()
.map(|v| MountDefinition {
source: v.source.clone(),
target: v.target.clone(),
mount_type: v.mount_type.clone(),
})
.collect();
let volumes: Vec<MountDefinition> = resources.additional_mounts.clone();
let entrypoint = resources.entrypoint_script.map(|script| {
vec![
@@ -2152,6 +2144,7 @@ RUN sed -i -E 's/((^|\s)PATH=)([^\$]*)$/\1\${PATH:-\3}/g' /etc/profile || true
project_directory_name.display()
),
mount_type: None,
..Default::default()
})
}
@@ -3303,7 +3296,9 @@ fn append_mount_with_target_override(mounts: &mut Vec<MountDefinition>, mount: M
fn mount_definition_from_metadata(value: &serde_json_lenient::Value) -> Option<MountDefinition> {
match value {
serde_json_lenient::Value::String(value) => parse_mount_definition_string(value),
serde_json_lenient::Value::String(value) => MountDefinition::parse(value)
.inspect_err(|error| log::warn!("Skipping image metadata mount: {error}"))
.ok(),
serde_json_lenient::Value::Object(object) => {
let source = object
.get("source")
@@ -3324,36 +3319,13 @@ fn mount_definition_from_metadata(value: &serde_json_lenient::Value) -> Option<M
source,
target,
mount_type,
..Default::default()
})
}
_ => None,
}
}
fn parse_mount_definition_string(value: &str) -> Option<MountDefinition> {
let mut source = None;
let mut target = None;
let mut mount_type = None;
for part in value.split(',') {
let Some((key, value)) = part.trim().split_once('=') else {
continue;
};
match key.trim() {
"source" | "src" => source = Some(value.trim().to_string()),
"target" | "dst" | "destination" => target = Some(value.trim().to_string()),
"type" => mount_type = Some(value.trim().to_string()),
_ => {}
}
}
target.map(|target| MountDefinition {
source,
target,
mount_type,
})
}
fn escape_compose_interpolation(value: &str) -> String {
value.replace('$', "$$")
}
@@ -3936,6 +3908,7 @@ mod test {
)),
target: "/var/lib/docker".to_string(),
mount_type: Some("volume".to_string()),
..Default::default()
}]
);
assert_eq!(
@@ -3960,6 +3933,98 @@ mod test {
);
}
async fn mount_options_test_resources(
cx: &mut TestAppContext,
) -> (DevContainerManifest, DockerBuildResources) {
let (_, mut devcontainer_manifest) = init_default_devcontainer_manifest(
cx,
r#"{
"image": "mcr.microsoft.com/devcontainers/base:ubuntu",
"mounts": [
"source=/host/hooks,target=/hooks,type=bind,READONLY=false,readonly",
"source=/host/cache,target=/cache,type=bind,bind-propagation=rslave"
]
}"#,
)
.await
.unwrap();
devcontainer_manifest.parse_nonremote_vars().unwrap();
let metadata = serde_json_lenient::from_str(
r#"[
{
"mounts": ["source=/host/metadata,target=/metadata,type=bind,\"ro\""]
}
]"#,
)
.unwrap();
let base_image = DockerInspect {
id: "base-image-id".to_string(),
config: DockerInspectConfig {
labels: DockerConfigLabels {
metadata: Some(metadata),
},
image_user: None,
env: Vec::new(),
},
mounts: None,
state: None,
};
let resources = devcontainer_manifest
.build_merged_resources(base_image, "mcr.microsoft.com/devcontainers/base:ubuntu")
.unwrap();
(devcontainer_manifest, resources)
}
#[gpui::test]
async fn should_pass_mount_options_to_docker_run(cx: &mut TestAppContext) {
let (devcontainer_manifest, resources) = mount_options_test_resources(cx).await;
let docker_run_command = devcontainer_manifest
.create_docker_run_command(resources)
.unwrap();
let args = docker_run_command.get_args().collect::<Vec<&OsStr>>();
let mounts = args
.iter()
.zip(args.iter().skip(1))
.filter(|(flag, _)| **flag == "--mount")
.map(|(_, mount)| mount.to_str().unwrap())
.skip(1)
.collect::<Vec<_>>();
assert_eq!(
mounts,
vec![
"type=bind,source=/host/metadata,target=/metadata,readonly,consistency=cached",
"type=bind,source=/host/hooks,target=/hooks,readonly,consistency=cached",
"type=bind,source=/host/cache,target=/cache,bind-propagation=rslave,consistency=cached",
]
);
}
#[gpui::test]
async fn should_pass_mount_options_to_compose_override(cx: &mut TestAppContext) {
let (devcontainer_manifest, resources) = mount_options_test_resources(cx).await;
let runtime_override = devcontainer_manifest
.build_runtime_override("app", None, resources)
.unwrap();
let runtime_override = serde_json_lenient::to_value(&runtime_override).unwrap();
let volumes: Vec<Value> = serde_json_lenient::from_str(
r#"[
{ "source": "/host/metadata", "target": "/metadata", "type": "bind", "read_only": true },
{ "source": "/host/hooks", "target": "/hooks", "type": "bind", "read_only": true },
{ "source": "/host/cache", "target": "/cache", "type": "bind" }
]"#,
)
.unwrap();
assert_eq!(
runtime_override["services"]["app"]["volumes"],
Value::Array(volumes)
);
}
#[gpui::test]
async fn should_use_devcontainer_cli_post_start_marker_for_started_container(
cx: &mut TestAppContext,
@@ -7514,6 +7579,7 @@ RUN echo $RUBY_VERSION2
source: Some("../..".to_string()),
target: "/workspaces".to_string(),
mount_type: Some("bind".to_string()),
..Default::default()
}],
command: vec!["sleep".to_string(), "infinity".to_string()],
..Default::default()
@@ -7533,6 +7599,7 @@ RUN echo $RUBY_VERSION2
source: Some("../..".to_string()),
target: "/workspaces".to_string(),
mount_type: Some("bind".to_string()),
..Default::default()
}],
network_mode: Some("service:db".to_string()),
..Default::default()
@@ -7546,6 +7613,7 @@ RUN echo $RUBY_VERSION2
source: Some("postgres-data".to_string()),
target: "/var/lib/postgresql/data".to_string(),
mount_type: Some("volume".to_string()),
..Default::default()
}],
env_file: Some(vec![".env".to_string()]),
..Default::default()
+4
View File
@@ -680,6 +680,7 @@ fn parse_compose_volume_string(s: &str) -> Option<MountDefinition> {
source: Some(source.to_string()),
target: target.to_string(),
mount_type: None,
..Default::default()
})
} else {
// No colon at all — anonymous volume with only a target path
@@ -690,6 +691,7 @@ fn parse_compose_volume_string(s: &str) -> Option<MountDefinition> {
source: None,
target: s.to_string(),
mount_type: None,
..Default::default()
})
}
}
@@ -1155,6 +1157,7 @@ mod test {
mount_type: Some("bind".to_string()),
source: Some("/path/to".to_string()),
target: "/workspaces".to_string(),
..Default::default()
}],
network_mode: Some("service:db".to_string()),
@@ -1192,6 +1195,7 @@ mod test {
mount_type: Some("volume".to_string()),
source: Some("postgres-data".to_string()),
target: "/var/lib/postgresql/data".to_string(),
..Default::default()
}],
environment: Some(HashMap::from([
("POSTGRES_DB".to_string(), "postgres".to_string()),
+1 -1
View File
@@ -35,7 +35,7 @@ Alternatively, you can reach for the Remote Projects modal (through the {#kb pro
If you modify `.devcontainer/devcontainer.json`, Zed does not currently rebuild or reload the container automatically. After changing configuration:
- Stop or kill the existing container manually (e.g., via `docker kill <container>`).
- Remove the existing container manually (e.g., via `docker rm -f <container>`).
- Reopen the project in the container.
## Working in a Dev Container