Skip to content

Commit

Permalink
CORS setup
Browse files Browse the repository at this point in the history
  • Loading branch information
Jerboa-app committed Mar 25, 2024
1 parent 94ff0b1 commit 71de6c1
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 12 deletions.
32 changes: 25 additions & 7 deletions src/server/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::str::from_utf8;
use axum::{
body::Bytes, http::{HeaderMap, Request}, middleware::Next, response::{Html, IntoResponse, Response}
};
use openssl::conf;
use reqwest::StatusCode;
use serde::Deserialize;

Expand Down Expand Up @@ -87,13 +88,20 @@ impl ApiRequest for Generate
}
};

is_authentic
(
headers,
"psv-token",
config.api_token,
body
)
match config.api_token
{
Some(t) =>
{
is_authentic
(
headers,
"psv-token",
t,
body
)
},
None => StatusCode::ACCEPTED
}
}

fn deserialise_payload(&mut self, _headers: HeaderMap, body: Bytes) -> StatusCode
Expand Down Expand Up @@ -239,6 +247,16 @@ impl ApiRequest for Generate
let time_stamp = chrono::offset::Utc::now().to_rfc3339();
response.headers_mut().insert("date", time_stamp.parse().unwrap());
response.headers_mut().insert("cache-control", format!("public, max-age={}", config.cache_period_seconds).parse().unwrap());

match config.cors_allow_address
{
Some(a) =>
{
response.headers_mut().insert("Access-Control-Allow-Origin", format!("{}",a).parse().unwrap());
response.headers_mut().insert("Access-Control-Allow-Methods", "POST".parse().unwrap());
},
None => {}
}
Ok(response)
},
None => { Err(status) }
Expand Down
8 changes: 5 additions & 3 deletions src/server/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ pub struct ThrottleConfig
/// - ```key_path```: ssl key
/// - ```domain```: domain name for https redirect etc.
/// - ```throttle```: [ThrottleConfig]
/// - ```api_token```: token to use for the server's POST api
/// - ```api_token```: optional token to use for the server's POST api
/// - ```cache_period_seconds```: max cache age for generated content
/// - ```cors_allow_address```: allowed address for cross origin request, leave blank to block
#[derive(Clone, Serialize, Deserialize)]
pub struct Config
{
Expand All @@ -36,8 +37,9 @@ pub struct Config
pub key_path: String,
pub domain: String,
pub throttle: ThrottleConfig,
pub api_token: String,
pub cache_period_seconds: u16
pub api_token: Option<String>,
pub cache_period_seconds: u16,
pub cors_allow_address: Option<String>
}

pub fn read_config() -> Option<Config>
Expand Down
3 changes: 2 additions & 1 deletion src/server/https.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use axum::
};
use axum_server::tls_rustls::RustlsConfig;

use super::api::{ApiRequest, Generate};
use super::{api::{ApiRequest, Generate}, filter_cors_preflight};

/// An https server that reads a directory configured with [Config]
/// ```.html``` pages and resources, then serves them.
Expand Down Expand Up @@ -87,6 +87,7 @@ impl Server

router = router.layer(middleware::from_fn_with_state(throttle_state.clone(), handle_throttle));
router = router.layer(middleware::from_fn(Generate::filter));
router = router.layer(middleware::from_fn(filter_cors_preflight));

Server
{
Expand Down
48 changes: 47 additions & 1 deletion src/server/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,62 @@
use axum::{body::Bytes, http::HeaderMap};
use axum::{body::Bytes, http::{HeaderMap, Request}, middleware::Next, response::{IntoResponse, Response}};
use openssl::{hash::MessageDigest, memcmp, pkey::PKey, sign::Signer};
use regex::Regex;
use reqwest::StatusCode;

use crate::util::{dump_bytes, read_bytes};

use self::config::read_config;

pub mod http;
pub mod https;
pub mod config;
pub mod throttle;
pub mod api;

async fn filter_cors_preflight<B>
(
headers: HeaderMap,
request: Request<B>,
next: Next<B>
) -> Result<Response, StatusCode>
where B: axum::body::HttpBody<Data = Bytes>
{

match headers.contains_key("Access-Control-Request-Headers")
{
false => return Ok(next.run(request).await),
true => {}
}

let config = match read_config()
{
Some(c) => c,
None =>
{
return Ok(StatusCode::INTERNAL_SERVER_ERROR.into_response());
}
};

match config.cors_allow_address
{
Some(a) =>
{
let mut response = String::new().into_response();
response.headers_mut().insert("Access-Control-Allow-Origin", format!("{}",a).parse().unwrap());
response.headers_mut().insert("Access-Control-Allow-Methods", "POST".parse().unwrap());
response.headers_mut().insert("Access-Control-Allow-Headers", "api, content-type".parse().unwrap());

Ok(response)
},
None =>
{
Ok(StatusCode::FORBIDDEN.into_response())
}
}



}
/// Uses openssl to verify the request body via the given hmac_token
/// - hmac_header_key is the location in the https header for the digest
pub fn is_authentic
Expand Down

0 comments on commit 71de6c1

Please sign in to comment.