Skip to main content

ostrya_remote/
error.rs

1//! The error type of this crate and its wire codes.
2
3use ostrya_core::{Checksum, ObjectName};
4
5use crate::proto::{ErrorMessage, RefState};
6
7/// The result type of this crate, with [`Error`] as its error.
8pub type Result<T> = std::result::Result<T, Error>;
9
10/// The error of each fallible operation of this crate.
11///
12/// A variant with a wire code matches one code of an `Error` message, for
13/// example [`Error::Protocol`] for the code `protocol`. [`ErrorCode`] names
14/// the codes. [`code`](Error::code) returns the code of an error and lists the
15/// variants that have no code.
16#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum Error {
19    /// The server does not support the requested protocol version.
20    #[error("version-unsupported: {0}")]
21    VersionUnsupported(String),
22    /// The server repository sets `[core] locking=false`.
23    #[error("locking-disabled: {0}")]
24    LockingDisabled(String),
25    /// A refusal of the credential of an HTTP push session.
26    ///
27    /// The client returns this variant for an `Error` message with the code
28    /// `unauthorized`. An ostrya server sends that message over HTTP alone,
29    /// with the status 401 or 403. A 401 or 403 whose body is not one frame
30    /// is [`Error::Transport`].
31    #[error("unauthorized: {0}")]
32    Unauthorized(String),
33    /// A malformed frame, an unknown kind, or a message out of order.
34    #[error("protocol: {0}")]
35    Protocol(String),
36    /// A frame, a batch, or a metadata object over its limit.
37    ///
38    /// With the `s3` feature, the bucket client returns this variant for an
39    /// object over the size limit of the caller, for a listing page over
40    /// 4 MiB, and for a body of `Bucket::put_stream` that is longer than
41    /// 10,000 parts. `s3::part_size` returns it for a part size over 5 GiB.
42    #[error("limit-exceeded: {0}")]
43    LimitExceeded(String),
44    /// An object whose bytes do not hash to its name.
45    #[error("checksum-mismatch: {0}")]
46    ChecksumMismatch(String),
47    /// Content that the server refuses to store.
48    ///
49    /// The repository mode cannot store the content, or the content is
50    /// privileged and the policy does not allow it.
51    #[error("mode-refused: {0}")]
52    ModeRefused(String),
53    /// A commit that reaches objects that the server does not hold.
54    ///
55    /// The objects are not in the repository and are not staged in the
56    /// session. `missing` lists them.
57    #[error("missing-objects: {message}")]
58    MissingObjects {
59        /// The message for a human.
60        message: String,
61        /// The objects that are missing.
62        missing: Vec<ObjectName>,
63    },
64    /// A ref that is not in its expected state, or a ref that exists and
65    /// that the update can create and not move.
66    ///
67    /// The second case is an update that writes a commit to a ref that
68    /// exists, with `t` and no `w` on the ref, also when the commit is the
69    /// current commit. `name` and `current` give the current state.
70    /// `current` is `None` if the ref is absent.
71    #[error("ref-mismatch: {message}")]
72    RefMismatch {
73        /// The message for a human.
74        message: String,
75        /// The name of the ref.
76        name: String,
77        /// The current commit of the ref.
78        current: Option<Checksum>,
79    },
80    /// A ref update that is not a fast-forward.
81    ///
82    /// The new commit does not descend from the current tip, and the policy
83    /// does not allow it.
84    #[error("non-fast-forward: {0}")]
85    NonFastForward(String),
86    /// A ref delete that the policy does not allow.
87    #[error("delete-denied: {0}")]
88    DeleteDenied(String),
89    /// A ref name that an ostrya server refuses.
90    #[error("invalid-ref: {0}")]
91    InvalidRef(String),
92    /// A session or a ref update that the policy refuses.
93    ///
94    /// In a push session, these are the causes:
95    ///
96    /// - The client group opens no push session.
97    /// - A ref of `Hello` has no `r`.
98    /// - An update writes a commit to a ref with no `w` and no `t`.
99    /// - An update names a ref that a push does not write: a remote ref, the
100    ///   collection anchor ref of a server with a collection id, a ref that
101    ///   is an alias, or a ref path that a ref write cannot replace.
102    /// - Two updates write a commit, and the ref of one names a directory of
103    ///   the other.
104    ///
105    /// In a one-way stream, the rule that matches the update does not accept
106    /// it, or the update names a remote ref that no rule matches.
107    #[error("ref-denied: {0}")]
108    RefDenied(String),
109    /// A commit with no trusted signature that verifies.
110    ///
111    /// The policy requires a trusted signature.
112    #[error("signature-required: {0}")]
113    SignatureRequired(String),
114    /// A commit whose bindings do not match the session.
115    ///
116    /// The `ostree.ref-binding` of the commit does not name a target ref, or
117    /// its `ostree.collection-binding` does not name the collection id of the
118    /// server.
119    #[error("binding-mismatch: {0}")]
120    BindingMismatch(String),
121    /// A server-side failure, for example an I/O error.
122    #[error("internal: {0}")]
123    Internal(String),
124    /// The client ended the session with `Abort`, or abandoned an object.
125    ///
126    /// The client abandons an object with the abandon marker. No wire code
127    /// carries this variant, because the server sends no `Error` message in
128    /// reply.
129    #[error("the client aborted the session")]
130    Aborted,
131    /// A `Commit` whose outcome is unknown.
132    ///
133    /// The client sent `Commit`, and the session ended with no reply that the
134    /// client can read. The server can have written the refs, and the client
135    /// cannot know if it did. `refs` names the refs of the ref updates.
136    #[error("the outcome of the commit of {refs:?} is unknown: {message}")]
137    CommitOutcomeUnknown {
138        /// The refs of the ref updates.
139        refs: Vec<String>,
140        /// A message for a human that states what ended the session.
141        message: String,
142    },
143    /// A failure of the object source while the session sends its objects.
144    ///
145    /// The session ends with `Abort`.
146    #[error("the object source failed: {0}")]
147    Source(#[source] Box<dyn std::error::Error + Send + Sync>),
148    /// A call of the client that the session refuses.
149    ///
150    /// The session refuses a call with an argument or source data that it
151    /// cannot send. It also refuses a call while another call runs, and a
152    /// call on a broken session.
153    ///
154    /// With the `s3` feature, the `s3` module returns this variant for a
155    /// refused value: a key pair, a region, a profile name, a setting of an
156    /// environment variable, or a shared AWS file that is larger than 1 MiB
157    /// or that the reader of the files refuses. It also returns it when no
158    /// source gives a key pair. The message holds no secret access key and no
159    /// session token. It also returns it for a refused address of a bucket
160    /// repository, endpoint URL, or location, for a key that is not a key of
161    /// a bucket repository, for a refused list prefix, for a part size
162    /// outside the range of 5 MiB to 5 GiB, and for an empty upload id.
163    ///
164    /// [`Endpoint::parse`](crate::transport::Endpoint::parse) returns this
165    /// variant for an `s3://` address. The session constructors return it
166    /// for an S3 endpoint.
167    #[error("invalid input: {0}")]
168    InvalidInput(String),
169    /// A failure of the transport under the session.
170    ///
171    /// - Over ssh, the ssh client cannot start, or it exits with a failure
172    ///   status while the session fails with an I/O error. The message names
173    ///   the program.
174    /// - Over HTTP, the session cannot use the response of the server. The
175    ///   message names the URL, and for the first three cases the status:
176    ///   - a status that the receive endpoint does not give, a 3xx included
177    ///   - a body that is not one frame
178    ///   - a frame other than an `Error` message with an error status
179    ///   - a `HelloReply` with no session id of 64 lowercase hex digits
180    ///   - a frame other than an `Error` message in answer to `DELETE`
181    /// - With the `s3` feature, the bucket client cannot use a listing: the
182    ///   XML reader refuses the body, a truncated page has no marker of the
183    ///   next page, a page does not move past the earlier pages, or a key is
184    ///   outside the prefix of the request.
185    /// - With the `s3` feature, the server answers a read or a list of the
186    ///   bucket client with 304. The request sends no validators, so the
187    ///   answer cannot be used.
188    /// - With the `s3` feature, the bucket client cannot use an answer of a
189    ///   multipart upload: the answer that starts the upload has no upload
190    ///   id, an upload id of more than 1 KiB, or no body, the answer to a
191    ///   part has no `ETag` or an `ETag` of more than 1 KiB, or the body of
192    ///   the answer that completes the upload cannot be read.
193    /// - With the `s3` feature, a completion of a multipart upload whose
194    ///   outcome is not known gets a 404 `NoSuchUpload`, and the key holds no
195    ///   object or an object of another length.
196    ///
197    /// No wire code carries this variant.
198    #[error("transport: {0}")]
199    Transport(String),
200    /// A failure of the HTTP client of the session.
201    ///
202    /// The client cannot be built, a request cannot be sent, or a request
203    /// fails after it is sent. With the `s3` feature, the bucket client
204    /// returns this variant for the same failures. No wire code carries this
205    /// variant.
206    #[error(transparent)]
207    Fetch(ostrya_fetch::Error),
208    /// An I/O error of the underlying stream.
209    ///
210    /// An end of file inside a frame or an object has the kind
211    /// `UnexpectedEof`.
212    ///
213    /// With the `s3` feature, the `s3` module returns this variant for a
214    /// shared AWS file that exists and cannot be read. The error keeps the
215    /// `io::ErrorKind` of the failure, and its message names the file and the
216    /// path. The bucket client returns it for a failed read of the body of
217    /// `Bucket::put_stream`, with the error of the reader unchanged.
218    #[error(transparent)]
219    Io(#[from] std::io::Error),
220    /// A failure of the walk or of the hash pass of a local tree.
221    ///
222    /// If the send pass cannot open a file of the tree again, it also
223    /// returns this variant. `path` names the entry on the local filesystem,
224    /// the walk root included. `source` keeps the `io::ErrorKind` of the
225    /// failure.
226    /// [`TreeModel::scan`](crate::tree::TreeModel::scan) lists the kinds in
227    /// its `# Errors` section.
228    ///
229    /// No wire code carries this variant. The walk and the hash pass come
230    /// before any session. A session returns a failed open of the send pass
231    /// inside [`Error::Source`].
232    #[error("{}: {source}", .path.display())]
233    Walk {
234        /// The entry on the local filesystem.
235        path: std::path::PathBuf,
236        /// The I/O error, with the `io::ErrorKind` of the failure.
237        #[source]
238        source: std::io::Error,
239    },
240    /// An error response of an S3 server to a request of the bucket client.
241    ///
242    /// `code` and `message` come from the `Code` and the `Message` elements
243    /// of the S3 `Error` document in the body. Both are `None` if the body
244    /// holds no such document, is larger than 4 MiB, declares a coding, or
245    /// did not arrive.
246    /// `code` and `message` have each control character and each format
247    /// character (Unicode categories Cc and Cf) replaced with U+FFFD, and
248    /// each holds at most 512 bytes.
249    ///
250    /// The bucket client also returns this variant for an `Error` document
251    /// that S3 sends with a 2xx status. Then `status` is that status.
252    ///
253    /// The message names the code `RequestTimeTooSkewed` and states that the
254    /// clock of this host is not in step with the clock of the server. A
255    /// wrong secret access key gives the code `SignatureDoesNotMatch`.
256    ///
257    /// No wire code carries this variant.
258    #[cfg(feature = "s3")]
259    #[cfg_attr(docsrs, doc(cfg(feature = "s3")))]
260    #[non_exhaustive]
261    #[error("{}", crate::s3::describe_status(*.status, .code.as_deref(), .message.as_deref(), .key.as_deref()))]
262    S3 {
263        /// The status of the response.
264        status: u16,
265        /// The `Code` element, or `None` if the body holds no S3 error.
266        code: Option<String>,
267        /// The `Message` element, or `None` if the body holds no S3 error.
268        message: Option<String>,
269        /// The full key of the object, with the prefix of the repository, or
270        /// `None` for a request on the bucket, for example a list.
271        key: Option<String>,
272    },
273    /// A bucket in a region other than the region of the signature.
274    ///
275    /// The bucket client returns this variant for an unsuccessful response
276    /// whose `x-amz-bucket-region` header, or whose `Region` element of the
277    /// S3 `Error` document, names a region other than the region of the
278    /// location.
279    ///
280    /// No wire code carries this variant.
281    #[cfg(feature = "s3")]
282    #[cfg_attr(docsrs, doc(cfg(feature = "s3")))]
283    #[non_exhaustive]
284    #[error(
285        "the bucket {bucket} is in the region {bucket_region}, and the requests are signed for \
286         the region {region}: set the region to {bucket_region}"
287    )]
288    S3Region {
289        /// The name of the bucket.
290        bucket: String,
291        /// The region of the signature.
292        region: String,
293        /// The region that the server names for the bucket.
294        bucket_region: String,
295    },
296}
297
298/// The wire code of an `Error` message.
299///
300/// A later protocol version can add codes.
301#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
302#[non_exhaustive]
303pub enum ErrorCode {
304    /// `version-unsupported`.
305    VersionUnsupported,
306    /// `locking-disabled`.
307    LockingDisabled,
308    /// `unauthorized`.
309    Unauthorized,
310    /// `protocol`.
311    Protocol,
312    /// `limit-exceeded`.
313    LimitExceeded,
314    /// `checksum-mismatch`.
315    ChecksumMismatch,
316    /// `mode-refused`.
317    ModeRefused,
318    /// `missing-objects`.
319    MissingObjects,
320    /// `ref-mismatch`.
321    RefMismatch,
322    /// `non-fast-forward`.
323    NonFastForward,
324    /// `delete-denied`.
325    DeleteDenied,
326    /// `invalid-ref`.
327    InvalidRef,
328    /// `ref-denied`.
329    RefDenied,
330    /// `signature-required`.
331    SignatureRequired,
332    /// `binding-mismatch`.
333    BindingMismatch,
334    /// `internal`.
335    Internal,
336}
337
338impl ErrorCode {
339    /// All 16 codes, in the order that [`ErrorCode`] declares them.
340    pub const ALL: [ErrorCode; 16] = [
341        ErrorCode::VersionUnsupported,
342        ErrorCode::LockingDisabled,
343        ErrorCode::Unauthorized,
344        ErrorCode::Protocol,
345        ErrorCode::LimitExceeded,
346        ErrorCode::ChecksumMismatch,
347        ErrorCode::ModeRefused,
348        ErrorCode::MissingObjects,
349        ErrorCode::RefMismatch,
350        ErrorCode::NonFastForward,
351        ErrorCode::DeleteDenied,
352        ErrorCode::InvalidRef,
353        ErrorCode::RefDenied,
354        ErrorCode::SignatureRequired,
355        ErrorCode::BindingMismatch,
356        ErrorCode::Internal,
357    ];
358
359    /// Returns the wire name of the code.
360    pub fn as_str(self) -> &'static str {
361        match self {
362            ErrorCode::VersionUnsupported => "version-unsupported",
363            ErrorCode::LockingDisabled => "locking-disabled",
364            ErrorCode::Unauthorized => "unauthorized",
365            ErrorCode::Protocol => "protocol",
366            ErrorCode::LimitExceeded => "limit-exceeded",
367            ErrorCode::ChecksumMismatch => "checksum-mismatch",
368            ErrorCode::ModeRefused => "mode-refused",
369            ErrorCode::MissingObjects => "missing-objects",
370            ErrorCode::RefMismatch => "ref-mismatch",
371            ErrorCode::NonFastForward => "non-fast-forward",
372            ErrorCode::DeleteDenied => "delete-denied",
373            ErrorCode::InvalidRef => "invalid-ref",
374            ErrorCode::RefDenied => "ref-denied",
375            ErrorCode::SignatureRequired => "signature-required",
376            ErrorCode::BindingMismatch => "binding-mismatch",
377            ErrorCode::Internal => "internal",
378        }
379    }
380
381    /// Returns the code of a wire name, or `None` if the name is not a code.
382    pub fn from_name(name: &str) -> Option<ErrorCode> {
383        ErrorCode::ALL.into_iter().find(|c| c.as_str() == name)
384    }
385}
386
387impl Error {
388    /// Returns the wire code of the error, or `None` for a variant with no code.
389    ///
390    /// These variants have no wire code:
391    ///
392    /// - [`Error::Aborted`]
393    /// - [`Error::CommitOutcomeUnknown`]
394    /// - [`Error::Source`]
395    /// - [`Error::InvalidInput`]
396    /// - [`Error::Transport`]
397    /// - [`Error::Fetch`]
398    /// - [`Error::Io`]
399    /// - [`Error::Walk`]
400    /// - `Error::S3` and `Error::S3Region`, with the `s3` feature
401    pub fn code(&self) -> Option<ErrorCode> {
402        Some(match self {
403            Error::VersionUnsupported(_) => ErrorCode::VersionUnsupported,
404            Error::LockingDisabled(_) => ErrorCode::LockingDisabled,
405            Error::Unauthorized(_) => ErrorCode::Unauthorized,
406            Error::Protocol(_) => ErrorCode::Protocol,
407            Error::LimitExceeded(_) => ErrorCode::LimitExceeded,
408            Error::ChecksumMismatch(_) => ErrorCode::ChecksumMismatch,
409            Error::ModeRefused(_) => ErrorCode::ModeRefused,
410            Error::MissingObjects { .. } => ErrorCode::MissingObjects,
411            Error::RefMismatch { .. } => ErrorCode::RefMismatch,
412            Error::NonFastForward(_) => ErrorCode::NonFastForward,
413            Error::DeleteDenied(_) => ErrorCode::DeleteDenied,
414            Error::InvalidRef(_) => ErrorCode::InvalidRef,
415            Error::RefDenied(_) => ErrorCode::RefDenied,
416            Error::SignatureRequired(_) => ErrorCode::SignatureRequired,
417            Error::BindingMismatch(_) => ErrorCode::BindingMismatch,
418            Error::Internal(_) => ErrorCode::Internal,
419            Error::Aborted
420            | Error::CommitOutcomeUnknown { .. }
421            | Error::Source(_)
422            | Error::InvalidInput(_)
423            | Error::Transport(_)
424            | Error::Fetch(_)
425            | Error::Io(_)
426            | Error::Walk { .. } => return None,
427            #[cfg(feature = "s3")]
428            Error::S3 { .. } | Error::S3Region { .. } => return None,
429        })
430    }
431
432    /// Returns the `Error` message that reports this error to the peer.
433    ///
434    /// An error with no wire code reports as the code `internal`, with its
435    /// display text as the message.
436    pub fn to_message(&self) -> ErrorMessage {
437        let (code, message) = match self {
438            Error::MissingObjects { message, missing } => {
439                return ErrorMessage {
440                    code: ErrorCode::MissingObjects,
441                    message: message.clone(),
442                    missing: missing.clone(),
443                    current: None,
444                };
445            }
446            Error::RefMismatch {
447                message,
448                name,
449                current,
450            } => {
451                return ErrorMessage {
452                    code: ErrorCode::RefMismatch,
453                    message: message.clone(),
454                    missing: Vec::new(),
455                    current: Some(RefState {
456                        name: name.clone(),
457                        commit: *current,
458                    }),
459                };
460            }
461            Error::Aborted
462            | Error::CommitOutcomeUnknown { .. }
463            | Error::Source(_)
464            | Error::InvalidInput(_)
465            | Error::Transport(_)
466            | Error::Fetch(_)
467            | Error::Io(_)
468            | Error::Walk { .. } => (ErrorCode::Internal, self.to_string()),
469            #[cfg(feature = "s3")]
470            Error::S3 { .. } | Error::S3Region { .. } => (ErrorCode::Internal, self.to_string()),
471            Error::VersionUnsupported(m)
472            | Error::LockingDisabled(m)
473            | Error::Unauthorized(m)
474            | Error::Protocol(m)
475            | Error::LimitExceeded(m)
476            | Error::ChecksumMismatch(m)
477            | Error::ModeRefused(m)
478            | Error::NonFastForward(m)
479            | Error::DeleteDenied(m)
480            | Error::InvalidRef(m)
481            | Error::RefDenied(m)
482            | Error::SignatureRequired(m)
483            | Error::BindingMismatch(m)
484            | Error::Internal(m) => (self.code().expect("not Io"), m.clone()),
485        };
486        ErrorMessage {
487            code,
488            message,
489            missing: Vec::new(),
490            current: None,
491        }
492    }
493}
494
495/// Converts an `Error` message from a server to the [`Error`] variant of its
496/// code.
497///
498/// The conversion drops a `missing` list or a `current` state on a code that
499/// does not carry one. A decoded `ref-mismatch` always carries its `current`
500/// state, so [`Error::to_message`] gives the same message back.
501impl From<ErrorMessage> for Error {
502    fn from(msg: ErrorMessage) -> Error {
503        let m = msg.message;
504        match msg.code {
505            ErrorCode::VersionUnsupported => Error::VersionUnsupported(m),
506            ErrorCode::LockingDisabled => Error::LockingDisabled(m),
507            ErrorCode::Unauthorized => Error::Unauthorized(m),
508            ErrorCode::Protocol => Error::Protocol(m),
509            ErrorCode::LimitExceeded => Error::LimitExceeded(m),
510            ErrorCode::ChecksumMismatch => Error::ChecksumMismatch(m),
511            ErrorCode::ModeRefused => Error::ModeRefused(m),
512            ErrorCode::MissingObjects => Error::MissingObjects {
513                message: m,
514                missing: msg.missing,
515            },
516            ErrorCode::RefMismatch => {
517                let (name, current) = match msg.current {
518                    Some(s) => (s.name, s.commit),
519                    None => (String::new(), None),
520                };
521                Error::RefMismatch {
522                    message: m,
523                    name,
524                    current,
525                }
526            }
527            ErrorCode::NonFastForward => Error::NonFastForward(m),
528            ErrorCode::DeleteDenied => Error::DeleteDenied(m),
529            ErrorCode::InvalidRef => Error::InvalidRef(m),
530            ErrorCode::RefDenied => Error::RefDenied(m),
531            ErrorCode::SignatureRequired => Error::SignatureRequired(m),
532            ErrorCode::BindingMismatch => Error::BindingMismatch(m),
533            ErrorCode::Internal => Error::Internal(m),
534        }
535    }
536}