remove some logs

This commit is contained in:
dusk 2023-04-21 19:39:04 +03:00
parent f6dd056503
commit dd6fce4b3c
Signed by: dusk
GPG Key ID: 1D8F8FAF2294D6EA
3 changed files with 47 additions and 44 deletions

View File

@ -36,11 +36,24 @@ use crate::{get_conf, AppState};
const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
pub(super) async fn public(state: AppState) -> Result<Router, AppError> { #[derive(Deserialize)]
struct Auth {
#[serde(default)]
token: Option<String>,
}
fn extract_password_from_basic_auth(auth: &str) -> Result<String, AppError> {
let decoded = B64.decode(auth.trim_start_matches("Basic "))?;
let auth = String::from_utf8(decoded)?;
Ok(auth.trim_start_matches("default:").to_string())
}
pub(super) async fn handler(state: AppState) -> Result<Router, AppError> {
let trace_layer = let trace_layer =
TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::default().include_headers(true)); TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::default().include_headers(true));
let router = Router::new() let router = Router::new()
.route("/generate_token", get(generate_token))
.route("/thumbnails/:id", get(http)) .route("/thumbnails/:id", get(http))
.route("/audio/id/:id", get(http)) .route("/audio/id/:id", get(http))
.route("/", get(metadata_ws)) .route("/", get(metadata_ws))
@ -57,13 +70,16 @@ pub(super) async fn public(state: AppState) -> Result<Router, AppError> {
Ok(router) Ok(router)
} }
pub(super) async fn internal(state: AppState) -> Router { async fn generate_token(
Router::new() State(app): State<AppState>,
.route("/generate_token", get(generate_token)) ConnectInfo(addr): ConnectInfo<SocketAddr>,
.with_state(state) ) -> Result<axum::response::Response, AppError> {
} // disallow any connections other than local ones
if !addr.ip().is_loopback() {
return Ok((StatusCode::FORBIDDEN, "not allowed").into_response());
}
async fn generate_token(State(app): State<AppState>) -> Result<impl IntoResponse, AppError> { // generate token
let token = app.tokens.generate().await?; let token = app.tokens.generate().await?;
// start task to write tokens // start task to write tokens
tokio::spawn(async move { tokio::spawn(async move {
@ -71,19 +87,7 @@ async fn generate_token(State(app): State<AppState>) -> Result<impl IntoResponse
tracing::error!("couldn't write tokens file: {err}"); tracing::error!("couldn't write tokens file: {err}");
} }
}); });
return Ok(token); return Ok(token.into_response());
}
#[derive(Deserialize)]
struct Auth {
#[serde(default)]
token: Option<String>,
}
fn extract_password_from_basic_auth(auth: &str) -> Result<String, AppError> {
let decoded = B64.decode(auth.trim_start_matches("Basic "))?;
let auth = String::from_utf8(decoded)?;
Ok(auth.trim_start_matches("default:").to_string())
} }
async fn http( async fn http(
@ -186,7 +190,6 @@ async fn handle_metadata_socket(
let (token, og_auth_msg) = 'ok: { let (token, og_auth_msg) = 'ok: {
'err: { 'err: {
if let Some(Ok(AxumMessage::Text(raw))) = client_socket.recv().await { if let Some(Ok(AxumMessage::Text(raw))) = client_socket.recv().await {
tracing::debug!("got client auth message: {raw}");
let Ok(parsed) = serde_json::from_str::<WsApiMessage>(&raw) else { let Ok(parsed) = serde_json::from_str::<WsApiMessage>(&raw) else {
tracing::error!("invalid auth message"); tracing::error!("invalid auth message");
break 'err; break 'err;
@ -253,7 +256,6 @@ async fn handle_metadata_socket(
}, },
}; };
let auth_msg_ser = serde_json::to_string(&auth_msg).expect(""); let auth_msg_ser = serde_json::to_string(&auth_msg).expect("");
tracing::debug!("sending auth message to musikcubed: {auth_msg_ser}");
if let Err(err) = server_socket if let Err(err) = server_socket
.send(TungsteniteMessage::Text(auth_msg_ser)) .send(TungsteniteMessage::Text(auth_msg_ser))
.await .await
@ -263,7 +265,6 @@ async fn handle_metadata_socket(
} }
// wait for auth reply // wait for auth reply
if let Some(Ok(TungsteniteMessage::Text(raw))) = server_socket.next().await { if let Some(Ok(TungsteniteMessage::Text(raw))) = server_socket.next().await {
tracing::debug!("got auth reply from musikcubed: {raw}");
let Ok(parsed) = serde_json::from_str::<WsApiMessage>(&raw) else { let Ok(parsed) = serde_json::from_str::<WsApiMessage>(&raw) else {
tracing::error!("invalid auth response message: {raw}"); tracing::error!("invalid auth response message: {raw}");
break 'err; break 'err;

View File

@ -1,5 +1,6 @@
use std::{net::SocketAddr, sync::Arc}; use std::{net::SocketAddr, sync::Arc};
use axum_server::tls_rustls::RustlsConfig;
use dotenvy::Error as DotenvError; use dotenvy::Error as DotenvError;
use error::AppError; use error::AppError;
use hyper::{client::HttpConnector, Body}; use hyper::{client::HttpConnector, Body};
@ -35,30 +36,32 @@ async fn app() -> Result<(), AppError> {
Err(err) => return Err(err.into()), Err(err) => return Err(err.into()),
} }
// let cert_path = get_conf("TLS_CERT_PATH"); let cert_path = get_conf("TLS_CERT_PATH").ok();
// let key_path = get_conf("TLS_KEY_PATH"); let key_path = get_conf("TLS_KEY_PATH").ok();
// info!("cert path is: {cert_path}");
// info!("key path is: {key_path}");
// let config = RustlsConfig::from_pem_file(cert_path, key_path)
// .await
// .unwrap();
let public_addr: SocketAddr = get_conf("ADDRESS")?.parse()?; let addr: SocketAddr = get_conf("ADDRESS")?.parse()?;
let local_addr: SocketAddr = get_conf("LOCAL_ADDRESS")?.parse()?;
let state = AppState::new(AppStateInternal::new(public_addr.port()).await?); let state = AppState::new(AppStateInternal::new(addr.port()).await?);
let public = handler::public(state.clone()).await?; let router = handler::handler(state).await?;
let internal = handler::internal(state).await; let make_service = router.into_make_service_with_connect_info::<SocketAddr>();
info!("listening on {public_addr} for public APIs, on {local_addr} for internal API use"); let (task, scheme) = if let (Some(cert_path), Some(key_path)) = (cert_path, key_path) {
// axum_server::bind_rustls(addr, config) info!("cert path is: {cert_path}");
let public = axum_server::bind(public_addr) info!("key path is: {key_path}");
.serve(public.into_make_service_with_connect_info::<SocketAddr>()); let config = RustlsConfig::from_pem_file(cert_path, key_path)
let internal = axum_server::bind(local_addr).serve(internal.into_make_service()); .await
.unwrap();
let task = tokio::spawn(axum_server::bind_rustls(addr, config).serve(make_service));
(task, "https")
} else {
let task = tokio::spawn(axum_server::bind(addr).serve(make_service));
(task, "http")
};
tokio::try_join!(public, internal) info!("listening on {scheme}://{addr}");
.map(|_| ()) task.await??;
.map_err(Into::into)
Ok(())
} }
fn get_conf(key: &str) -> Result<String, AppError> { fn get_conf(key: &str) -> Result<String, AppError> {

View File

@ -64,7 +64,6 @@ impl Tokens {
pub async fn verify(&self, token: impl AsRef<str>) -> Result<bool, AppError> { pub async fn verify(&self, token: impl AsRef<str>) -> Result<bool, AppError> {
let token = token.as_ref(); let token = token.as_ref();
let token_hash = hash_string(token.as_bytes())?; let token_hash = hash_string(token.as_bytes())?;
tracing::debug!("verifying token {token}, hash {token_hash}");
Ok(self.hashed.contains_async(&Cow::Owned(token_hash)).await) Ok(self.hashed.contains_async(&Cow::Owned(token_hash)).await)
} }
} }