hyprstream_core/cli/sign_challenge.rs
1//! Handler for `hyprstream sign-challenge`.
2//!
3//! Signs an Ed25519 challenge using the local user identity key stored in the OS keyring.
4//!
5//! Two modes:
6//!
7//! 1. **Device flow**: `hyprstream sign-challenge ABCD-EFGH`
8//! - Fetches nonce from `GET /oauth/device/nonce?user_code=ABCD-EFGH`
9//! - Constructs challenge: `"{username}:{user_code_normalized}:{nonce}"`
10//! - Signs and POSTs to `/oauth/device/verify` automatically
11//! - Prints: `"✓ Device authorized for {username}."`
12//!
13//! 2. **Auth code flow**: `hyprstream sign-challenge --nonce <n> --code-challenge <cc>`
14//! - Derives the SSH-style key fingerprint (`SHA256:...`) of the local
15//! user signing key.
16//! - Constructs challenge: `"{fingerprint}:{nonce}:{code_challenge}"`
17//! - Prints: `"Fingerprint: {fingerprint}\nSignature: {base64}"`
18//! - User pastes these into the browser challenge form. The server
19//! resolves the username from the fingerprint via the pubkey reverse
20//! index — the client never declares an identity.
21// CLI handler intentionally prints to stdout/stderr for user interaction
22#![allow(clippy::print_stdout, clippy::print_stderr)]
23
24use anyhow::{Context, Result};
25use base64::engine::general_purpose::STANDARD;
26use base64::Engine;
27use ed25519_dalek::Signer;
28
29/// Handle `hyprstream sign-challenge [USER_CODE] [--nonce N] [--code-challenge CC]`
30///
31/// `config` is the already-loaded `HyprConfig` (honoring `--config`/env) so the
32/// OAuth issuer URL *and* the secrets directory holding the local self-signed
33/// cert are resolved from the user's selected configuration, not re-derived
34/// from defaults. `None` falls back to default config resolution.
35pub async fn handle_sign_challenge(
36 user_code: Option<String>,
37 nonce: Option<String>,
38 code_challenge: Option<String>,
39 server: Option<String>,
40 insecure: bool,
41 config: Option<&crate::config::HyprConfig>,
42) -> Result<()> {
43 // Load user identity key from OS keyring
44 let (signing_key, username) = load_user_signing_key()?;
45
46 match (user_code, nonce, code_challenge) {
47 // Device flow: sign-challenge ABCD-EFGH
48 (Some(user_code), None, None) => {
49 handle_device_flow(signing_key, username, user_code, server, insecure, config).await
50 }
51 // Auth code flow: sign-challenge --nonce N --code-challenge CC
52 (None, Some(nonce), Some(code_challenge)) => {
53 handle_auth_code_flow(signing_key, username, nonce, code_challenge)
54 }
55 // Missing args for auth code flow
56 (None, Some(_), None) => {
57 anyhow::bail!("--code-challenge is required when --nonce is specified")
58 }
59 (None, None, Some(_)) => {
60 anyhow::bail!("--nonce is required when --code-challenge is specified")
61 }
62 // Both modes specified — ambiguous
63 (Some(_), Some(_), _) | (Some(_), _, Some(_)) => {
64 anyhow::bail!(
65 "Specify either USER_CODE (device flow) or --nonce + --code-challenge (auth code flow)"
66 )
67 }
68 // No args at all
69 (None, None, None) => {
70 anyhow::bail!(
71 "Usage:\n \
72 hyprstream sign-challenge ABCD-EFGH\n \
73 hyprstream sign-challenge --nonce <nonce> --code-challenge <cc>"
74 )
75 }
76 }
77}
78
79/// Device flow: fetch nonce, sign, POST to /oauth/device/verify.
80async fn handle_device_flow(
81 signing_key: ed25519_dalek::SigningKey,
82 username: String,
83 user_code: String,
84 server: Option<String>,
85 insecure: bool,
86 config: Option<&crate::config::HyprConfig>,
87) -> Result<()> {
88 let base_url = resolve_server_url(server, config);
89 let normalized = user_code.replace('-', "").to_uppercase();
90
91 // Build an HTTP client that trusts the local self-signed dev cert by
92 // default (Option B), or — when `--insecure` is passed — disables TLS
93 // verification entirely (Option A, opt-in with a warning). Pass the
94 // loaded config so the cert is looked up in the --config-selected
95 // secrets directory, not a re-derived default location.
96 let client = build_oauth_http_client(insecure, config)?;
97
98 let nonce_url = format!("{}/oauth/device/nonce?user_code={}", base_url, normalized);
99 let resp = client
100 .get(&nonce_url)
101 .send()
102 .await
103 .context("Failed to reach OAuth server")?;
104
105 if !resp.status().is_success() {
106 let status = resp.status();
107 let body = resp.text().await.unwrap_or_default();
108 anyhow::bail!("Server returned {}: {}", status, body);
109 }
110
111 let json: serde_json::Value = resp
112 .json()
113 .await
114 .context("Invalid JSON from nonce endpoint")?;
115 let nonce = json["nonce"]
116 .as_str()
117 .context("Missing 'nonce' in server response")?;
118
119 // Construct and sign challenge: "{username}:{user_code_normalized}:{nonce}"
120 let challenge = format!("{}:{}:{}", username, normalized, nonce);
121 let signature = signing_key.sign(challenge.as_bytes());
122 let sig_b64 = STANDARD.encode(signature.to_bytes());
123
124 // POST to /oauth/device/verify.
125 // Send Accept: application/json so the server returns structured JSON errors
126 // instead of HTML (which would require fragile HTML parsing).
127 let verify_url = format!("{}/oauth/device/verify", base_url);
128 let resp = client
129 .post(&verify_url)
130 .header("Accept", "application/json")
131 .form(&[
132 ("user_code", user_code.as_str()),
133 ("username", username.as_str()),
134 ("signature", sig_b64.as_str()),
135 ])
136 .send()
137 .await
138 .context("Failed to POST to device verify endpoint")?;
139
140 if resp.status().is_success() {
141 println!("✓ Device authorized for {}.", username);
142 } else {
143 let status = resp.status();
144 let body = resp.text().await.unwrap_or_default();
145 // Parse JSON error_description returned by verify_post when Accept: application/json
146 let error_msg = serde_json::from_str::<serde_json::Value>(&body)
147 .ok()
148 .and_then(|v| {
149 v["error_description"]
150 .as_str()
151 .map(std::borrow::ToOwned::to_owned)
152 })
153 .unwrap_or_else(|| format!("Server returned {}", status));
154 anyhow::bail!("Authorization failed: {}", error_msg);
155 }
156
157 Ok(())
158}
159
160/// Auth code flow: sign and print Fingerprint + Signature for browser paste.
161fn handle_auth_code_flow(
162 signing_key: ed25519_dalek::SigningKey,
163 _username: String,
164 nonce: String,
165 code_challenge: String,
166) -> Result<()> {
167 let verifying_key = signing_key.verifying_key();
168 let fingerprint = crate::auth::pubkey_fingerprint(&verifying_key);
169
170 // Construct challenge: "{fingerprint}:{nonce}:{code_challenge}"
171 // The server resolves the user from the fingerprint via the pubkey
172 // reverse index — no username on the wire.
173 let challenge = format!("{}:{}:{}", fingerprint, nonce, code_challenge);
174 let signature = signing_key.sign(challenge.as_bytes());
175 let sig_b64 = STANDARD.encode(signature.to_bytes());
176
177 println!("Fingerprint: {}", fingerprint);
178 println!("Signature: {}", sig_b64);
179
180 Ok(())
181}
182
183/// Load the user's Ed25519 signing key from the configured secrets directory.
184///
185/// Returns `(signing_key, os_username)`. The OS username is kept for the
186/// device flow (which embeds it in the challenge string and posts it to
187/// `/oauth/device/verify`); the auth-code flow ignores it and uses the
188/// signing key's fingerprint instead.
189fn load_user_signing_key() -> Result<(ed25519_dalek::SigningKey, String)> {
190 // Device flow embeds the username in the challenge string. The OS user
191 // matches what the wizard registers; falls back to "anonymous" for the
192 // edge case where USER/LOGNAME aren't set.
193 let username = std::env::var("USER")
194 .or_else(|_| std::env::var("LOGNAME"))
195 .unwrap_or_else(|_| "anonymous".to_owned());
196
197 if let Some((sk, _vk)) = crate::config::HyprConfig::user_signing_key_bypass()? {
198 return Ok((sk, username));
199 }
200
201 let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir()?;
202 let (sk, _vk) = crate::auth::identity_store::load_or_generate_user_signing_key(&secrets_dir)
203 .map_err(|e| {
204 anyhow::anyhow!(
205 "Could not load user signing key: {e}\n\
206 Run 'hyprstream wizard' to set up your identity first."
207 )
208 })?;
209
210 Ok((sk, username))
211}
212
213/// Resolve the OAuth server URL from the option or the loaded config.
214///
215/// `config` is the already-loaded configuration (honoring `--config`/env).
216/// We must NOT call `HyprConfig::load()` here: that re-derives the *default*
217/// config location and would ignore a user-supplied `--config`, so the
218/// issuer URL (and, downstream, the secrets dir for the local dev cert)
219/// would be read from the wrong place (#450). When `config` is `None` we
220/// fall back to a fresh default load for backward compatibility.
221fn resolve_server_url(
222 server: Option<String>,
223 config: Option<&crate::config::HyprConfig>,
224) -> String {
225 if let Some(s) = server {
226 return s;
227 }
228 if let Some(c) = config {
229 return c.oauth.issuer_url();
230 }
231 crate::config::HyprConfig::load()
232 .map(|c| c.oauth.issuer_url())
233 .unwrap_or_else(|_| "http://localhost:6791".to_owned())
234}
235
236/// Name of the self-signed TLS certificate secret persisted in the shared
237/// secrets directory (see `auth::identity_store::load_or_generate_tls_materials`).
238const LOCAL_TLS_CERT_SECRET: &str = "tls-cert";
239
240/// Build the `reqwest::Client` used to reach the OAuth server.
241///
242/// Two modes, resolving issue #450:
243///
244/// - **`insecure = true`** (Option A, explicit opt-in via `--insecure`):
245/// disables certificate verification entirely with
246/// `danger_accept_invalid_certs(true)` and prints a warning to stderr.
247/// Use this only against throwaway dev servers where importing the cert
248/// is impractical.
249///
250/// - **`insecure = false`** (default, Option B): if the OAuth server uses the
251/// self-signed cert this project generates into the shared secrets
252/// directory (the default local-dev / air-gapped mode — see
253/// `server::tls` and `auth::identity_store::load_or_generate_tls_materials`),
254/// that cert is loaded and added as a trusted root. This makes
255/// `sign-challenge` "just work" against a local install *without* weakening
256/// TLS for any other host. The system trust store is still consulted for
257/// any cert it already trusts (e.g. a real CA-backed deployment), so adding
258/// the local dev cert is strictly additive. If the cert cannot be read
259/// (e.g. the secrets directory does not exist yet, or the server uses a
260/// real CA), we fall through to the system trust store.
261fn build_oauth_http_client(
262 insecure: bool,
263 config: Option<&crate::config::HyprConfig>,
264) -> Result<reqwest::Client> {
265 let mut builder = reqwest::Client::builder().timeout(std::time::Duration::from_secs(30));
266
267 if insecure {
268 // Explicit opt-in: blanket TLS bypass. Warn loudly — this defeats
269 // server authentication and must never be a default.
270 eprintln!(
271 "⚠️ --insecure: TLS certificate verification disabled. \
272 Only use against a trusted local dev server."
273 );
274 builder = builder.danger_accept_invalid_certs(true);
275 } else if let Some(cert_der) = load_local_tls_cert(config) {
276 // Trust the project's own self-signed dev cert (stored as DER).
277 // `from_pem` is backend-agnostic (works for both native-tls and
278 // rustls reqwest backends), so convert DER → PEM here.
279 match reqwest::Certificate::from_pem(&der_to_pem_cert(&cert_der)) {
280 Ok(cert) => {
281 builder = builder.add_root_certificate(cert);
282 }
283 Err(e) => {
284 // Don't hard-fail: a malformed local cert shouldn't block a
285 // user pointing at a real-CA server. Fall through to the
286 // system trust store.
287 tracing::debug!(
288 "could not parse local TLS cert as a root: {} \
289 (falling back to system trust store)",
290 e
291 );
292 }
293 }
294 }
295
296 builder.build().context("failed to build OAuth HTTP client")
297}
298
299/// Load the local self-signed TLS certificate (DER) from the shared secrets
300/// directory, if one is present.
301///
302/// `config` is the already-loaded configuration (honoring `--config`/env) so
303/// the secrets directory is resolved consistently with wherever the OAuth
304/// server itself is reading from — `resolve_secrets_dir_for(config)`, NOT a
305/// default re-derivation that would miss a custom `--config`.
306///
307/// Returns `None` silently when the secrets directory or the cert is absent —
308/// callers fall back to the system trust store.
309fn load_local_tls_cert(config: Option<&crate::config::HyprConfig>) -> Option<Vec<u8>> {
310 let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir_for(config).ok()?;
311 crate::auth::identity_store::read_secret(&secrets_dir, LOCAL_TLS_CERT_SECRET)
312 .ok()
313 .flatten()
314}
315
316/// Wrap DER-encoded certificate bytes as a PEM block.
317///
318/// reqwest's `Certificate::from_pem` is accepted by every TLS backend, while
319/// `from_der` is native-tls-only — so we convert here to stay backend-agnostic.
320fn der_to_pem_cert(der: &[u8]) -> Vec<u8> {
321 use base64::engine::general_purpose::STANDARD as B64;
322 // base64 output is always ASCII, so we can work in raw bytes and avoid
323 // any UTF-8 validation overhead (or `expect`).
324 let b64 = B64.encode(der);
325 let mut pem: Vec<u8> = Vec::with_capacity(b64.len() + 64);
326 pem.extend_from_slice(b"-----BEGIN CERTIFICATE-----\n");
327 for chunk in b64.as_bytes().chunks(64) {
328 pem.extend_from_slice(chunk);
329 pem.push(b'\n');
330 }
331 pem.extend_from_slice(b"-----END CERTIFICATE-----\n");
332 pem
333}
334
335#[cfg(test)]
336#[allow(clippy::unwrap_used, clippy::expect_used)]
337mod tests {
338 use super::*;
339
340 #[test]
341 fn der_to_pem_roundtrips_through_reqwest() {
342 // Generate a throwaway self-signed cert and confirm reqwest accepts
343 // the PEM we produce from its DER encoding.
344 let kp = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).expect("gen key");
345 let mut params =
346 rcgen::CertificateParams::new(vec!["localhost".to_owned()]).expect("params");
347 params.not_before = time::OffsetDateTime::now_utc();
348 params.not_after = time::OffsetDateTime::now_utc() + time::Duration::days(365);
349 let cert = params.self_signed(&kp).expect("self-signed");
350 let der = cert.der().to_vec();
351
352 let pem = der_to_pem_cert(&der);
353 assert!(pem.starts_with(b"-----BEGIN CERTIFICATE-----\n"));
354 assert!(pem.ends_with(b"-----END CERTIFICATE-----\n"));
355 reqwest::Certificate::from_pem(&pem)
356 .expect("reqwest must accept the PEM we produce from a valid DER cert");
357 }
358
359 #[test]
360 fn der_to_pem_wraps_at_64_columns() {
361 // 256 bytes of DER → base64 is longer than 64 chars, so we must wrap.
362 let der = vec![0u8; 256];
363 let pem = der_to_pem_cert(&der);
364 let text = std::str::from_utf8(&pem).unwrap();
365 for line in text.lines() {
366 // Header/footer lines are exempt; body lines must be ≤ 64 chars.
367 if line.starts_with("-----") {
368 continue;
369 }
370 assert!(line.len() <= 64, "PEM body line exceeds 64 cols: {line}");
371 }
372 }
373}