Skip to content
This repository has been archived by the owner on Jan 7, 2025. It is now read-only.

Commit

Permalink
Implement CORS & refactor logging
Browse files Browse the repository at this point in the history
  • Loading branch information
containerscrew committed Nov 2, 2024
1 parent 57a86b2 commit 998da68
Show file tree
Hide file tree
Showing 10 changed files with 54 additions and 24 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ description = "Proxy server for IP geolocation. Use external services to get the

[dependencies]
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["json"] }
tracing-subscriber = { version = "0.3.18", features = ["json", "fmt"] }
axum = "0.7.5"
serde_json = "1.0.122"
serde = { version = "1.0.205", features = ["derive"] }
Expand All @@ -25,4 +25,4 @@ bson = "2.11.0"
thiserror = "1.0.63"
openssl = { version = "0.10.59", features = ["vendored"] }
rand = "0.8.5"
tower-http = { version = "0.6.1", features = ["trace"] }
tower-http = { version = "0.6.1", features = ["cors", "trace"] }
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
FROM docker.io/rust:1.80-bullseye as build

WORKDIR /app
COPY . /app
COPY .. /app

RUN cargo build --release

FROM gcr.io/distroless/cc-debian12
WORKDIR /app
COPY --from=build /app/target/release/iproxy /app/iproxy
COPY config.toml /app/config.toml
COPY ../config.toml /app/config.toml
EXPOSE 8000
CMD ["./iproxy"]
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ With [this file](./config.toml) located in the root of this repository, you will
|:----------------------------|
| Before start the docker-compose, change the directory where you want to save the mongodb data |

Example, from [compose.yml](./compose.yml):
Example, from [compose.yml](compose.yml):

```yaml
mongodb:
Expand Down Expand Up @@ -163,6 +163,8 @@ mongorestore --uri="mongodb+srv://USERNAME:PASSWORD@XXXXX.XXXX.mongodb.net/?retr

* Testing and error handling with custom errors ([MyErrors](./src/error.rs))
* Generate possible public ipv4 https://www.criminalip.io/ip-ranges
* Prometheus metrics
* JWT token

# Pending to fix

Expand Down
15 changes: 14 additions & 1 deletion compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ services:
iproxy:
build:
context: .
dockerfile: Dockerfile
dockerfile: ./Dockerfile
restart: unless-stopped
container_name: iproxy
networks:
Expand All @@ -24,6 +24,19 @@ services:
volumes:
- /mnt/ssd/iproxy:/data/db

# mongodb_exporter:
# image: docker.io/percona/mongodb_exporter:latest
# container_name: mongodb_exporter
# networks:
# - iproxy
# restart: unless-stopped
# ports:
# - 9216:9216
# environment:
# - MONGODB_URI=mongodb://admin:admin@mongodb:27017
# depends_on:
# - mongodb

# docker network create iproxy
networks:
iproxy:
Expand Down
5 changes: 3 additions & 2 deletions config.toml
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
[server]
address = "0.0.0.0"
port = 8000
use_proxy = true
use_proxy = false

[logging]
log_level = "info"
log_level = "info" # trace, debug, info, warn or error. Defaults to info if not set
log_type = "json" # text or json. Defaults to text if not set

[database]
# If you are running iproxy in localhost, change the address from mongodb:27017 to localhost:27017
Expand Down
3 changes: 2 additions & 1 deletion local.config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ port = 8000
use_proxy = false

[logging]
log_level = " info"
log_level = "info" # trace, debug, info, warn or error. Defaults to info if not set
log_type = "text" # text or json. Defaults to text if not set

[database]
# If you are running iproxy in localhost, change the address from mongodb:27017 to localhost:27017
Expand Down
3 changes: 2 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ pub struct ServerConfig {
#[derive(Deserialize)]
pub struct LoggingConfig {
pub(crate) log_level: String,
}
pub(crate) log_type: String,
}

#[derive(Deserialize)]
pub struct DatabaseConfig {
Expand Down
4 changes: 2 additions & 2 deletions src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::Json;
use std::sync::Arc;
use tracing::{info, trace, warn};
use tracing::{trace, warn};

pub async fn health_checker_handler() -> impl IntoResponse {
// Healthcheck response
Expand Down Expand Up @@ -54,7 +54,7 @@ pub async fn get_ip(

// Try to insert the geolocation data into the database
match app_state.db.insert_ip(&data).await {
Ok(_) => info!("Ip {} registered in database", ip),
Ok(_) => trace!("Ip {} registered in database", ip),
Err(e) => warn!("Error inserting IP data into database: {}", e),
}

Expand Down
21 changes: 12 additions & 9 deletions src/logger.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::fmt::{format::FmtSpan};

pub fn setup_logger(log_level: String) {
pub fn setup_logger(log_level: String, format: String) {
let log_level = match log_level.as_str() {
"trace" => tracing::Level::TRACE,
"debug" => tracing::Level::DEBUG,
Expand All @@ -10,15 +10,18 @@ pub fn setup_logger(log_level: String) {
_ => tracing::Level::INFO,
};

tracing_subscriber::fmt()
.json()
// Create a base subscriber with common settings
let base_subscriber = tracing_subscriber::fmt()
.with_thread_names(false)
.with_max_level(log_level)
.with_span_events(FmtSpan::FULL)
.with_file(false)
.with_target(false)
.with_current_span(true)
.flatten_event(true)
// .with_timer(CustomTimeFormatter)
.init();
.with_target(false);

// Apply JSON or text formatting based on the format parameter
match format.as_str() {
"json" => base_subscriber.json().init(),
"text" => base_subscriber.init(),
_ => base_subscriber.init(),
};
}
15 changes: 12 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ use crate::logger::setup_logger;
use crate::router::create_router;
use std::net::SocketAddr;
use std::sync::Arc;
use axum::http::{HeaderValue, Method};
use axum::http::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE};
use tower_http::cors::CorsLayer;
use tracing::info;

mod config;
Expand All @@ -29,7 +32,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load_config();

// Enable logging
setup_logger(config.logging.log_level);
setup_logger(config.logging.log_level, config.logging.log_type);

info!("starting iproxy server");

Expand All @@ -41,13 +44,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)
.await?;

// TODO: control CORS
// Cors
let cors = CorsLayer::new()
.allow_origin("http://127.0.0.1:8000".parse::<HeaderValue>().unwrap())
.allow_methods([Method::GET, Method::POST, Method::PATCH, Method::DELETE])
.allow_credentials(true)
.allow_headers([AUTHORIZATION, ACCEPT, CONTENT_TYPE]);

// Run server
let app = create_router(Arc::new(AppState {
db: db.clone(),
use_proxy: config.server.use_proxy,
})); //.layer(cors);
})).layer(cors);

let app = app.fallback(handler_404);

// Create index
Expand Down

0 comments on commit 998da68

Please sign in to comment.