mirror of
https://github.com/rustfs/rustfs.git
synced 2026-09-09 13:46:05 +00:00
ae9fe62fb1
* fix(sse): resolve bucket default encryption per request PUT and the POST-object/extract path resolved a bucket's default encryption with a hard-coded "no explicit SSE-C" flag, so the default was layered onto a request that already carried an SSE-C header triple and then tripped that request's own mutual-exclusion check. Every bucket with default encryption refused SSE-C single PUTs with 400 InvalidArgument, while CreateMultipartUpload on the same bucket succeeded because it resolves SSE elsewhere. Both call sites now derive the flag from the request headers, as COPY already did. The bucket default's KMS key id was also inherited independently of the effective algorithm, so an explicit AES256 request against an aws:kms default bucket produced a self-contradictory algorithm/key-id pair and was rejected. The key id is now inherited only when the effective algorithm is aws:kms, matching the storage-layer resolver. Refs backlog#2368 B1, B2. * fix(sse): refuse SSE-KMS without a running KMS service A write requesting aws:kms on a node with no KMS service fell back to the node-local SSE-S3 provider: the data key was wrapped with RUSTFS_SSE_S3_MASTER_KEY while the object metadata still recorded aws:kms and the requested KMS key id. The stored object claimed a KMS protection it never had, under a key that was never consulted, and no signal distinguished it from a genuine SSE-KMS object. The managed-encryption path now asks the resolved DEK provider whether it wraps with a node-local master key and refuses SSE-KMS in that case: InvalidRequest when KMS was never configured, ServiceUnavailable when a configured service is not running. The check sits after the per-key authorization gate so an unauthorized caller still receives AccessDenied whatever the KMS runtime state is, and asks the provider rather than a parallel availability signal because the provider is what actually wraps the key. A missing master key no longer answers an SSE-KMS request with an SSE-S3-worded configuration error. The SSE-S3 local fallback is unchanged. Refs backlog#2368 B4. * fix(ecstore): restore and archive tiers in stored coordinates Multipart restore addressed the remote tier in plaintext coordinates while the copy-back reads the stored representation. Each part received a misaligned slice of the remote object whose length still satisfied the range, the hash reader and the completion size check, so the restore reported success and silently replaced the object's bytes. Encrypted and compressed multipart objects were both affected. Restore now accumulates stored part sizes, passes the stored length to the hash reader alongside the plaintext length, and validates against the stored size. The copy-back digests stored bytes, so its computed MD5 is not the object's public ETag. Restore now preserves the object ETag on both the single-part and multipart paths, and gives each restored part its own recorded part ETag rather than the object-level value. Transition also handed the tier the object's SSE headers and its RustFS-wrapped data key as request headers. Any S3 target rejected an SSE-C archive outright, an SSE-KMS archive asked the target to encrypt a second time under a key id it does not own, and the wrapped DEK left the cluster. The archive request now strips every SSE header and encryption marker with the predicate the replication path already uses; the local xl.meta keeps all of it, so read-through and restore are unaffected. Objects restored by an affected release are not detected or repaired retroactively and must be re-restored from the tier. Refs backlog#2368 B3, B5; backlog#2369 P7.1. * fix(rio): lock the v1 nonce layout within a segment Decrypting a v1 segment tried three historical nonce layouts per frame, independently for every frame. The last of them exists for streams written before 1.0.0-alpha.91, which reused a segment's part nonce for every block in it; because block zero's derived nonce equals that base nonce, a frame encrypted at index zero authenticated at any position. An attacker able to rewrite the underlying shards could replay it and have the forged plaintext returned with 200 and an unchanged length. Shard integrity uses a keyed-hash-free checksum, which such an attacker can recompute, so it is not a barrier. A segment now locks onto whichever layout decoded its first non-zero-index frame and rejects any later frame needing a different one. That leaves one residual shape: a stream built purely from repeats of frame zero has no later frame to disagree. New RUSTFS_ENCRYPTION_LEGACY_NONCE_FALLBACK (default true, so pre-alpha.91 objects keep decrypting) drops the third layout entirely when set to false, which closes it. Turning it off refuses pre-alpha.91 objects, so migrate them first by rewriting in place. Refs backlog#2369 P2. * fix(kms): reload a service that failed to start POST /rustfs/admin/v3/kms/reload short-circuited whenever the persisted configuration matched the in-memory one byte for byte. A node whose KMS failed to start keeps that configuration and sits in Error, so the documented recovery call returned "reloaded successfully" while leaving the node down. Peers reached the same path through the reload broadcast, so a cluster that lost Vault during a rolling restart had no working recovery route other than the node-local start endpoint. Reload now short-circuits only for a service that is actually running, and otherwise reconfigures, which starts a service that is not running. The AWS backend also advertised key-version enumeration through kms/status, which its own documentation says it cannot do; the capability and its golden snapshot now say false. Refs backlog#2369 P1, P7.3. * docs: record the SSE and KMS changes for 1.0.0 The Unreleased changelog section carried no entry for any encryption work merged since 1.0.0-rc.5, including three items with operational impact: the config-secret variable whose absence persists secrets in cleartext with only a warning, the v2 frame write switch and its rolling-upgrade constraint, and per-key authorization making a public bucket incompatible with SSE-KMS objects. Adds those plus this batch, including the SSE-KMS refusal as a breaking change with both routes out. Also corrects four places where documentation contradicted the code: the cleanup register still called encrypted range seek opt-in after its default flipped, the Helm README claimed vault_mount_path only applies to Transit while the template also feeds the KV2 mount, the disaster-recovery drill listed bundle contents for backends whose export is refused with 501, and the Chinese README capability table predated most of the feature set. Documents the SSE-S3 local master key as a first-class operational mode with its rotation dead end, and what the v1 frame layout does and does not authenticate. Refs backlog#2369 P5. * fix(kms): classify data-path KMS failures by what the caller can do Only "key not found" and a backend outage were classified; every other KMS failure that reached the S3 data path fell through to 500 InternalError with a generic message. A disabled or pending-deletion key, a denied KMS grant, an encryption-context mismatch, an unsupported algorithm, a credential or timeout failure, and a capability the configured backend does not have all looked identical to a server fault. SDKs therefore applied exponential backoff to configuration errors no retry can fix, and monitoring counted every one of them against the server's own error rate. Unusable-key and request-side failures now answer 400, a denied grant 403, transient backend failures 503, and a missing backend capability 501. Damaged, unreadable, or unknown-format key material keeps its 500: it is a server-side integrity fault, and existing tests pin it. The classifier is deliberately separate from the admin lifecycle mapping, which answers 404 for a missing key because there a key id is the resource being addressed; on the data path it arrives inside a request header or a bucket default. Messages either name what the caller asked for or stay generic, with deployment-side detail left on the error source the way the storage-IO mapping already does. Refs backlog#2368 B6. * fix(kms): track and renew static Vault tokens Token authentication hard-coded "this token carries no lease", so the renewal task never started, the remaining-TTL gauge was never published, and nothing looked wrong. `vault token create` grants a 768-hour TTL by default, so a cluster that had been healthy for a month turned every KMS call into a 403 and could not recover without a restart or a reconfigure. Production configuration validation only rejects the literal dev-token, so an ordinary expiring token reaches a whole cluster. The source now reads `auth/token/lookup-self` at login and adopts what Vault reports. A token with no expiry behaves exactly as before. An expiring renewable one is picked up by the existing renewal loop and renewed at half TTL like every other auth method. An expiring non-renewable one warns with its remaining lifetime and publishes the gauge, so the fail-closed window is visible before it arrives. The probe never fails the login: a policy that omits lookup-self, or a Vault that is briefly unreachable, warns and falls back to exactly the previous behaviour rather than taking down a deployment that works today. The scripted Vault test double answers the lookup out of band so existing scripts keep describing only the protocol under test. Refs backlog#2369 P3. * feat(sse): report SSE-C requests that arrive without TLS An SSE-C request carries the customer's AES key in a request header, so AWS S3 and MinIO both refuse one that did not arrive over TLS. RustFS accepted them on any transport: a plaintext hop hands the key to anyone on the path, and since the object cannot be read without that same key, the exposure lasts as long as the object does. Refusing outright is the correct end state but not a safe default to adopt inside a release window, because the project's own s3-tests and e2e lanes and most staging deployments speak plain HTTP. This release reports instead: each such request increments rustfs_ssec_plaintext_requests_total and logs one warning per process, so an operator can confirm nothing would break before the default flips. RUSTFS_SSE_C_REQUIRE_TLS=true opts into the AWS 400 now. The verdict is per connection rather than per deployment: the layer is built with whether this listener terminated TLS, and additionally accepts an https protocol forwarded by a proxy the trusted-proxy configuration already vetted. It sits beside the rate limiter, after the layer that makes a forwarded protocol trustworthy and after the request context, so a rejection can echo the request id. Refs backlog#2369 P7.2. * fix(kms): say what a node-local backend means for a cluster The Local backend keeps key material on each node's own disk and generates its Argon2id salt per node, so two nodes derive different keys from the same master_key and an object encrypted on one node cannot be decrypted on another. Behind a load balancer that surfaces as intermittent 500s on reads that succeeded moments earlier, with nothing tying the symptom to the cause: the only signal was a generic "development, testing and demos only" positioning warning that says nothing about what actually breaks. Configuring or reconfiguring Local while the deployment is distributed now logs a dedicated event and appends the consequence to the configure response, so the operator who made the change sees it. The product decision to warn rather than refuse is unchanged. Refs backlog#2369 P7.4. * docs: record the remaining SSE and KMS changes for 1.0.0 Adds changelog entries for the KMS data-path status classification, the Vault static-token lease probe, the SSE-C plaintext-transport report and its switch, and the node-local backend warning. Documents two things the backend security guide never stated: that SSE-C belongs on a secure transport, with the counter and switch to plan the change around, and that the Local backend cannot be shared by a multi-node deployment because each node derives different keys from the same master key. Refs backlog#2368 B6; backlog#2369 P3, P5, P7.2, P7.4. * fix(kms): report an unreadable key store as an outage on the S3 path A backend now distinguishes a key store it could not read from a key that is genuinely absent, but the S3 boundary collapsed the first one back onto 500 InternalError through the fallthrough for integrity faults. The distinction was therefore invisible to the client: a temporary key-directory outage looked exactly like a permanently damaged key record, and neither the status nor the metric said the request was worth retrying. An unreadable key store joins the retryable class and answers 503, next to a backend error and a credential failure. Damaged, unreadable or unknown-format key material keeps its 500. Refs backlog#2368 B6; builds on rustfs/rustfs#7470.
492 lines
19 KiB
Rust
492 lines
19 KiB
Rust
// Copyright 2024 RustFS Team
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
//! Minimal scripted HTTP responder standing in for a Vault server.
|
|
//!
|
|
//! Wiring tests need to observe how many Vault requests a code path performs
|
|
//! (retries, read-confirm recovery) without a live Vault. The responder serves
|
|
//! one canned response per incoming request in order, closes the connection
|
|
//! after each response, and records the `METHOD /path` sequence for
|
|
//! assertions. It intentionally implements just enough HTTP/1.1 for the
|
|
//! `vaultrs` reqwest client: no keep-alive, no chunked bodies.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
use tokio::net::{TcpListener, TcpStream};
|
|
|
|
/// One scripted connection outcome.
|
|
pub(crate) enum ScriptedResponse {
|
|
Http { status: u16, body: String },
|
|
Close,
|
|
}
|
|
|
|
impl ScriptedResponse {
|
|
/// A 200 response carrying `data` inside the standard Vault envelope.
|
|
pub(crate) fn ok(data: serde_json::Value) -> Self {
|
|
Self::Http {
|
|
status: 200,
|
|
body: serde_json::json!({
|
|
"request_id": "scripted",
|
|
"lease_id": "",
|
|
"lease_duration": 0,
|
|
"renewable": false,
|
|
"data": data,
|
|
})
|
|
.to_string(),
|
|
}
|
|
}
|
|
|
|
/// An error response in Vault's `{"errors": [...]}` format.
|
|
pub(crate) fn error(status: u16, message: &str) -> Self {
|
|
Self::Http {
|
|
status,
|
|
body: serde_json::json!({ "errors": [message] }).to_string(),
|
|
}
|
|
}
|
|
|
|
/// The 404 Vault answers a LIST of an empty path with: something routed the
|
|
/// request and found nothing under it, so the `errors` array comes back
|
|
/// empty. [`ScriptedResponse::error`] cannot stand in — it always fills
|
|
/// `errors`, which is what marks a 404 as an unrouted path instead.
|
|
pub(crate) fn empty_list_404() -> Self {
|
|
Self::Http {
|
|
status: 404,
|
|
body: serde_json::json!({ "errors": [] }).to_string(),
|
|
}
|
|
}
|
|
|
|
/// Close the connection after consuming a request without sending an HTTP response.
|
|
pub(crate) fn close() -> Self {
|
|
Self::Close
|
|
}
|
|
}
|
|
|
|
/// The `auth/token/lookup-self` answer every scripted Vault serves for free.
|
|
///
|
|
/// A Vault client now probes its token's remaining lifetime at login
|
|
/// (backlog#2369 P3), which is credential plumbing rather than the protocol any
|
|
/// of these tests is scripting. Answering it out of band keeps every existing
|
|
/// script meaningful: `ttl` 0 is Vault's "this token does not expire", so the
|
|
/// probe changes nothing about how a scripted test behaves.
|
|
pub(crate) fn token_lookup_self_response() -> String {
|
|
serde_json::json!({
|
|
"data": {
|
|
"accessor": "scripted-accessor",
|
|
"creation_time": 1_700_000_000u64,
|
|
"creation_ttl": 0,
|
|
"display_name": "token",
|
|
"entity_id": "",
|
|
"explicit_max_ttl": 0,
|
|
"id": "scripted-token",
|
|
"num_uses": 0,
|
|
"orphan": true,
|
|
"path": "auth/token/create",
|
|
"policies": ["default"],
|
|
"renewable": false,
|
|
"ttl": 0
|
|
}
|
|
})
|
|
.to_string()
|
|
}
|
|
|
|
/// Whether a recorded request line addresses the token self-lookup.
|
|
pub(crate) fn is_token_lookup_self(request_line: &str) -> bool {
|
|
request_line.contains("/v1/auth/token/lookup-self")
|
|
}
|
|
|
|
/// A scripted stand-in Vault listening on a loopback port.
|
|
pub(crate) struct ScriptedVault {
|
|
/// Base address (`http://127.0.0.1:port`) to point a Vault client at.
|
|
pub(crate) address: String,
|
|
requests: Arc<Mutex<Vec<(String, String)>>>,
|
|
kv2_state: Option<Arc<Mutex<Kv2State>>>,
|
|
}
|
|
|
|
impl ScriptedVault {
|
|
/// Bind a loopback listener and serve `responses` one per request.
|
|
///
|
|
/// Requests beyond the script get a 599 error so a test that under-scripts
|
|
/// fails loudly instead of hanging.
|
|
pub(crate) async fn serve(responses: Vec<ScriptedResponse>) -> Self {
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind scripted vault listener");
|
|
let address = format!("http://{}", listener.local_addr().expect("scripted vault local addr"));
|
|
let requests = Arc::new(Mutex::new(Vec::new()));
|
|
let recorded = Arc::clone(&requests);
|
|
|
|
tokio::spawn(async move {
|
|
let mut responses = responses.into_iter();
|
|
loop {
|
|
let Ok((stream, _)) = listener.accept().await else {
|
|
return;
|
|
};
|
|
let Some((request_line, body, mut stream)) = read_request(stream).await else {
|
|
continue;
|
|
};
|
|
if is_token_lookup_self(&request_line) {
|
|
// Served out of band so the credential probe does not
|
|
// consume a scripted response meant for the protocol under
|
|
// test, and is not recorded as one of its requests.
|
|
let body = token_lookup_self_response();
|
|
let payload = format!(
|
|
"HTTP/1.1 200 Scripted\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
|
|
body.len(),
|
|
);
|
|
let _ = stream.write_all(payload.as_bytes()).await;
|
|
let _ = stream.shutdown().await;
|
|
continue;
|
|
}
|
|
recorded
|
|
.lock()
|
|
.expect("scripted vault request log poisoned")
|
|
.push((request_line, body));
|
|
let response = responses
|
|
.next()
|
|
.unwrap_or_else(|| ScriptedResponse::error(599, "scripted vault: script exhausted"));
|
|
if let ScriptedResponse::Http { status, body } = response {
|
|
let payload = format!(
|
|
"HTTP/1.1 {status} Scripted\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
|
|
body.len(),
|
|
);
|
|
let _ = stream.write_all(payload.as_bytes()).await;
|
|
let _ = stream.shutdown().await;
|
|
}
|
|
}
|
|
});
|
|
|
|
Self {
|
|
address,
|
|
requests,
|
|
kv2_state: None,
|
|
}
|
|
}
|
|
|
|
/// Bind a small stateful KV2 responder for concurrency tests.
|
|
///
|
|
/// Unlike Self::serve, this responder evaluates CAS writes against a
|
|
/// shared in-memory record and handles connections concurrently. It models
|
|
/// only the KV2 data and metadata paths used by the rotation protocol; an
|
|
/// unknown request receives a 599 response so a test cannot silently
|
|
/// under-specify the Vault exchange.
|
|
pub(crate) async fn serve_kv2(key_path: &str, key_data: serde_json::Value) -> Self {
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind scripted vault listener");
|
|
let address = format!("http://{}", listener.local_addr().expect("scripted vault local addr"));
|
|
let requests = Arc::new(Mutex::new(Vec::new()));
|
|
let state = Arc::new(Mutex::new(Kv2State::new(key_data)));
|
|
let recorded = Arc::clone(&requests);
|
|
let state_for_server = Arc::clone(&state);
|
|
let key_path = key_path.to_string();
|
|
|
|
tokio::spawn(async move {
|
|
loop {
|
|
let Ok((stream, _)) = listener.accept().await else {
|
|
return;
|
|
};
|
|
let recorded = Arc::clone(&recorded);
|
|
let state = Arc::clone(&state_for_server);
|
|
let key_path = key_path.clone();
|
|
tokio::spawn(async move {
|
|
let Some((request_line, body, stream)) = read_request(stream).await else {
|
|
return;
|
|
};
|
|
if is_token_lookup_self(&request_line) {
|
|
// Credential plumbing, not part of the KV2 protocol
|
|
// this responder models; see token_lookup_self_response.
|
|
write_response(
|
|
stream,
|
|
ScriptedResponse::Http {
|
|
status: 200,
|
|
body: token_lookup_self_response(),
|
|
},
|
|
)
|
|
.await;
|
|
return;
|
|
}
|
|
recorded
|
|
.lock()
|
|
.expect("scripted vault request log poisoned")
|
|
.push((request_line.clone(), body.clone()));
|
|
let response = state
|
|
.lock()
|
|
.expect("scripted KV2 state poisoned")
|
|
.respond(&key_path, &request_line, &body);
|
|
write_response(stream, response).await;
|
|
});
|
|
}
|
|
});
|
|
|
|
Self {
|
|
address,
|
|
requests,
|
|
kv2_state: Some(state),
|
|
}
|
|
}
|
|
|
|
/// The `METHOD /path` lines of every request served so far, in order.
|
|
pub(crate) fn requests(&self) -> Vec<String> {
|
|
self.requests
|
|
.lock()
|
|
.expect("scripted vault request log poisoned")
|
|
.iter()
|
|
.map(|(line, _)| line.clone())
|
|
.collect()
|
|
}
|
|
|
|
/// The request bodies, in the same order as [`Self::requests`]; empty for
|
|
/// bodyless requests. Lets tests assert what a write actually persisted
|
|
/// (record contents, check-and-set options), not just that a write happened.
|
|
pub(crate) fn request_bodies(&self) -> Vec<String> {
|
|
self.requests
|
|
.lock()
|
|
.expect("scripted vault request log poisoned")
|
|
.iter()
|
|
.map(|(_, body)| body.clone())
|
|
.collect()
|
|
}
|
|
|
|
/// Snapshot the in-memory KV2 state used by Self::serve_kv2.
|
|
pub(crate) fn kv2_snapshot(&self) -> Option<Kv2Snapshot> {
|
|
self.kv2_state.as_ref().map(|state| {
|
|
let state = state.lock().expect("scripted KV2 state poisoned");
|
|
Kv2Snapshot {
|
|
current_data: state.current_data.clone(),
|
|
current_secret_version: state.current_secret_version,
|
|
version_records: state.version_records.clone(),
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
/// State captured by the stateful KV2 responder for assertions in wiring tests.
|
|
#[derive(Debug, Clone)]
|
|
pub(crate) struct Kv2Snapshot {
|
|
pub(crate) current_data: serde_json::Value,
|
|
pub(crate) current_secret_version: u64,
|
|
pub(crate) version_records: BTreeMap<u32, serde_json::Value>,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct Kv2State {
|
|
current_data: serde_json::Value,
|
|
current_secret_version: u64,
|
|
history: BTreeMap<u64, serde_json::Value>,
|
|
version_records: BTreeMap<u32, serde_json::Value>,
|
|
}
|
|
|
|
impl Kv2State {
|
|
fn new(current_data: serde_json::Value) -> Self {
|
|
let mut version_records = BTreeMap::new();
|
|
if current_data["baseline_version"].as_u64() == Some(1) {
|
|
version_records.insert(1, current_data.clone());
|
|
}
|
|
Self {
|
|
history: BTreeMap::from([(1, current_data.clone())]),
|
|
current_data,
|
|
current_secret_version: 1,
|
|
version_records,
|
|
}
|
|
}
|
|
|
|
fn respond(&mut self, key_path: &str, request_line: &str, body: &str) -> ScriptedResponse {
|
|
let Some((method, path)) = request_line.split_once(' ') else {
|
|
return ScriptedResponse::error(599, "scripted KV2: malformed request line");
|
|
};
|
|
let data_path = format!("/v1/secret/data/{key_path}");
|
|
let metadata_path = format!("/v1/secret/metadata/{key_path}");
|
|
let version_data_prefix = format!("{data_path}/versions/");
|
|
let version_metadata_path = format!("{metadata_path}/versions");
|
|
|
|
if method == "GET" && path == metadata_path {
|
|
return ScriptedResponse::ok(metadata_data(self.current_secret_version));
|
|
}
|
|
|
|
if method == "LIST" && path == version_metadata_path {
|
|
let keys = self.version_records.keys().map(u32::to_string).collect::<Vec<_>>();
|
|
return ScriptedResponse::ok(serde_json::json!({ "keys": keys }));
|
|
}
|
|
|
|
if let Some(version) = path
|
|
.strip_prefix(&version_data_prefix)
|
|
.and_then(|value| value.parse::<u32>().ok())
|
|
{
|
|
return match method {
|
|
"GET" => self
|
|
.version_records
|
|
.get(&version)
|
|
.cloned()
|
|
.map(read_data)
|
|
.unwrap_or_else(|| ScriptedResponse::error(404, "not found")),
|
|
"POST" => self.create_version_record(version, body),
|
|
_ => ScriptedResponse::error(599, "scripted KV2: unsupported version request"),
|
|
};
|
|
}
|
|
|
|
if method == "GET" && path.strip_prefix(&data_path).is_some() {
|
|
let version = path
|
|
.split_once("?version=")
|
|
.and_then(|(_, value)| value.parse::<u64>().ok())
|
|
.unwrap_or(self.current_secret_version);
|
|
return self
|
|
.history
|
|
.get(&version)
|
|
.cloned()
|
|
.map(read_data)
|
|
.unwrap_or_else(|| ScriptedResponse::error(404, "not found"));
|
|
}
|
|
|
|
if method == "POST" && path == data_path {
|
|
return self.write_current_record(body);
|
|
}
|
|
|
|
ScriptedResponse::error(599, "scripted KV2: unexpected request")
|
|
}
|
|
|
|
fn create_version_record(&mut self, version: u32, body: &str) -> ScriptedResponse {
|
|
let body: serde_json::Value = match serde_json::from_str(body) {
|
|
Ok(body) => body,
|
|
Err(_) => return ScriptedResponse::error(400, "invalid JSON"),
|
|
};
|
|
if body["options"]["cas"].as_u64() != Some(0) {
|
|
return ScriptedResponse::error(400, "version record requires create-only CAS");
|
|
}
|
|
if self.version_records.contains_key(&version) {
|
|
return ScriptedResponse::error(400, CAS_CONFLICT_MESSAGE);
|
|
}
|
|
let Some(data) = body.get("data").cloned() else {
|
|
return ScriptedResponse::error(400, "missing data");
|
|
};
|
|
self.version_records.insert(version, data);
|
|
write_ack(1)
|
|
}
|
|
|
|
fn write_current_record(&mut self, body: &str) -> ScriptedResponse {
|
|
let body: serde_json::Value = match serde_json::from_str(body) {
|
|
Ok(body) => body,
|
|
Err(_) => return ScriptedResponse::error(400, "invalid JSON"),
|
|
};
|
|
if body["options"]["cas"].as_u64() != Some(self.current_secret_version) {
|
|
return ScriptedResponse::error(400, CAS_CONFLICT_MESSAGE);
|
|
}
|
|
let Some(data) = body.get("data").cloned() else {
|
|
return ScriptedResponse::error(400, "missing data");
|
|
};
|
|
self.current_secret_version += 1;
|
|
self.current_data = data.clone();
|
|
self.history.insert(self.current_secret_version, data);
|
|
write_ack(self.current_secret_version)
|
|
}
|
|
}
|
|
|
|
const CAS_CONFLICT_MESSAGE: &str = "check-and-set parameter did not match the current version";
|
|
|
|
fn metadata_data(current_version: u64) -> serde_json::Value {
|
|
serde_json::json!({
|
|
"cas_required": false,
|
|
"created_time": "2026-01-01T00:00:00Z",
|
|
"current_version": current_version,
|
|
"delete_version_after": "0s",
|
|
"max_versions": 0,
|
|
"oldest_version": 0,
|
|
"updated_time": "2026-01-01T00:00:00Z",
|
|
"custom_metadata": null,
|
|
"versions": {},
|
|
})
|
|
}
|
|
|
|
fn read_data(data: serde_json::Value) -> ScriptedResponse {
|
|
ScriptedResponse::ok(serde_json::json!({
|
|
"data": data,
|
|
"metadata": {
|
|
"created_time": "2026-01-01T00:00:00Z",
|
|
"deletion_time": "",
|
|
"custom_metadata": null,
|
|
"destroyed": false,
|
|
"version": 1,
|
|
},
|
|
}))
|
|
}
|
|
|
|
fn write_ack(version: u64) -> ScriptedResponse {
|
|
ScriptedResponse::ok(serde_json::json!({
|
|
"created_time": "2026-01-01T00:00:00Z",
|
|
"custom_metadata": null,
|
|
"deletion_time": "",
|
|
"destroyed": false,
|
|
"version": version,
|
|
}))
|
|
}
|
|
|
|
async fn write_response(mut stream: TcpStream, response: ScriptedResponse) {
|
|
if let ScriptedResponse::Http { status, body } = response {
|
|
let payload = format!(
|
|
"HTTP/1.1 {status} Scripted\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
|
|
body.len(),
|
|
);
|
|
let _ = stream.write_all(payload.as_bytes()).await;
|
|
let _ = stream.shutdown().await;
|
|
}
|
|
}
|
|
|
|
/// Read one HTTP/1.1 request (head plus content-length body) and return its
|
|
/// `METHOD /path` line together with the body. Draining the body before
|
|
/// responding keeps the client from seeing a connection reset while it is
|
|
/// still writing.
|
|
async fn read_request(mut stream: TcpStream) -> Option<(String, String, TcpStream)> {
|
|
let mut buffer = Vec::new();
|
|
let mut chunk = [0u8; 4096];
|
|
let head_end = loop {
|
|
if let Some(position) = buffer.windows(4).position(|window| window == b"\r\n\r\n") {
|
|
break position + 4;
|
|
}
|
|
let read = stream.read(&mut chunk).await.ok()?;
|
|
if read == 0 {
|
|
return None;
|
|
}
|
|
buffer.extend_from_slice(&chunk[..read]);
|
|
};
|
|
|
|
let head = String::from_utf8_lossy(&buffer[..head_end]).into_owned();
|
|
let mut lines = head.lines();
|
|
let request_line = lines.next()?;
|
|
let mut parts = request_line.split_whitespace();
|
|
let method = parts.next()?;
|
|
let path = parts.next()?;
|
|
// rustify appends a lone "?" when an endpoint has no query parameters;
|
|
// strip it so assertions can use the plain path.
|
|
let path = path.strip_suffix('?').unwrap_or(path);
|
|
|
|
let content_length: usize = lines
|
|
.filter_map(|line| {
|
|
let (name, value) = line.split_once(':')?;
|
|
name.eq_ignore_ascii_case("content-length")
|
|
.then(|| value.trim().parse().ok())?
|
|
})
|
|
.next()
|
|
.unwrap_or(0);
|
|
let mut body = buffer[head_end..].to_vec();
|
|
let mut remaining = content_length.saturating_sub(body.len());
|
|
while remaining > 0 {
|
|
let read = stream.read(&mut chunk).await.ok()?;
|
|
if read == 0 {
|
|
break;
|
|
}
|
|
body.extend_from_slice(&chunk[..read]);
|
|
remaining = remaining.saturating_sub(read);
|
|
}
|
|
body.truncate(content_length);
|
|
|
|
Some((format!("{method} {path}"), String::from_utf8_lossy(&body).into_owned(), stream))
|
|
}
|