Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions crates/unftp-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,24 @@

When you need to FTP, but don't want to.

![logo](../../logo.png)
![unFTP logo](https://raw.githubusercontent.com/bolcom/libunftp/master/logo.png)

[**Website**](https://unftp.rs) | [**API Docs**](https://docs.rs/unftp-core) | [**libunftp**](https://github.com/bolcom/libunftp) | [**unFTP**](https://github.com/bolcom/unFTP)
[**Website**](https://unftp.rs) | [**API docs**](https://docs.rs/unftp-core) |
[**libunftp**](https://github.com/bolcom/libunftp) | [**unFTP server**](https://github.com/bolcom/unFTP)

This crate contains the core traits and types for [unFTP](https://unftp.rs/) backends.
This crate contains the core traits and types for [unFTP](https://unftp.rs/) backends (extensions).

This crate was split of from `libunftp` and defines an API that authentication and storage backend (extention/plug-in) implementations in
the unFTP ecosystem should implement. The [`libunftp`](https://unftp.rs/libunftp/) crate provides the server implementation and depends on this core crate too.
## About the wider unFTP project

Existing backend implementations exists on crates.io ([search for `unftp-`](https://crates.io/search?q=unftp-)). To implement your own follow the [API Documentation](https://docs.rs/unftp-core).
unFTP is an open-source, cloud-focused FTP and FTPS server project. It is an FTP server, not an SFTP server. You can run
the standalone [unFTP server](https://github.com/bolcom/unFTP), embed the [libunftp library](https://github.com/bolcom/libunftp) in your application and add existing extensions or create your own extensions. Its pluggable authentication, storage, user-detail providers and other extensions let you connect the server to the systems your application uses.

## About `unftp-core`

`unftp-core` defines the shared Rust traits and types used to write extensions in the unFTP ecosystem. Authentication and storage backend crates implement these interfaces, and `libunftp` uses them to implement a server. This crate provides the interfaces; it is not itself an FTP server or a storage backend.

Use `unftp-core` when building an authentication or storage backend for the unFTP ecosystem. Browse existing
[authentication backends](https://crates.io/search?q=unftp-auth-) and [storage backends](https://crates.io/search?q=unftp-sbe-),
or follow the [API documentation](https://docs.rs/unftp-core) to implement your own.

The unFTP ecosystem has more extension points, which will, as they mature be moved to `unftp-core`.
37 changes: 24 additions & 13 deletions crates/unftp-core/src/auth/authenticator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,26 @@ pub trait Authenticator: Sync + Send + Debug {
/// To obtain full user details, use a [`UserDetailProvider`] to convert the `Principal`
/// into a full [`UserDetail`] implementation.
///
/// [`Principal`]: struct.Principal.html
/// [`UserDetailProvider`]: ../trait.UserDetailProvider.html
/// [`UserDetail`]: ../trait.UserDetail.html
/// # Errors
///
/// Return [`AuthenticationError`] when the credentials are rejected or authentication fails.
///
/// [`UserDetailProvider`]: crate::auth::UserDetailProvider
/// [`UserDetail`]: crate::auth::UserDetail
async fn authenticate(&self, username: &str, creds: &Credentials) -> Result<Principal, AuthenticationError>;

/// Tells whether its OK to not ask for a password when a valid client cert
/// was presented.
/// Returns whether a valid client certificate is sufficient to authenticate this username
/// without a password.
///
/// The default is `false`, so authenticators must opt in to certificate-only authentication.
async fn cert_auth_sufficient(&self, _username: &str) -> bool {
false
}

/// Implement to set the name of the authenticator. By default it returns the type signature.
/// Returns the name used to identify this authenticator in server diagnostics.
///
/// Override this to provide a stable, human-readable name. By default, the Rust type name is
/// returned.
fn name(&self) -> &str {
std::any::type_name::<Self>()
}
Expand All @@ -51,9 +59,9 @@ pub trait Authenticator: Sync + Send + Debug {
/// assert_eq!(principal.username, "alice");
/// ```
///
/// [`Authenticator`]: trait.Authenticator.html
/// [`UserDetail`]: ../trait.UserDetail.html
/// [`UserDetailProvider`]: ../trait.UserDetailProvider.html
/// [`Authenticator`]: crate::auth::Authenticator
/// [`UserDetail`]: crate::auth::UserDetail
/// [`UserDetailProvider`]: crate::auth::UserDetailProvider
#[derive(Debug, Clone)]
pub struct Principal {
/// The authenticated username
Expand Down Expand Up @@ -105,8 +113,8 @@ impl AuthenticationError {

/// Credentials passed to an [Authenticator](crate::auth::Authenticator)
///
/// [Authenticator](crate::auth::Authenticator) implementations can assume that either `certificate_chain` or `password`
/// will not be `None`.
/// At least one of `password` or `certificate_chain` is present. Both may be present when a client
/// supplies a password and a certificate.
#[derive(Clone, Debug)]
pub struct Credentials {
/// The password that the client sent.
Expand All @@ -130,14 +138,17 @@ impl From<&str> for Credentials {
}
}

/// Contains a single DER-encoded X.509 client certificate.
/// Wraps a single DER-encoded X.509 client certificate.
#[derive(Clone, Eq, PartialEq)]
pub struct ClientCert(pub Vec<u8>);

use x509_parser::prelude::parse_x509_certificate;

impl ClientCert {
/// Returns true if the Common Name from the client certificate matches the allowed_cn
/// Returns whether the rendered certificate subject contains `allowed_cn`.
///
/// This is a case-sensitive substring check of the full subject, not an exact comparison of
/// the certificate's Common Name field. Returns an error if the certificate cannot be parsed.
pub fn verify_cn(&self, allowed_cn: &str) -> Result<bool, std::io::Error> {
let client_cert = parse_x509_certificate(&self.0);
let subject = match client_cert {
Expand Down
44 changes: 21 additions & 23 deletions crates/unftp-core/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
//!
//! Pre-made implementations exist on crates.io (search for `unftp-auth-`) and you can define your
//! own implementation to integrate your FTP(S) server with whatever authentication mechanism you
//! need. For example, to define an `Authenticator` that will randomly decide:
//! need. The example below shows a simple password check. It is only illustrative; production
//! authenticators should use an appropriate password-verification mechanism.
//!
//! 1. Declare dependencies on async-trait, tokio, and unftp-core
//!
//! ```toml
//! async-trait = "0.1.89"
//! tokio = { version = "1.49.0", features = ["macros", "rt"] }
//! unftp-core = { path = "../path/to/unftp-core" }
//! unftp-core = "0.1"
//! ```
//!
//! 2. Implement the [`Authenticator`] trait and optionally the [`UserDetail`] and [`UserDetailProvider`] traits:
Expand All @@ -19,47 +20,44 @@
//! use async_trait::async_trait;
//!
//! #[derive(Debug)]
//! struct RandomAuthenticator;
//! struct ExampleAuthenticator;
//!
//! #[async_trait]
//! impl Authenticator for RandomAuthenticator {
//! async fn authenticate(&self, _username: &str, _creds: &Credentials) -> Result<Principal, AuthenticationError> {
//! Ok(Principal { username: _username.to_string() })
//! impl Authenticator for ExampleAuthenticator {
//! async fn authenticate(&self, username: &str, creds: &Credentials) -> Result<Principal, AuthenticationError> {
//! if creds.password.as_deref() != Some("example-password") {
//! return Err(AuthenticationError::BadPassword);
//! }
//!
//! Ok(Principal { username: username.to_owned() })
//! }
//! }
//!
//! #[derive(Debug)]
//! struct RandomUser;
//! struct ExampleUser;
//!
//! impl UserDetail for RandomUser {}
//! impl UserDetail for ExampleUser {}
//!
//! impl std::fmt::Display for RandomUser {
//! impl std::fmt::Display for ExampleUser {
//! fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//! write!(f, "RandomUser")
//! write!(f, "ExampleUser")
//! }
//! }
//!
//! #[derive(Debug)]
//! struct RandomUserDetailProvider;
//! struct ExampleUserDetailProvider;
//!
//! #[async_trait]
//! impl UserDetailProvider for RandomUserDetailProvider {
//! type User = RandomUser;
//! impl UserDetailProvider for ExampleUserDetailProvider {
//! type User = ExampleUser;
//!
//! async fn provide_user_detail(&self, _principal: &Principal) -> Result<RandomUser, UserDetailError> {
//! Ok(RandomUser {})
//! async fn provide_user_detail(&self, _principal: &Principal) -> Result<ExampleUser, UserDetailError> {
//! Ok(ExampleUser {})
//! }
//! }
//! ```
//!
//! 3. Initialize it with the server in your application:
//!
//! ```no_run
//! # use unftp_core::auth::Principal;
//! # async fn demo() {
//! let _principal = Principal { username: "alice".to_string() };
//! # }
//! ```
//! 3. Configure the authenticator and user-detail provider on your [`libunftp::ServerBuilder`](https://docs.rs/libunftp/latest/libunftp/struct.ServerBuilder.html).
//!

mod authenticator;
Expand Down
20 changes: 10 additions & 10 deletions crates/unftp-core/src/auth/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ pub trait UserDetail: Send + Sync + Display + Debug {
/// }
/// ```
///
/// [`Principal`]: ../struct.Principal.html
/// [`UserDetail`]: trait.UserDetail.html
/// [`Principal`]: crate::auth::Principal
/// [`UserDetail`]: crate::auth::UserDetail
#[async_trait]
pub trait UserDetailProvider: Send + Sync + Debug {
/// The `UserDetail` type that this provider returns
Expand All @@ -97,16 +97,16 @@ pub trait UserDetailProvider: Send + Sync + Debug {
/// Returns [`UserDetailError`] if the user details cannot be retrieved, for example if the
/// user is not found in the user database.
///
/// [`Principal`]: ../struct.Principal.html
/// [`UserDetail`]: trait.UserDetail.html
/// [`UserDetailError`]: enum.UserDetailError.html
/// [`Principal`]: crate::auth::Principal
/// [`UserDetail`]: crate::auth::UserDetail
/// [`UserDetailError`]: crate::auth::UserDetailError
async fn provide_user_detail(&self, principal: &Principal) -> Result<Self::User, UserDetailError>;
}

/// The error type returned by [`UserDetailProvider::provide_user_detail`]
///
/// [`UserDetailProvider`]: trait.UserDetailProvider.html
/// [`UserDetailProvider::provide_user_detail`]: trait.UserDetailProvider.html#tymethod.provide_user_detail
/// [`UserDetailProvider`]: crate::auth::UserDetailProvider
/// [`UserDetailProvider::provide_user_detail`]: crate::auth::UserDetailProvider::provide_user_detail
#[derive(Debug, Error)]
pub enum UserDetailError {
/// A generic error occurred while retrieving user details
Expand Down Expand Up @@ -172,9 +172,9 @@ impl Display for DefaultUser {
/// # }
/// ```
///
/// [`UserDetailProvider`]: trait.UserDetailProvider.html
/// [`Principal`]: ../struct.Principal.html
/// [`DefaultUser`]: struct.DefaultUser.html
/// [`UserDetailProvider`]: crate::auth::UserDetailProvider
/// [`Principal`]: crate::auth::Principal
/// [`DefaultUser`]: crate::auth::DefaultUser
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DefaultUserDetailProvider;

Expand Down
42 changes: 21 additions & 21 deletions crates/unftp-core/src/storage/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ use crate::BoxError;
use derive_more::Display;
use thiserror::Error;

/// The Error returned by storage backends. Storage backend implementations should choose the
/// `ErrorKind` chosen for errors carefully since that will determine what is returned to the FTP
/// client.
/// An error returned by a storage backend.
///
/// Choose the [`ErrorKind`] carefully: the server uses it to select the FTP reply sent to the
/// client. The optional source error is retained for diagnostics.
#[derive(Debug, Error)]
#[error("storage error: {kind}")]
pub struct Error {
Expand All @@ -14,7 +15,9 @@ pub struct Error {
}

impl Error {
/// Creates a new storage error
/// Creates a storage error with an underlying cause.
///
/// The server maps `kind` to an FTP reply; `error` is retained as the source for diagnostics.
pub fn new<E>(kind: ErrorKind, error: E) -> Error
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
Expand All @@ -25,7 +28,7 @@ impl Error {
}
}

/// Detailed information about what the FTP server should do with the failure
/// Returns the kind that determines how the server reports this failure to the FTP client.
pub fn kind(&self) -> ErrorKind {
self.kind
}
Expand All @@ -44,32 +47,30 @@ impl From<ErrorKind> for Error {

/// The `ErrorKind` variants that can be produced by the [`StorageBackend`] implementations.
///
/// [`StorageBackend`]: trait.StorageBackend.html
/// [`StorageBackend`]: crate::storage::StorageBackend
#[derive(Copy, Clone, Eq, PartialEq, Debug, Display)]
pub enum ErrorKind {
/// Error that will cause an FTP reply code of 450 to be returned to the FTP client.
/// The storage back-end implementation should return this if a error occurred that my be
/// retried for example in the case where a file is busy.
/// Return this for a temporary failure that may succeed if retried, such as a file that is
/// temporarily busy.
#[display("450 Transient file not available")]
TransientFileNotAvailable,
/// Error that will cause an FTP reply code of 550 to be returned to the FTP client.
/// The storage back-end implementation should return this if a error occurred where it doesn't
/// make sense for it to be retried. For example in the case where a file is busy.
/// Return this when retrying is not expected to help, such as when the requested file does not
/// exist.
#[display("550 Permanent file not available")]
PermanentFileNotAvailable,
/// Error that will cause an FTP reply code of 550 to be returned to the FTP client.
/// The storage back-end implementation should return this if a error occurred where it doesn't
/// make sense for it to be retried. For example in the case where the directory doesn't exist
/// Return this when retrying is not expected to help, such as when the requested directory does
/// not exist.
#[display("550 Permanent directory not available")]
PermanentDirectoryNotAvailable,
/// Error that will cause an FTP reply code of 550 to be returned to the FTP client.
/// The storage back-end implementation should return this if a error occurred where it doesn't
/// make sense for it to be retried. For example in the case where file access is denied.
/// Return this when a directory cannot be removed because it is not empty.
#[display("550 The directory is not empty")]
PermanentDirectoryNotEmpty,
/// Error that will cause an FTP reply code of 550 to be returned to the FTP client.
/// The storage back-end implementation should return this if a error occurred where it doesn't
/// make sense for it to be retried. For example in the case where file access is denied.
/// Return this when the requested operation is denied by the storage backend's permissions.
#[display("550 Permission denied")]
PermissionDenied,
/// Error that will cause an FTP reply code of 426 to be returned to the FTP client. It means the transfer was
Expand All @@ -91,14 +92,13 @@ pub enum ErrorKind {
/// dataset).
#[display("552 Exceeded storage allocation error")]
ExceededStorageAllocationError,
/// Error that will cause an FTP reply code of 553 to be returned to the FTP client. Its means
/// Error that will cause an FTP reply code of 553 to be returned to the FTP client. It means
/// the requested action was not taken due to an illegal file name.
#[display("553 File name not allowed error")]
FileNameNotAllowedError,
/// Error that will cause an FTP reply code of 502. The indicates to the client that the command
/// is not implemented for the storage back-end. For instance the GCS back-end don't implement
/// RMD (remove directory) but returns this error instead from its StorageBackend::rmd
/// implementation.
/// Error that causes FTP reply code 502, indicating that the storage backend does not
/// implement the requested command. For example, a backend that cannot remove directories may
/// return this from its `StorageBackend::rmd` implementation.
#[display("502 Command not implemented")]
CommandNotImplemented,
}
7 changes: 3 additions & 4 deletions crates/unftp-core/src/storage/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Contains the [`StorageBackend`] trait that can be implemented to create virtual file systems for libunftp.
//!
//! Pre-made implementations exists on crates.io (search for `unftp-sbe-`) and you can define your
//! Pre-made implementations exist on crates.io (search for `unftp-sbe-`) and you can define your
//! own implementation to integrate your FTP(S) server with whatever storage mechanism you prefer.
//!
//! To create a new storage back-end:
Expand All @@ -10,7 +10,7 @@
//! ```toml
//! async-trait = "0.1.89"
//! tokio = { version = "1.49.0", features = ["full"] }
//! unftp-core = { path = "../path/to/unftp-core" }
//! unftp-core = "0.1"
//! ```
//!
//! 2. Implement the [`StorageBackend`] trait and optionally the [`Metadata`] trait:
Expand Down Expand Up @@ -157,8 +157,7 @@
//! }
//! ```
//!
//! 3. Initialize it with the server in your application.
//!
//! 3. Register the backend when constructing a server with [`libunftp::ServerBuilder`](https://docs.rs/libunftp/latest/libunftp/struct.ServerBuilder.html).

mod error;
pub use error::{Error, ErrorKind};
Expand Down
Loading
Loading