Compare commits

...

2 Commits

Author SHA1 Message Date
Oskar ff02a1e180 feat: add support for disable https to run http server 2022-09-26 20:04:28 +00:00
Oskar 1b9529223a chore: configure github codespace 2022-09-26 19:41:37 +00:00
7 changed files with 117 additions and 19 deletions

16
.devcontainer/Dockerfile Normal file
View File

@ -0,0 +1,16 @@
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/rust/.devcontainer/base.Dockerfile
# [Choice] Debian OS version (use bullseye on local arm64/Apple Silicon): buster, bullseye
ARG VARIANT="buster"
FROM mcr.microsoft.com/vscode/devcontainers/rust:0-${VARIANT}
USER vscode
RUN rustup install nightly \
&& rustup component add rustfmt --toolchain nightly \
&& rustup component add clippy --toolchain nightly
USER root
# [Optional] Uncomment this section to install additional packages.
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
# && apt-get -y install --no-install-recommends <your-package-list-here>

View File

@ -0,0 +1,52 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/rust
{
"name": "Rust",
"build": {
"dockerfile": "Dockerfile",
"args": {
// Use the VARIANT arg to pick a Debian OS version: buster, bullseye
// Use bullseye when on local on arm64/Apple Silicon.
"VARIANT": "bullseye"
}
},
"runArgs": [
"--cap-add=SYS_PTRACE",
"--security-opt",
"seccomp=unconfined"
],
// Configure tool-specific properties.
"customizations": {
// Configure properties specific to VS Code.
"vscode": {
// Set *default* container specific settings.json values on container create.
"settings": {
"lldb.executable": "/usr/bin/lldb",
// VS Code don't watch files under ./target
"files.watcherExclude": {
"**/target/**": true
},
"rust-analyzer.checkOnSave.command": "clippy"
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"vadimcn.vscode-lldb",
"mutantdino.resourcemonitor",
"rust-lang.rust-analyzer",
"tamasfe.even-better-toml",
"serayuzgur.crates"
]
}
},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "rustc --version",
// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode"
}

6
.gitignore vendored
View File

@ -1,5 +1,4 @@
# Generated by Cargo
# will have compiled files and executables
# Rust output
/target
# Logs files
@ -17,3 +16,6 @@ cert.pem
# IDE configs
.idea
.vscode
# Development storage directory
/storage

View File

@ -28,7 +28,7 @@ Now you can run server using command `./target/release/homedisk`.
```bash
# Generate private key
openssl genrsa -out cert.key 204
openssl genrsa -out cert.key 2048
# Generate certificate
openssl req -new -x509 -key cert.key -out cert.pem -days 365
```

View File

@ -1,6 +1,7 @@
[http]
host = "0.0.0.0"
httpPort = 8080 # http server port (recommended 80)
enableHttps = true # if true start https server and http will be redirect to https
httpsPort = 8443 # https server port (recommended 443)
cors = [ "localhost:8000" ] # CORS domains
tlsCert = "./cert.pem" # TLS certificate file
@ -11,4 +12,4 @@ secret = "secret key used to sign tokens" # jsonwebtoken secret string used to s
expires = 24 # token expiration time in hours (default one day)
[storage]
path = "/home/homedisk" # path to directory where user files will be stored
path = "storage" # path to directory where user files will be stored

View File

@ -14,6 +14,7 @@ pub struct Config {
pub struct ConfigHTTP {
pub host: String,
pub http_port: u16,
pub enable_https: bool,
pub https_port: u16,
pub cors: Vec<String>,
pub tls_cert: String,

View File

@ -2,7 +2,10 @@ mod api;
pub mod error;
pub mod utils;
use std::path::PathBuf;
use std::{
path::{Path, PathBuf},
process::exit,
};
use anyhow::anyhow;
use axum::{
@ -18,14 +21,27 @@ use tower_http::{
cors::{AllowOrigin, CorsLayer},
BoxError,
};
use tracing::{debug, info};
use tracing::{debug, error, info};
use crate::{config::Config, database::Database};
pub async fn start_server(config: Config, db: Database) -> anyhow::Result<()> {
let host = format!("{}:{}", config.http.host, config.http.https_port);
let host = if config.http.enable_https {
format!("{}:{}", config.http.host, config.http.https_port)
} else {
format!("{}:{}", config.http.host, config.http.http_port)
};
tokio::spawn(redirect_http_to_https(config.clone()));
if config.http.enable_https {
// check if tls cert and key file exists
if !Path::new(&config.http.tls_cert).exists() || !Path::new(&config.http.tls_key).exists() {
error!("TLS cert or/and key file not found!");
exit(1);
}
// start http redirect to https
tokio::spawn(redirect_http_to_https(config.clone()));
}
info!("🚀 Server has launched on https://{host}");
@ -37,23 +53,33 @@ pub async fn start_server(config: Config, db: Database) -> anyhow::Result<()> {
.map(|e| e.parse().expect("Failed to parse CORS hosts"))
.collect::<Vec<HeaderValue>>();
let tls_config = RustlsConfig::from_pem_file(
PathBuf::from("").join("").join(&config.http.tls_cert),
PathBuf::from("").join("").join(&config.http.tls_key),
)
.await
.unwrap();
let app = Router::new()
.nest("/api", api::app())
.route("/", get(api::health))
.layer(CorsLayer::new().allow_origin(AllowOrigin::list(origins)))
.layer(Extension(config))
.layer(Extension(config.clone()))
.layer(Extension(db));
axum_server::bind_rustls(host.parse()?, tls_config)
.serve(app.into_make_service())
.await?;
// if https is enabled, run it, otherwise run server http
if config.http.enable_https {
// start https server
let tls_config = RustlsConfig::from_pem_file(
PathBuf::from("").join("").join(&config.http.tls_cert),
PathBuf::from("").join("").join(&config.http.tls_key),
)
.await
.unwrap();
axum_server::bind_rustls(host.parse()?, tls_config)
.serve(app.into_make_service())
.await?;
} else {
// start http server
axum::Server::bind(&host.parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
Err(anyhow!("Server unexpected stopped!"))
}