From 8151bdea5cb12589376d1f4bc4b31f73c60817ea Mon Sep 17 00:00:00 2001 From: eust-w Date: Wed, 29 Jul 2026 02:50:00 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20Make=20drosync=20HTTPS=20enforce?= =?UTF-8?q?ment=20configurable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/drosync/acceptance-report-2026-07-29.md | 35 ++++++--- docs/drosync/installation.md | 18 ++++- docs/drosync/testing-acceptance.md | 12 +++- scripts/drosync-capacity-acceptance.py | 11 ++- scripts/drosync-poc-acceptance.py | 49 +++++++++++-- tests/backend/drosync_acceptance_test.py | 31 +++++++- tools/drosync/crates/cli/src/main.rs | 33 ++++++++- tools/drosync/crates/daemon/src/lib.rs | 54 +++++++++++++- tools/drosync/crates/transfer/src/lib.rs | 76 +++++++++++++++++--- 9 files changed, 282 insertions(+), 37 deletions(-) diff --git a/docs/drosync/acceptance-report-2026-07-29.md b/docs/drosync/acceptance-report-2026-07-29.md index 62a54143..2857618e 100644 --- a/docs/drosync/acceptance-report-2026-07-29.md +++ b/docs/drosync/acceptance-report-2026-07-29.md @@ -4,18 +4,37 @@ `BLOCKED_EXTERNAL` -The implemented data path has passed real installed-client, POC API, BOS direct upload, 300 MiB multipart, unchanged/no-delete, two-device lease contention, keep-both, full-object SHA-256, and audit-linkage checks. The full production acceptance cannot be marked `PASS` because the POC has no trusted HTTPS listener, no Apple signing/notarization identity is available, and no approved 20 TiB quota/cost record or 100 GiB acceptance volume is available. +The implemented data path has passed real installed-client, POC API, BOS direct upload, 300 MiB multipart, unchanged/no-delete, two-device lease contention, keep-both, full-object SHA-256, and audit-linkage checks. HTTP is currently an explicitly accepted POC transport risk rather than an acceptance blocker. The full production acceptance still cannot be marked `PASS` because no Apple signing/notarization identity is available and no approved 20 TiB quota/cost record or 100 GiB acceptance volume is available. The currently deployed POC API reports commit `20d1c25966049faae3bd66ef8f279e63556e6c17`. The coordinator deployment uses image tag `419149c-poc-20260729-drosync-full2`; both deployments reported 2/2 ready replicas during this run. +## HTTP policy follow-up + +After freezing HTTP as an allowed current POC transport, the release-mode macOS +CLI, daemon, and GUI were rebuilt, ad-hoc signed, installed in the existing +per-user location, and the LaunchAgent was restarted without replacing SQLite, +Keychain, or session history. + +- `http://120.48.164.19/api/health` returned `status=ok` from deployed commit + `20d1c25966049faae3bd66ef8f279e63556e6c17`. +- Default `drosync configure --server http://120.48.164.19` succeeded and returned + `transportSecurity.encrypted=false`, `requireHttps=false`, and the accepted-risk + warning. +- Repeating configure with `--require-https` rejected the same endpoint with + exit code 50 and did not overwrite the stored permissive policy. +- The restarted daemon reported `running`, zero mappings, and its socket and + SQLite file remained mode `0600`. +- Rust tests separately prove that this exception is scoped to the control-plane + base URL: public HTTP presigned uploads remain rejected. + ## Layer status | Layer | Status | Evidence | |---|---|---| | Source and contract | PASS | Scoped Key/Secret auth, automatic device registration, resumable multipart, fencing/keep-both, cleanup-aware runners, OpenAPI generation, and Web controls are present in the commit containing this report. | | Automated gates | PASS | Full Go tests, targeted Go race tests, Rust fmt/Clippy/workspace/doc tests, 248 React tests, Web build/typecheck, OpenAPI generation check, and Kubernetes rendering passed. | -| POC API deployment | PASS | Public HTTP health returned `ok`; API and coordinator were both 2/2 ready. This does not satisfy the HTTPS gate. | -| Trusted public HTTPS | BLOCKED_EXTERNAL | `https://120.48.164.19/api/health` returned no TLS response; the cluster has no configured trusted ingress/certificate path. | +| POC API deployment | PASS | Public HTTP health returned `ok`; API and coordinator were both 2/2 ready. The current policy allows HTTP and records it as unencrypted accepted risk. | +| Trusted public HTTPS | NOT_RUN | The current POC policy does not require HTTPS. A strict run can be enabled later with `--require-https`; the current endpoint has no configured trusted ingress/certificate path. | | Installed macOS client | PASS | `drosync 1.0.0`, protocol `v1`, macOS arm64; LaunchAgent running; IPC socket and SQLite state are mode `0600`. | | Apple signature/notarization | BLOCKED_EXTERNAL | The installed binary is ad-hoc signed and the machine reports zero valid code-signing identities. | | Browser control plane | PASS | Real POC admin session verified separate BOS AK/SK validation and drosync Key/Secret management, automatic device registration, Session states, keep-both conflict, and audit views. Execution used diagnostic HTTP. | @@ -29,7 +48,7 @@ The currently deployed POC API reports commit `20d1c25966049faae3bd66ef8f279e635 | Crash/network recovery | NOT_RUN | Retry and resume paths are covered by source tests, but real response loss, daemon kill/restart, API/coordinator restart, and URL renewal were not injected in this POC run. | | Release/daily audit seal | NOT_RUN | No immutable Release, signed daily seal, or exported CSV/NDJSON artifact was certified against real BOS in this run. | | Windows/Linux runtime | NOT_RUN | The frozen scope only requires macOS as this run's real-install gate; Windows/Linux runtime installation was not claimed. | -| Formal capacity | BLOCKED_EXTERNAL | Trusted HTTPS, an approved BOS quota/cost record, and a volume with at least 100 GiB free are absent. The Mac has about 22 GiB free. | +| Formal capacity | BLOCKED_EXTERNAL | An approved BOS quota/cost record and a volume with at least 100 GiB free are absent. The Mac has about 22 GiB free. HTTP is no longer a capacity-runner blocker under the current policy. | ## Real data evidence @@ -49,7 +68,7 @@ The currently deployed POC API reports commit `20d1c25966049faae3bd66ef8f279e635 - Hidden file, temporary suffix, and symlink did not reach the manifest. - The remote 1-byte object remained after the local copy was deleted. -The raw report is retained at `.codex-artifacts/drosync-acceptance-20260729/poc/20260728T174925Z-ffcf70ee/report.json`. It was produced before the runner's status-semantics fix and therefore says `FAIL` solely because the URL was HTTP; its functional layers are `PASS` and `publicHttps` is `BLOCKED_EXTERNAL`. Future diagnostic-HTTP runs report top-level `BLOCKED_EXTERNAL`. +The raw report is retained at `.codex-artifacts/drosync-acceptance-20260729/poc/20260728T174925Z-ffcf70ee/report.json`. It predates the configurable transport policy and therefore says `FAIL` solely because the URL was HTTP; its functional layers are `PASS` and `publicHttps` is `BLOCKED_EXTERNAL`. New default-policy HTTP runs can report top-level `PASS` and include `controlPlaneTransport.encrypted=false`; strict runs still block HTTP. ### Two-device conflict run @@ -85,7 +104,7 @@ The estimate must be refreshed and explicitly approved before execution. Referen ## Remaining production decisions and external inputs -1. Provide the trusted POC hostname, ingress/load-balancer TLS configuration, and certificate chain. -2. Provide Apple Developer ID Application/Installer identities and notarization credentials through CI secrets. -3. Approve the refreshed capacity estimate and provide written BOS quota evidence plus a dedicated volume with at least 100 GiB free. +1. Provide Apple Developer ID Application/Installer identities and notarization credentials through CI secrets. +2. Approve the refreshed capacity estimate and provide written BOS quota evidence plus a dedicated volume with at least 100 GiB free. +3. Decide when the control-plane policy should switch from accepted-risk HTTP to strict HTTPS; the implementation no longer makes that a current prerequisite. 4. Decide whether to authorize the >5 GiB copy, real update/drift, destructive-but-recoverable fault injection, signed update, Release, and daily-seal runs in the next acceptance window. diff --git a/docs/drosync/installation.md b/docs/drosync/installation.md index eb180202..399f0840 100644 --- a/docs/drosync/installation.md +++ b/docs/drosync/installation.md @@ -2,7 +2,8 @@ ## Common prerequisites -- The control-plane base URL must be reachable over public HTTPS. +- The control-plane base URL may use HTTP or HTTPS. HTTP is currently allowed for POC deployments, but it sends drosync credentials and control-plane metadata without transport encryption. Use an isolated network or accepted-risk POC endpoint only. +- Add `--require-https` to `configure` and `auth` when a deployment must reject HTTP. The daemon persists this policy with the profile. - An administrator creates a scoped drosync Access Key ID/Secret in `对象存储` → `密钥验证`. The scope fixes the allowed Space, relative prefix, and actions. The Secret is displayed only once. - `drosync auth` validates that Key/Secret directly and automatically registers the device for audit; there is no short-code or manual device approval. - For the initial headless authentication, read the drosync Secret from a `0600` file with `--secret-file` or inject it through `DROSYNC_SECRET`. After authentication, the daemon reads its bearer token from the OS credential store, `DROSYNC_TOKEN`, or a `0600` file named by `DROSYNC_SECRET_FILE`. @@ -52,3 +53,18 @@ drosync doctor drosync plan drosync sync ``` + +For a strict profile, configure and authenticate with the same policy: + +```bash +drosync configure --server https://data.example.com --require-https +drosync auth --server https://data.example.com --profile default \ + --access-key-id dsk_example --secret-file /run/secrets/drosync-client-secret \ + --require-https +``` + +When an `http://` endpoint is accepted, CLI JSON and human-readable output include +`transportSecurity.encrypted=false` and the corresponding accepted-risk message. +This exception applies only to the control-plane endpoint. Public BOS presigned +uploads and update artifacts remain HTTPS-only; loopback HTTP remains available +for local test fixtures. diff --git a/docs/drosync/testing-acceptance.md b/docs/drosync/testing-acceptance.md index 4f44ffac..0508fde2 100644 --- a/docs/drosync/testing-acceptance.md +++ b/docs/drosync/testing-acceptance.md @@ -8,16 +8,22 @@ Functional POC acceptance creates an isolated Space/prefix and scoped client Key ```bash npm run acceptance:drosync-poc -- \ - --base-url https://poc.example.com \ + --base-url http://poc.example.com \ --connection-id osc_example \ --bucket acceptance-bucket ``` -The formal capacity runner refuses HTTP, a local volume with less than 100 GiB free, a group/world-readable Secret file, missing BOS price/quota records, or an absent explicit real-cost confirmation. Its defaults are the formal targets; reduced values produce `DIAGNOSTIC_PASS`, never `PASS`. +Both runners accept HTTP and HTTPS by default. An HTTP run records +`encrypted=false` plus an accepted-risk warning; it is not by itself a functional +acceptance blocker. Add `--require-https` or set +`DROSYNC_ACCEPTANCE_REQUIRE_HTTPS=true` when validating a deployment whose policy +requires TLS. + +The formal capacity runner refuses a local volume with less than 100 GiB free, a group/world-readable Secret file, missing BOS price/quota records, or an absent explicit real-cost confirmation. Its defaults are the formal targets; reduced values produce `DIAGNOSTIC_PASS`, never `PASS`. ```bash npm run acceptance:drosync-capacity -- \ - --base-url https://poc.example.com \ + --base-url http://poc.example.com \ --connection-id osc_example \ --bucket acceptance-bucket \ --space-id oss_capacity \ diff --git a/scripts/drosync-capacity-acceptance.py b/scripts/drosync-capacity-acceptance.py index 5045c279..e8432a55 100644 --- a/scripts/drosync-capacity-acceptance.py +++ b/scripts/drosync-capacity-acceptance.py @@ -40,6 +40,7 @@ ExternalBlock = COMMON["ExternalBlock"] object_path = COMMON["object_path"] redact = COMMON["redact"] run_json = COMMON["run_json"] +transport_security = COMMON["transport_security"] utc_now = COMMON["utc_now"] wait_for_session = COMMON["wait_for_session"] @@ -68,6 +69,12 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--evidence-dir", default=".codex-artifacts/drosync-capacity") parser.add_argument("--retain-local", action="store_true") parser.add_argument("--resume-fixtures", action="store_true") + parser.add_argument( + "--require-https", + action="store_true", + default=os.getenv("DROSYNC_ACCEPTANCE_REQUIRE_HTTPS", "").lower() in {"1", "true", "yes"}, + help="reject an HTTP control-plane URL; HTTP is allowed by default", + ) return parser.parse_args() @@ -198,8 +205,7 @@ def main() -> int: try: if args.confirmation != CONFIRMATION: raise ExternalBlock(f"--confirmation must exactly equal {CONFIRMATION}") - if urllib.parse.urlparse(args.base_url).scheme != "https": - raise ExternalBlock("formal capacity certification requires trusted HTTPS") + transport = transport_security(args.base_url, args.require_https) required = { "--base-url": args.base_url, "--connection-id": args.connection_id, @@ -239,6 +245,7 @@ def main() -> int: report["preflight"] = { "status": "PASS", "baseUrl": args.base_url, + "transportSecurity": transport, "volume": str(volume), "volumeFreeBytes": usage.free, "costRecord": str(pathlib.Path(args.bos_cost_record).resolve()), diff --git a/scripts/drosync-poc-acceptance.py b/scripts/drosync-poc-acceptance.py index 63dacac0..8e2fac3a 100644 --- a/scripts/drosync-poc-acceptance.py +++ b/scripts/drosync-poc-acceptance.py @@ -190,10 +190,30 @@ def wait_for_session(api: API, mapping_id: str, after: str, timeout: int = 900) raise AcceptanceError(f"session for mapping {mapping_id} did not reach a terminal state") -def acceptance_status(public_scheme: str, audit_present: bool) -> str: +def transport_security(base_url: str, require_https: bool) -> dict[str, Any]: + parsed = urllib.parse.urlparse(base_url) + if parsed.scheme not in {"http", "https"} or not parsed.netloc: + raise ExternalBlock("control-plane base URL must be an absolute http:// or https:// URL") + if require_https and parsed.scheme != "https": + raise ExternalBlock("this acceptance run was configured to require HTTPS") + encrypted = parsed.scheme == "https" + return { + "status": "PASS", + "scheme": parsed.scheme, + "encrypted": encrypted, + "requireHttps": require_https, + "acceptedRisk": ( + None + if encrypted + else "control-plane credentials and metadata use an unencrypted HTTP connection" + ), + } + + +def acceptance_status(public_scheme: str, audit_present: bool, require_https: bool = False) -> str: if not audit_present: return "FAIL" - if public_scheme != "https": + if require_https and public_scheme != "https": return "BLOCKED_EXTERNAL" return "PASS" @@ -211,7 +231,17 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--stability-seconds", type=int, default=60) parser.add_argument("--multipart-bytes", type=int, default=300 * 1024 * 1024) parser.add_argument("--evidence-dir", default=".codex-artifacts/drosync-acceptance") - parser.add_argument("--diagnostic-http", action="store_true") + parser.add_argument( + "--require-https", + action="store_true", + default=os.getenv("DROSYNC_ACCEPTANCE_REQUIRE_HTTPS", "").lower() in {"1", "true", "yes"}, + help="reject an HTTP control-plane URL; HTTP is allowed by default for the current POC", + ) + parser.add_argument( + "--diagnostic-http", + action="store_true", + help=argparse.SUPPRESS, + ) parser.add_argument("--keep-workdir", action="store_true") return parser.parse_args() @@ -237,9 +267,8 @@ def main() -> int: try: if not args.base_url or not args.connection_id or not args.bucket: raise ExternalBlock("--base-url, --connection-id and --bucket are required") + transport = transport_security(args.base_url, args.require_https) parsed = urllib.parse.urlparse(args.base_url) - if parsed.scheme != "https" and not (args.diagnostic_http and parsed.scheme == "http"): - raise ExternalBlock("POC must expose a trusted HTTPS base URL; HTTP is diagnostic-only") if shutil.which(args.drosync_bin) is None and not pathlib.Path(args.drosync_bin).exists(): raise ExternalBlock(f"drosync executable was not found: {args.drosync_bin}") api = API(args.base_url, args.api_token) @@ -455,13 +484,19 @@ def main() -> int: }, "realBos": {"status": "PASS", "objects": remote_evidence, "remoteDelete": "not_performed"}, "audit": {"status": "PASS" if related_audit else "FAIL", "events": redact(related_audit)}, + "controlPlaneTransport": {**transport, "baseUrl": args.base_url}, "publicHttps": { - "status": "PASS" if parsed.scheme == "https" else "BLOCKED_EXTERNAL", + "status": "PASS" if parsed.scheme == "https" else "NOT_RUN", + "required": args.require_https, "baseUrl": args.base_url, }, } ) - report["status"] = acceptance_status(parsed.scheme, bool(related_audit)) + report["status"] = acceptance_status( + parsed.scheme, + bool(related_audit), + args.require_https, + ) except ExternalBlock as error: report["status"] = "BLOCKED_EXTERNAL" report["error"] = str(error) diff --git a/tests/backend/drosync_acceptance_test.py b/tests/backend/drosync_acceptance_test.py index d42325c3..b2436c82 100644 --- a/tests/backend/drosync_acceptance_test.py +++ b/tests/backend/drosync_acceptance_test.py @@ -15,8 +15,35 @@ def test_acceptance_status_requires_audit() -> None: assert acceptance_status("http", False) == "FAIL" -def test_acceptance_status_distinguishes_external_https_block() -> None: +def test_acceptance_status_only_enforces_https_in_strict_mode() -> None: acceptance_status = SCRIPT["acceptance_status"] - assert acceptance_status("http", True) == "BLOCKED_EXTERNAL" + assert acceptance_status("http", True) == "PASS" + assert acceptance_status("http", True, True) == "BLOCKED_EXTERNAL" + assert acceptance_status("https", True, True) == "PASS" assert acceptance_status("https", True) == "PASS" + + +def test_transport_security_records_http_as_an_accepted_risk() -> None: + transport_security = SCRIPT["transport_security"] + + evidence = transport_security("http://poc.example.com", False) + assert evidence == { + "status": "PASS", + "scheme": "http", + "encrypted": False, + "requireHttps": False, + "acceptedRisk": "control-plane credentials and metadata use an unencrypted HTTP connection", + } + + +def test_transport_security_rejects_http_in_strict_mode() -> None: + transport_security = SCRIPT["transport_security"] + external_block = SCRIPT["ExternalBlock"] + + try: + transport_security("http://poc.example.com", True) + except external_block: + pass + else: + raise AssertionError("strict transport policy accepted HTTP") diff --git a/tools/drosync/crates/cli/src/main.rs b/tools/drosync/crates/cli/src/main.rs index 7d17492c..fa433bd0 100644 --- a/tools/drosync/crates/cli/src/main.rs +++ b/tools/drosync/crates/cli/src/main.rs @@ -46,6 +46,8 @@ enum Command { struct Configure { #[arg(long)] server: String, + #[arg(long)] + require_https: bool, } #[derive(Debug, Args)] @@ -62,6 +64,8 @@ struct Auth { secret_file: Option, #[arg(long)] secret_stdin: bool, + #[arg(long)] + require_https: bool, } #[derive(Debug, Args)] @@ -202,7 +206,16 @@ fn exit_code_for(error: &anyhow::Error) -> u8 { #[allow(clippy::too_many_lines)] async fn execute(app: &App) -> Result { match &app.command { - Command::Configure(input) => ipc("configure", json!({"serverUrl": input.server})).await, + Command::Configure(input) => { + ipc( + "configure", + json!({ + "serverUrl": input.server, + "requireHttps": input.require_https, + }), + ) + .await + } Command::Auth(input) => { let access_key_id = input .access_key_id @@ -228,7 +241,13 @@ async fn execute(app: &App) -> Result { if secret.is_empty() { return Err(anyhow!("drosync access key secret must not be empty")); } - let client = drosync_transfer::Client::new(&input.server, None)?; + let transport_policy = if input.require_https { + drosync_transfer::TransportSecurityPolicy::RequireHttps + } else { + drosync_transfer::TransportSecurityPolicy::AllowHttp + }; + let client = + drosync_transfer::Client::new_with_policy(&input.server, None, transport_policy)?; let device_id = drosync_platform::load_or_create_device_id(&input.profile)?; let authenticated = client .authenticate_access_key(&AccessKeyAuthentication { @@ -247,6 +266,7 @@ async fn execute(app: &App) -> Result { "serverUrl": input.server, "credentialProfile": input.profile, "accessToken": authenticated.access_token, + "requireHttps": input.require_https, }), ) .await?; @@ -255,6 +275,15 @@ async fn execute(app: &App) -> Result { "accessKeyId": access_key_id, "profile": input.profile, "scopeCount": authenticated.scopes.len(), + "transportSecurity": { + "encrypted": input.server.trim().to_ascii_lowercase().starts_with("https://"), + "requireHttps": input.require_https, + "acceptedRisk": if input.server.trim().to_ascii_lowercase().starts_with("http://") { + Value::String("control-plane credentials and metadata use an unencrypted HTTP connection".to_owned()) + } else { + Value::Null + }, + }, })) } Command::Mapping(input) => match &input.command { diff --git a/tools/drosync/crates/daemon/src/lib.rs b/tools/drosync/crates/daemon/src/lib.rs index 70bd0dc4..1b28ebd4 100644 --- a/tools/drosync/crates/daemon/src/lib.rs +++ b/tools/drosync/crates/daemon/src/lib.rs @@ -8,7 +8,7 @@ use drosync_protocol::{ ManifestPage, MultipartPart, PROTOCOL_VERSION, SessionCreate, SessionRecord, SessionStatus, }; use drosync_state::{StateStore, StoredPart}; -use drosync_transfer::{Client, content_md5}; +use drosync_transfer::{Client, TransportSecurityPolicy, content_md5}; use notify::{RecursiveMode, Watcher}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -98,7 +98,19 @@ fn load_transfer_client(state: &StateStore) -> Result { let token = drosync_platform::load_runtime_credential(&profile).context( "load device credential from OS credential store, DROSYNC_TOKEN, or DROSYNC_SECRET_FILE", )?; - Ok(Client::new(server_url, Some(token))?) + let transport_policy = if state + .get_meta("transport_require_https")? + .is_some_and(|value| value.eq_ignore_ascii_case("true")) + { + TransportSecurityPolicy::RequireHttps + } else { + TransportSecurityPolicy::AllowHttp + }; + Ok(Client::new_with_policy( + server_url, + Some(token), + transport_policy, + )?) } fn is_paused(state: &StateStore) -> Result { @@ -716,7 +728,19 @@ async fn dispatch(state: &mut StateStore, request: IpcRequest) -> IpcResponse { .and_then(Value::as_str) .ok_or_else(|| anyhow!("serverUrl is required")); server_url.and_then(|value| { + let require_https = request + .arguments + .get("requireHttps") + .and_then(Value::as_bool) + .unwrap_or(false); + let transport_policy = if require_https { + TransportSecurityPolicy::RequireHttps + } else { + TransportSecurityPolicy::AllowHttp + }; + Client::new_with_policy(value, None, transport_policy)?; state.set_meta("server_url", value)?; + state.set_meta("transport_require_https", &require_https.to_string())?; if let Some(profile) = request .arguments .get("credentialProfile") @@ -724,7 +748,18 @@ async fn dispatch(state: &mut StateStore, request: IpcRequest) -> IpcResponse { { state.set_meta("credential_profile", profile)?; } - Ok(serde_json::json!({"serverUrl": value})) + Ok(serde_json::json!({ + "serverUrl": value, + "transportSecurity": { + "encrypted": value.trim().to_ascii_lowercase().starts_with("https://"), + "requireHttps": require_https, + "acceptedRisk": if value.trim().to_ascii_lowercase().starts_with("http://") { + Value::String("control-plane credentials and metadata use an unencrypted HTTP connection".to_owned()) + } else { + Value::Null + }, + }, + })) }) } "credential.store" => { @@ -752,12 +787,25 @@ async fn dispatch(state: &mut StateStore, request: IpcRequest) -> IpcResponse { server_url.and_then(|server_url| { let profile = profile?; let access_token = access_token?; + let require_https = request + .arguments + .get("requireHttps") + .and_then(Value::as_bool) + .unwrap_or(false); + let transport_policy = if require_https { + TransportSecurityPolicy::RequireHttps + } else { + TransportSecurityPolicy::AllowHttp + }; + Client::new_with_policy(server_url, None, transport_policy)?; drosync_platform::save_credential(profile, access_token)?; state.set_meta("server_url", server_url)?; state.set_meta("credential_profile", profile)?; + state.set_meta("transport_require_https", &require_https.to_string())?; Ok(serde_json::json!({ "serverUrl": server_url, "credentialProfile": profile, + "requireHttps": require_https, })) }) } diff --git a/tools/drosync/crates/transfer/src/lib.rs b/tools/drosync/crates/transfer/src/lib.rs index dd05289d..238d2137 100644 --- a/tools/drosync/crates/transfer/src/lib.rs +++ b/tools/drosync/crates/transfer/src/lib.rs @@ -47,13 +47,27 @@ pub struct Client { permits: Arc, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TransportSecurityPolicy { + AllowHttp, + RequireHttps, +} + impl Client { pub fn new( base_url: impl Into, credential: Option, + ) -> Result { + Self::new_with_policy(base_url, credential, TransportSecurityPolicy::AllowHttp) + } + + pub fn new_with_policy( + base_url: impl Into, + credential: Option, + transport_policy: TransportSecurityPolicy, ) -> Result { let base_url = base_url.into().trim_end_matches('/').to_owned(); - validate_transport_url(&base_url)?; + validate_control_plane_url(&base_url, transport_policy)?; Ok(Self { base_url, credential, @@ -387,7 +401,7 @@ impl Client { size: u64, headers: &[(String, String)], ) -> Result { - validate_transport_url(url)?; + validate_presigned_url(url)?; let _permit = self.permit().await?; let mut file = tokio::fs::File::open(path).await?; file.seek(std::io::SeekFrom::Start(offset)).await?; @@ -420,7 +434,28 @@ impl Client { } } -fn validate_transport_url(value: &str) -> Result<(), TransferError> { +fn validate_control_plane_url( + value: &str, + transport_policy: TransportSecurityPolicy, +) -> Result<(), TransferError> { + let parsed = reqwest::Url::parse(value) + .map_err(|error| TransferError::InvalidEndpoint(error.to_string()))?; + if parsed.scheme() == "https" + || (parsed.scheme() == "http" && transport_policy == TransportSecurityPolicy::AllowHttp) + { + return Ok(()); + } + if parsed.scheme() == "http" { + return Err(TransferError::InvalidEndpoint( + "this client profile requires an HTTPS control-plane endpoint".to_owned(), + )); + } + Err(TransferError::InvalidEndpoint( + "control-plane endpoint must use http or https".to_owned(), + )) +} + +fn validate_presigned_url(value: &str) -> Result<(), TransferError> { let parsed = reqwest::Url::parse(value) .map_err(|error| TransferError::InvalidEndpoint(error.to_string()))?; if parsed.scheme() == "https" { @@ -435,7 +470,7 @@ fn validate_transport_url(value: &str) -> Result<(), TransferError> { return Ok(()); } Err(TransferError::InvalidEndpoint( - "HTTPS is required except for loopback development endpoints".to_owned(), + "HTTPS is required for presigned uploads except on loopback".to_owned(), )) } @@ -477,15 +512,38 @@ pub async fn content_md5(path: &Path, offset: u64, size: u64) -> Result