Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions crates/protrus-artifact/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,13 @@ mod tests {
assert!(matches!(b.digest(), Err(ArtifactError::InvalidPath(_))));
}
#[test]
fn a_manifest_id_that_is_not_a_module_id_does_not_deserialize() {
let mut manifest = serde_json::to_value(bundle().manifest).unwrap();
manifest["id"] = "../../escaped".into();
let error = serde_json::from_value::<ManifestV1>(manifest).unwrap_err();
assert!(error.to_string().contains("invalid module id"), "{error}");
}
#[test]
fn patch_preserves_unmodified_files_and_requires_a_new_signature() {
let mut base = bundle();
base.files
Expand Down
28 changes: 27 additions & 1 deletion crates/protrus-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,25 @@ use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::{Arc, Mutex};

/// A module id is a path segment of the stores and worker sockets, so it deserializes through
/// [`ModuleId::parse`]: a body or manifest can never carry an id `parse` would refuse.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
#[serde(into = "String", try_from = "String")]
pub struct ModuleId(String);

impl TryFrom<String> for ModuleId {
type Error = DomainError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::parse(value)
}
}

impl From<ModuleId> for String {
fn from(id: ModuleId) -> Self {
id.0
}
}

impl ModuleId {
pub fn parse(value: impl Into<String>) -> Result<Self, DomainError> {
let value = value.into();
Expand Down Expand Up @@ -548,6 +563,17 @@ impl AuditQuery for MemoryAuditSink {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn module_id_deserializes_only_through_parse() {
let id: ModuleId = serde_json::from_str("\"hello-2\"").unwrap();
assert_eq!(id, ModuleId::parse("hello-2").unwrap());
assert_eq!(serde_json::to_string(&id).unwrap(), "\"hello-2\"");
for invalid in ["\"../../escaped\"", "\"a/b\"", "\"..\"", "\"\"", "\"Hello\""] {
let error = serde_json::from_str::<ModuleId>(invalid).unwrap_err();
assert!(error.to_string().contains("invalid module id"), "{invalid}: {error}");
}
}

#[test]
fn isolation_modes_validate_the_default_and_resolve_like_protean() {
assert_eq!(
Expand Down
25 changes: 17 additions & 8 deletions crates/protrus-host/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -977,11 +977,7 @@ impl OciLaunchResolver for VerifiedOciLaunchPolicy {
module_id: record.module_id.clone(),
revision: record.revision.clone(),
image_digest: spawn.image_digest,
control_socket: self.control_socket_root.join(format!(
"{}-{}.sock",
record.module_id.as_str(),
record.revision.0
)),
control_socket: worker_control_socket(&self.control_socket_root, record)?,
artifact_directory,
component_digest: format!("sha256:{}", hex_encode(&Sha256::digest(component))),
control_secret_file: Some(self.control_secret_file.clone()),
Expand Down Expand Up @@ -1841,9 +1837,7 @@ impl WorkerProcessResolver for VerifiedWorkerLaunchPolicy {
let component_digest = format!("sha256:{}", hex_encode(&Sha256::digest(component)));
secure_private_directory(&self.control_socket_root)?;
let artifact_directory = self.materializer.materialize(&digest, &signed)?;
let control_socket = self
.control_socket_root
.join(format!("{}-{}.sock", record.module_id, record.revision.0));
let control_socket = worker_control_socket(&self.control_socket_root, record)?;
clear_stale_worker_socket(&control_socket)?;
if component_abi_version == 2 {
worker_stream::start_worker_stream_server(
Expand Down Expand Up @@ -2462,6 +2456,21 @@ impl WorkerProcessDeployment {
}
}

/// `<root>/<module>-<revision>.sock`. The OCI runtime bind-mounts the socket's directory, so the
/// name must be one path segment directly under `root`; `ModuleId::parse` guarantees it, and this
/// checks it again where the path is built.
fn worker_control_socket(
root: &std::path::Path,
record: &ModuleRecord,
) -> Result<std::path::PathBuf, String> {
let name = format!("{}-{}.sock", record.module_id, record.revision.0);
let mut components = std::path::Path::new(&name).components();
match (components.next(), components.next()) {
(Some(std::path::Component::Normal(_)), None) => Ok(root.join(name)),
_ => Err(format!("worker control socket name is not a single path segment: {name}")),
}
}

fn secure_private_directory(path: &std::path::Path) -> Result<(), String> {
std::fs::create_dir_all(path).map_err(|error| error.to_string())?;
#[cfg(unix)]
Expand Down
43 changes: 34 additions & 9 deletions crates/protrus-store-fs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ pub enum FsStoreError {
Json(#[from] serde_json::Error),
#[error("injected write interruption: {0}")]
Injected(String),
#[error("module id is not a single path segment: {0}")]
UnsafeModuleId(String),
}

impl FsModuleStore {
Expand All @@ -112,11 +114,19 @@ impl FsModuleStore {
fn modules_dir(&self) -> PathBuf {
self.root.join("modules")
}
fn module_dir(&self, id: &ModuleId) -> PathBuf {
self.modules_dir().join(id.as_str())
/// The directory of `id`, which must stay a direct child of `modules/`. `ModuleId::parse`
/// already guarantees that; checking it again here keeps the store safe on its own.
fn module_dir(&self, id: &ModuleId) -> Result<PathBuf, FsStoreError> {
let mut components = Path::new(id.as_str()).components();
match (components.next(), components.next()) {
(Some(std::path::Component::Normal(_)), None) => {
Ok(self.modules_dir().join(id.as_str()))
}
_ => Err(FsStoreError::UnsafeModuleId(id.as_str().to_owned())),
}
}
fn current_path(&self, id: &ModuleId) -> PathBuf {
self.module_dir(id).join("current.json")
fn current_path(&self, id: &ModuleId) -> Result<PathBuf, FsStoreError> {
Ok(self.module_dir(id)?.join("current.json"))
}
fn hook(&self, phase: WritePhase, record: &ModuleRecord) -> Result<(), FsStoreError> {
match &self.hook {
Expand All @@ -126,7 +136,7 @@ impl FsModuleStore {
}

fn lock_module(&self, module_id: &ModuleId) -> Result<fs::File, FsStoreError> {
let directory = self.module_dir(module_id);
let directory = self.module_dir(module_id)?;
fs::create_dir_all(&directory)?;
let lock = fs::OpenOptions::new()
.create(true)
Expand Down Expand Up @@ -198,17 +208,17 @@ impl ModuleStore for FsModuleStore {
let _lock = self.lock_module(&record.module_id)?;
let bytes = serde_json::to_vec_pretty(record)?;
let history = self
.module_dir(&record.module_id)
.module_dir(&record.module_id)?
.join("history")
.join(format!("{:020}.json", record.revision.0));
Self::atomic_write(&history, &bytes)?;
self.hook(WritePhase::HistoryDurable, record)?;
self.hook(WritePhase::BeforeCurrentPublish, record)?;
Self::atomic_write(&self.current_path(&record.module_id), &bytes)
Self::atomic_write(&self.current_path(&record.module_id)?, &bytes)
}

fn load(&self, module_id: &ModuleId) -> Result<Option<ModuleRecord>, Self::Error> {
let path = self.current_path(module_id);
let path = self.current_path(module_id)?;
match fs::read(path) {
Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Expand All @@ -225,7 +235,7 @@ impl ModuleStore for FsModuleStore {
})
}
fn history(&self, module_id: &ModuleId) -> Result<Vec<ModuleRecord>, Self::Error> {
let directory = self.module_dir(module_id).join("history");
let directory = self.module_dir(module_id)?.join("history");
let entries = match fs::read_dir(directory) {
Ok(entries) => entries,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(vec![]),
Expand Down Expand Up @@ -374,6 +384,21 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn a_record_cannot_carry_a_module_id_that_escapes_the_store() {
let root = root();
let _ = fs::remove_dir_all(&root);
let store = FsModuleStore::new(root.join("store"));
let mut value = serde_json::to_value(record(1)).unwrap();
value["module_id"] = "../../escaped".into();
let error = serde_json::from_value::<ModuleRecord>(value).unwrap_err();
assert!(error.to_string().contains("invalid module id"), "{error}");
store.save(&record(1)).unwrap();
let module_dir = store.module_dir(&ModuleId::parse("hello").unwrap()).unwrap();
assert_eq!(module_dir, root.join("store/modules/hello"));
assert!(!root.join("escaped").exists());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn audit_sink_appends_durable_distinct_events() {
let root = root();
let _ = fs::remove_dir_all(&root);
Expand Down
74 changes: 68 additions & 6 deletions crates/protrus-web/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,26 @@ pub struct DeployInput {
pub signed_artifact: Option<protrus_artifact::SignedArtifact>,
}

/// The JSON deploy envelope of `POST /platform/modules` and `PUT /platform/modules/{id}`. A body
/// serde refuses, such as one whose `record.module_id` is not a valid module id, is a bad deploy
/// envelope: 400 `INVALID_ARGUMENT`, as Java's `IllegalArgumentException` (design 24). A missing
/// or wrong content type keeps axum's own rejection.
pub struct DeployBody(pub DeployInput);

impl<S: Send + Sync> axum::extract::FromRequest<S> for DeployBody {
type Rejection = Response;
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
use axum::extract::rejection::JsonRejection;
match Json::<DeployInput>::from_request(request, state).await {
Ok(Json(input)) => Ok(Self(input)),
Err(rejection @ (JsonRejection::JsonDataError(_) | JsonRejection::JsonSyntaxError(_))) => {
Err(RestProblem::invalid_argument(rejection.body_text()).into_response())
}
Err(rejection) => Err(rejection.into_response()),
}
}
}

impl TryFrom<DeployInput> for protrus_gate::DeployRequest {
type Error = String;
fn try_from(input: DeployInput) -> Result<Self, Self::Error> {
Expand Down Expand Up @@ -3860,7 +3880,7 @@ async fn deploy(
source, authorizer, ..
}): State<WebState>,
principal: Option<axum::Extension<AuthenticatedPrincipal>>,
Json(input): Json<DeployInput>,
DeployBody(input): DeployBody,
) -> Result<(StatusCode, HeaderMap, Json<ModuleStatus>), RestProblem> {
let request = input.try_into().map_err(RestProblem::invalid_argument)?;
dispatch_rest_command(
Expand Down Expand Up @@ -3899,15 +3919,15 @@ async fn deploy_from_manifest(
let input = serde_norway::from_str::<DeployInput>(&body).map_err(|error| {
RestProblem::invalid_argument(error.to_string())
})?;
deploy(State(state), principal, Json(input)).await
deploy(State(state), principal, DeployBody(input)).await
}
/// Replaces a deployed module with a complete, newly signed artifact. Unlike the Java descriptor
/// endpoint, this boundary never constructs executable content or a signature from a partial body.
async fn replace_module(
State(state): State<WebState>,
principal: Option<axum::Extension<AuthenticatedPrincipal>>,
Path(raw): Path<String>,
Json(input): Json<DeployInput>,
DeployBody(input): DeployBody,
) -> Result<Json<ModuleStatus>, RestProblem> {
let id = ModuleId::parse(raw).map_err(invalid_module_id)?;
if input.record.module_id != id {
Expand Down Expand Up @@ -5140,7 +5160,7 @@ mod tests {
signed_artifact: None,
};
let (status, headers, Json(module)) =
match deploy(State(WebState::new(source)), None, Json(input)).await {
match deploy(State(WebState::new(source)), None, DeployBody(input)).await {
Ok(response) => response,
Err(_) => panic!("fixture deploy must succeed"),
};
Expand All @@ -5162,6 +5182,48 @@ mod tests {
assert_eq!(error.code, "INVALID_ARGUMENT");
}
#[tokio::test]
async fn deploy_rejects_a_body_module_id_that_is_not_a_path_segment() {
let source = Arc::new(Source);
let input = DeployInput {
idempotency_key: "escape".into(),
expected_revision: None,
record: source
.module(&ModuleId::parse("hello").unwrap())
.unwrap()
.unwrap(),
routes: vec![],
signed_artifact: None,
};
let mut body = serde_json::to_value(&input).unwrap();
body["record"]["module_id"] = "../../escaped".into();
for (method, uri) in [("POST", "/platform/modules"), ("PUT", "/platform/modules/hello")] {
let response = router(source.clone())
.oneshot(
Request::builder()
.method(method)
.uri(uri)
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{method} {uri}");
assert_eq!(response.headers()["content-type"], "application/problem+json");
let json: Value = serde_json::from_slice(
&axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(),
)
.unwrap();
assert_eq!(json["code"], "INVALID_ARGUMENT");
assert!(json["detail"].as_str().unwrap().contains("invalid module id"), "{json}");
}
let yaml = serde_norway::to_string(&body).unwrap();
let error = deploy_from_manifest(State(WebState::new(source)), None, yaml)
.await
.expect_err("a traversal id in the manifest envelope must fail");
assert_eq!(error.code, "INVALID_ARGUMENT");
}
#[tokio::test]
async fn manifest_route_deploys_the_signed_envelope_yaml() {
let source = Arc::new(Source);
let input = DeployInput {
Expand Down Expand Up @@ -5222,7 +5284,7 @@ mod tests {
State(WebState::new(source)),
None,
Path("hello".into()),
Json(DeployInput {
DeployBody(DeployInput {
idempotency_key: "replace-hello".into(),
expected_revision: Some(Revision(1)),
record,
Expand All @@ -5249,7 +5311,7 @@ mod tests {
State(WebState::new(source)),
None,
Path("different".into()),
Json(DeployInput {
DeployBody(DeployInput {
idempotency_key: "replace-wrong-id".into(),
expected_revision: Some(Revision(1)),
record,
Expand Down
1 change: 1 addition & 0 deletions docs/design/24-http-admin-route-parity.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ Non-parity:
| --- | --- | --- | --- |
| REST module changes are not authorized by the controller | Denial is a 403 `FORBIDDEN` problem, as for config, scopes, and shared libs (design 17 §4.4, 29) | Same shape as the other authorized REST routes | `rest_module_errors_are_java_problems` |
| An id is looked up as given | A malformed id is a 400 `INVALID_ARGUMENT` before any lookup | A malformed id is a 400, not a 404 | same |
| The descriptor `id` in a deploy body is stored as given | 배포 envelope 의 `record.module_id` 와 서명 manifest 의 `id` 는 `ModuleId::parse` 를 거쳐서만 역직렬화된다. 거부된 JSON 본문(`POST`/`PUT`)과 manifest YAML 은 400 `INVALID_ARGUMENT` 이고, content type 오류는 axum 의 거부 그대로다 | id 는 저장소 디렉터리와 worker/OCI 제어 소켓 경로의 한 세그먼트라 `../` 같은 값이 경로를 벗어나지 못한다. 예전에는 JSON 본문 거부가 axum 의 422 평문이었다 | `deploy_rejects_a_body_module_id_that_is_not_a_path_segment`, `module_id_deserializes_only_through_parse` |
| A missing manifest field adds `missingFields` | Not added: the Rust manifest is a signed envelope that serde rejects as a whole | `detail` names the field | — |

## Module status non-parity
Expand Down