1use std::fs::{self, File, OpenOptions};
4use std::io::{self, IsTerminal as _, Read as _, Write as _};
5use std::os::unix::fs::OpenOptionsExt as _;
6use std::path::{Path, PathBuf};
7
8use serde_json::json;
9use stratum_node_core::{DidNostr, NostrSecretKey, ParsePodPathError, PodPath};
10
11use crate::error::CliError;
12use crate::exit;
13use crate::gate::{
14 self, GateClient, Head, Precondition, Request, Route, ANY, LD_JSON, MAX_LISTING_BYTES,
15 MAX_RESOURCE_BYTES,
16};
17use crate::listing::{self, Child};
18use crate::origin::GateTarget;
19use crate::output::sanitize;
20use crate::session::{Confirmation, Session};
21
22const TURTLE: &str = "text/turtle";
24
25const OCTET_STREAM: &str = "application/octet-stream";
27
28#[derive(Debug, Clone, PartialEq, Eq, Default)]
30#[non_exhaustive]
31pub enum WriteCondition {
32 #[default]
34 Always,
35 IfMatch(String),
39 CreateOnly,
42}
43
44#[derive(Debug, Clone, Default)]
46pub struct PutOptions {
47 pub path: String,
51 pub file: PathBuf,
53 pub content_type: Option<String>,
56 pub condition: WriteCondition,
58}
59
60impl Session {
61 pub fn pod_ls(&self, target: &GateTarget, path: &str) -> Result<u8, CliError> {
75 let key = self.key()?;
76 let mut text = path.to_owned();
77 if !text.is_empty() && !text.ends_with('/') {
78 text.push('/');
79 }
80 let container = resolve_path(&key.public(), &text)?;
81 if !container.is_container() {
82 return Err(CliError::Usage(format!("{container} is not a container")));
83 }
84 let gate = GateClient::new(target.clone());
85 let response = gate.fetch(
86 &Request::new("GET", container.as_str(), LD_JSON),
87 Some(&key),
88 MAX_LISTING_BYTES,
89 )?;
90 if !response.head.is_success() {
91 return Err(response.into_error(Route::Pod));
92 }
93 let children = listing::children(target.origin(), &container, &response.body)?;
94 let mut listed = Vec::new();
95 let mut refused = Vec::new();
96 for child in children {
97 match child {
98 Child::Accepted(path) => {
99 self.output().line(path.as_str())?;
100 listed.push(json!({"path": path, "container": path.is_container()}));
101 }
102 Child::Refused { id, reason } => {
103 self.output()
104 .note(&format!("refused listed child {id:?}: {reason}"))?;
105 refused.push(json!({"id": id, "reason": reason}));
106 }
107 }
108 }
109 self.output().json(&json!({
110 "path": container,
111 "children": listed,
112 "refused": refused,
113 }))?;
114 Ok(exit::OK)
115 }
116
117 pub fn pod_get(
132 &self,
133 target: &GateTarget,
134 path: &str,
135 output: Option<&Path>,
136 ) -> Result<u8, CliError> {
137 let key = self.key()?;
138 let resource = resolve_path(&key.public(), path)?;
139 self.download(target, &key, &resource, output)
140 }
141
142 pub fn pod_acl_get(
151 &self,
152 target: &GateTarget,
153 path: &str,
154 output: Option<&Path>,
155 ) -> Result<u8, CliError> {
156 let key = self.key()?;
157 let acl = acl_of(&resolve_path(&key.public(), path)?)?;
158 self.download(target, &key, &acl, output)
159 }
160
161 pub fn pod_put(&self, target: &GateTarget, options: &PutOptions) -> Result<u8, CliError> {
172 let key = self.key()?;
173 let resource = resolve_path(&key.public(), &options.path)?;
174 if resource.is_container() {
175 return Err(CliError::Usage(format!(
176 "{resource} is a container; give a resource path"
177 )));
178 }
179 let content_type = options
180 .content_type
181 .clone()
182 .unwrap_or_else(|| guess_content_type(&options.file, &resource).to_owned());
183 self.upload(target, &key, &resource, options, &content_type)
184 }
185
186 pub fn pod_acl_put(&self, target: &GateTarget, options: &PutOptions) -> Result<u8, CliError> {
196 let key = self.key()?;
197 let acl = acl_of(&resolve_path(&key.public(), &options.path)?)?;
198 let content_type = options.content_type.as_deref().unwrap_or(TURTLE).to_owned();
199 self.upload(target, &key, &acl, options, &content_type)
200 }
201
202 pub fn pod_rm(
211 &self,
212 target: &GateTarget,
213 path: &str,
214 confirmation: Confirmation,
215 ) -> Result<u8, CliError> {
216 let key = self.key()?;
217 let resource = resolve_path(&key.public(), path)?;
218 if resource.is_root_acl() {
219 return Err(CliError::Usage(
220 "the root ACL cannot be deleted: it would lock everyone out of the pod, \
221 its owner included; change it with `stratum pod acl put`"
222 .to_owned(),
223 ));
224 }
225 if !self.confirmed(&format!("delete {resource}?"), confirmation)? {
226 return Err(CliError::NotConfirmed);
227 }
228 let gate = GateClient::new(target.clone());
229 let response = gate.fetch(
230 &Request::new("DELETE", resource.as_str(), ANY),
231 Some(&key),
232 crate::client::MAX_RESPONSE_BYTES,
233 )?;
234 if !response.head.is_success() {
235 return Err(response.into_error(Route::Pod));
236 }
237 self.output().json(&json!({
238 "path": resource,
239 "status": response.head.status,
240 "deleted": true,
241 }))?;
242 self.output().line(&format!("deleted {resource}"))?;
243 Ok(exit::OK)
244 }
245
246 fn download(
248 &self,
249 target: &GateTarget,
250 key: &NostrSecretKey,
251 resource: &PodPath,
252 output: Option<&Path>,
253 ) -> Result<u8, CliError> {
254 if output.is_none() && self.output().is_json() {
255 return Err(CliError::Usage(
256 "--json reports on the resource and needs -o <file> for its bytes".to_owned(),
257 ));
258 }
259 let gate = GateClient::new(target.clone());
260 let request = Request::new("GET", resource.as_str(), ANY);
261 let (head, streamed) = match output {
262 Some(path) => {
263 let mut file = create_output(path)?;
264 let result = gate.stream(&request, key, &mut file, MAX_RESOURCE_BYTES);
265 let finished = match result {
266 Ok((head, Ok(streamed))) => {
267 file.sync_all().map(|()| (head, streamed)).map_err(|err| {
268 CliError::Local(format!("writing {} failed: {err}", path.display()))
269 })
270 }
271 Ok((head, Err(body))) => Err(gate::error_from(&head, &body, Route::Pod)),
272 Err(err) => Err(err),
273 };
274 match finished {
275 Ok(done) => done,
276 Err(err) => {
277 drop(file);
278 let _removed = fs::remove_file(path);
280 return Err(err);
281 }
282 }
283 }
284 None => self.to_stdout(&gate, &request, key)?,
285 };
286 let report = json!({
287 "path": resource,
288 "status": head.status,
289 "content_type": head.content_type.as_deref().map(sanitize),
290 "etag": head.etag.as_deref().map(sanitize),
291 "size": streamed.size,
292 "sha256": streamed.sha256,
293 "output": output.map(|p| p.display().to_string()),
294 });
295 self.output().json(&report)?;
296 if let Some(path) = output {
297 self.output().line(&format!(
298 "wrote {} bytes to {} (sha256 {})",
299 streamed.size,
300 path.display(),
301 streamed.sha256
302 ))?;
303 if let Some(etag) = &head.etag {
304 self.output().line(&format!("etag: {}", sanitize(etag)))?;
305 }
306 }
307 Ok(exit::OK)
308 }
309
310 fn to_stdout(
313 &self,
314 gate: &GateClient,
315 request: &Request<'_>,
316 key: &NostrSecretKey,
317 ) -> Result<(Head, gate::Streamed), CliError> {
318 let stdout = io::stdout();
319 if stdout.is_terminal() {
320 let mut buffer = Vec::new();
321 let (head, streamed) = gate.stream(request, key, &mut buffer, MAX_RESOURCE_BYTES)?;
322 let streamed = streamed.map_err(|body| gate::error_from(&head, &body, Route::Pod))?;
323 self.output()
324 .line(sanitize(&String::from_utf8_lossy(&buffer)).trim_end())?;
325 return Ok((head, streamed));
326 }
327 let mut lock = stdout.lock();
328 let (head, streamed) = gate.stream(request, key, &mut lock, MAX_RESOURCE_BYTES)?;
329 let streamed = streamed.map_err(|body| gate::error_from(&head, &body, Route::Pod))?;
330 lock.flush()
331 .map_err(|err| CliError::Local(format!("writing output failed: {err}")))?;
332 Ok((head, streamed))
333 }
334
335 fn upload(
337 &self,
338 target: &GateTarget,
339 key: &NostrSecretKey,
340 resource: &PodPath,
341 options: &PutOptions,
342 content_type: &str,
343 ) -> Result<u8, CliError> {
344 if !is_header_value(content_type) {
345 return Err(CliError::Usage(
346 "--content-type must be printable ASCII".to_owned(),
347 ));
348 }
349 if let WriteCondition::IfMatch(etag) = &options.condition {
350 if !is_header_value(etag) {
351 return Err(CliError::Usage(
352 "--if-match must be printable ASCII, such as \"<64 hex>\"".to_owned(),
353 ));
354 }
355 }
356 let body = read_upload(&options.file)?;
357 let precondition = match &options.condition {
358 WriteCondition::Always => Precondition::None,
359 WriteCondition::IfMatch(etag) => Precondition::IfMatch(etag),
360 WriteCondition::CreateOnly => Precondition::CreateOnly,
361 };
362 let gate = GateClient::new(target.clone()).with_busy_retries(*self.output());
363 let request = Request::new("PUT", resource.as_str(), ANY)
364 .with_body(&body, content_type)
365 .with_precondition(precondition);
366 let response = gate.fetch(&request, Some(key), crate::client::MAX_RESPONSE_BYTES)?;
367 if !response.head.is_success() {
368 return Err(response.into_error(Route::Pod));
369 }
370 let head = response.head;
371 let digest = stratum_node_core::Sha256Digest::of(&body);
372 self.output().json(&json!({
373 "path": resource,
374 "status": head.status,
375 "created": head.status == 201,
376 "size": body.len(),
377 "sha256": digest,
378 "content_type": content_type,
379 "etag": head.etag.as_deref().map(sanitize),
380 }))?;
381 let verb = if head.status == 201 {
382 "created"
383 } else {
384 "wrote"
385 };
386 self.output().line(&format!(
387 "{verb} {resource} ({} bytes, sha256 {digest})",
388 body.len()
389 ))?;
390 if let Some(etag) = &head.etag {
391 self.output().line(&format!("etag: {}", sanitize(etag)))?;
392 }
393 Ok(exit::OK)
394 }
395}
396
397pub(crate) fn resolve_path(owner: &DidNostr, text: &str) -> Result<PodPath, CliError> {
404 let root = PodPath::pod_root(owner);
405 let result = if text.starts_with('/') {
406 PodPath::parse(text)
407 } else if text.is_empty() {
408 Ok(root)
409 } else {
410 root.join(text)
411 };
412 result.map_err(|err| CliError::Usage(path_refusal(text, err)))
413}
414
415fn path_refusal(text: &str, err: ParsePodPathError) -> String {
417 let shown = sanitize(text);
418 match err {
419 ParsePodPathError::ForbiddenCharacter => format!(
420 "{shown:?} is refused by the Step 2 character rule: names may use only \
421 A-Z a-z 0-9 - . _ ~ and / between segments; no spaces and no percent-encoding"
422 ),
423 ParsePodPathError::DotSegment => {
424 format!("{shown:?} has a . or .. segment, which pod paths may not have")
425 }
426 ParsePodPathError::EmptySegment => format!(
427 "{shown:?} has an empty segment (// or a leading /); relative paths start with a name"
428 ),
429 _ => format!(
430 "{shown:?} is not a pod path: give a path relative to your pod, or an absolute \
431 /pods/<64 lowercase hex>/… or /pods/<64 lowercase hex>.acl"
432 ),
433 }
434}
435
436fn acl_of(path: &PodPath) -> Result<PodPath, CliError> {
438 path.acl_path().ok_or_else(|| {
439 CliError::Usage(format!(
440 "{path} is itself an ACL; give the resource or container it controls"
441 ))
442 })
443}
444
445fn guess_content_type(file: &Path, resource: &PodPath) -> &'static str {
447 let name = resource.as_str();
448 let extension = file
449 .extension()
450 .and_then(|e| e.to_str())
451 .or_else(|| name.rsplit_once('.').map(|(_, e)| e))
452 .unwrap_or("")
453 .to_ascii_lowercase();
454 match extension.as_str() {
455 "acl" | "ttl" => TURTLE,
456 "txt" => "text/plain",
457 "md" => "text/markdown",
458 "html" | "htm" => "text/html",
459 "json" => "application/json",
460 "jsonld" => "application/ld+json",
461 "png" => "image/png",
462 "jpg" | "jpeg" => "image/jpeg",
463 "pdf" => "application/pdf",
464 _ => OCTET_STREAM,
465 }
466}
467
468fn is_header_value(text: &str) -> bool {
470 !text.is_empty() && text.bytes().all(|b| (0x20..0x7f).contains(&b))
471}
472
473fn read_upload(path: &Path) -> Result<Vec<u8>, CliError> {
475 let fail = |message: String| CliError::FileContents {
476 path: path.to_owned(),
477 message,
478 };
479 let file = File::open(path).map_err(|err| fail(format!("cannot be opened: {err}")))?;
480 let metadata = file
481 .metadata()
482 .map_err(|err| fail(format!("cannot be read: {err}")))?;
483 if !metadata.is_file() {
484 return Err(fail("is not a regular file".to_owned()));
485 }
486 if metadata.len() > MAX_RESOURCE_BYTES {
487 return Err(fail(format!(
488 "is larger than {MAX_RESOURCE_BYTES} bytes, the most a pod accepts"
489 )));
490 }
491 let mut body = Vec::new();
492 file.take(MAX_RESOURCE_BYTES + 1)
493 .read_to_end(&mut body)
494 .map_err(|err| fail(format!("cannot be read: {err}")))?;
495 if u64::try_from(body.len()).unwrap_or(u64::MAX) > MAX_RESOURCE_BYTES {
496 return Err(fail(format!(
497 "is larger than {MAX_RESOURCE_BYTES} bytes, the most a pod accepts"
498 )));
499 }
500 Ok(body)
501}
502
503fn create_output(path: &Path) -> Result<File, CliError> {
506 OpenOptions::new()
507 .write(true)
508 .create_new(true)
509 .mode(0o600)
510 .open(path)
511 .map_err(|err| {
512 if err.kind() == io::ErrorKind::AlreadyExists {
513 CliError::File {
514 path: path.to_owned(),
515 source: crate::private_file::PrivateFileError::AlreadyExists,
516 }
517 } else {
518 CliError::File {
519 path: path.to_owned(),
520 source: crate::private_file::PrivateFileError::Io(err),
521 }
522 }
523 })
524}
525
526#[cfg(test)]
527mod tests {
528 use super::*;
529
530 const A: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
531
532 #[test]
533 fn command_line_paths_resolve_or_say_why_not() {
534 let owner = DidNostr::from_hex(A).expect("key");
535 assert_eq!(
536 resolve_path(&owner, "").expect("root").as_str(),
537 format!("/pods/{A}/")
538 );
539 assert_eq!(
540 resolve_path(&owner, "private/x.txt")
541 .expect("relative")
542 .as_str(),
543 format!("/pods/{A}/private/x.txt")
544 );
545 assert_eq!(
546 resolve_path(&owner, &format!("/pods/{A}.acl"))
547 .expect("root acl")
548 .as_str(),
549 format!("/pods/{A}.acl")
550 );
551 let err = resolve_path(&owner, "my file.txt").expect_err("space");
552 assert!(err.to_string().contains("Step 2 character rule"), "{err}");
553 let err = resolve_path(&owner, "a%20b").expect_err("percent");
554 assert!(err.to_string().contains("no percent-encoding"), "{err}");
555 let err = resolve_path(&owner, "a/../b").expect_err("dot");
556 assert!(err.to_string().contains(". or .."), "{err}");
557 let err = resolve_path(&owner, "/etc/passwd").expect_err("outside");
558 assert!(err.to_string().contains("not a pod path"), "{err}");
559 assert_eq!(err.exit_code(), exit::USAGE);
560 }
561
562 #[test]
563 fn acl_paths_sit_beside_their_resource() {
564 let owner = DidNostr::from_hex(A).expect("key");
565 let root = resolve_path(&owner, "").expect("root");
566 assert_eq!(
567 acl_of(&root).expect("acl").as_str(),
568 format!("/pods/{A}.acl")
569 );
570 let acl = resolve_path(&owner, "x.txt.acl").expect("acl");
571 assert!(acl_of(&acl).is_err());
572 }
573}