Skip to content

Commit

Permalink
Refactor middleware and move sending trace to examples directory
Browse files Browse the repository at this point in the history
  • Loading branch information
hatchan committed Jan 14, 2025
1 parent 7f24eaf commit 035c4d9
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 47 deletions.
9 changes: 0 additions & 9 deletions fpx-workers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,6 @@ Now you can simply run the worker using the wrangler CLI:
npx wrangler dev
```

Testing the authenticated `/v1/traces` endpoint:

```bash
curl -X POST http://localhost:8787/v1/traces \
-H "Authorization: Bearer your-secret-token-here" \
-H "Content-Type: application/json" \
--data-binary @trace.json
```

The Rust code will be compiled and once that is finished a local server will be
running on `http://localhost:8787`. You can send traces using any otel exporter
and inspect the traces using the [`fpx client`](../fpx).
Expand Down
11 changes: 11 additions & 0 deletions fpx-workers/examples/send-trace/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Manually submitting a trace

The following curl command shows how you can send a trace to the worker. Be sure
to update the secret token in the command.

```bash
curl -X POST http://localhost:8787/v1/traces \
-H "Authorization: Bearer your-secret-token-here" \
-H "Content-Type: application/json" \
--data-binary @trace.json
```
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,4 @@
]
}
]
}
}
7 changes: 6 additions & 1 deletion fpx-workers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,17 @@ async fn fetch(
let store = D1Store::new(d1_database);
let boxed_store = Arc::new(store);

let expected_token = env
.var("API_TOKEN")
.expect("no auth token is set")
.to_string();

let service = service::Service::new(boxed_store.clone(), boxed_events.clone());
let api_router =
api::Builder::new()
.build(service, boxed_store)
.route_layer(axum::middleware::from_fn(move |req, next| {
auth_middleware(req, env.as_ref().clone(), next)
auth_middleware(expected_token.clone(), req, next)
}));

let mut router: axum::Router = axum::Router::new()
Expand Down
48 changes: 13 additions & 35 deletions fpx-workers/src/middleware/auth.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,25 @@
use axum::{
body::Body,
http::{Request, StatusCode},
middleware::Next,
response::Response,
};

use tracing::debug;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::middleware::Next;
use axum::response::Response;

pub async fn auth_middleware(
expected_token: String,
request: Request<Body>,
env: worker::Env,
next: Next,
) -> Result<Response, StatusCode> {
let expected_token = env
.var("API_TOKEN")
.map_err(|_| {
debug!("Failed to get API_TOKEN");
StatusCode::INTERNAL_SERVER_ERROR
})?
.to_string();

if expected_token.is_empty() {
debug!("API_TOKEN is empty");
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
debug!("Expected token: {}", expected_token);

// Retrieve the Authorization from the request. If we are not able to parse
// the Header or it is missing, then the variable will be a empty &str.
let auth_header = request
.headers()
.get("Authorization")
.and_then(|header| header.to_str().ok());

match auth_header {
Some(auth) if auth.starts_with("Bearer ") => {
let token = &auth[7..];
debug!("Received token: {}", token);
.and_then(|header| header.to_str().ok())
.unwrap_or("");

if token == expected_token {
Ok(next.run(request).await)
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
// Split on the first space and make sure the first part matches 'Bearer'
// and the second part matches the expected_token.
match auth_header.split_once(' ') {
Some(("Bearer", token)) if token == expected_token => Ok(next.run(request).await),
_ => Err(StatusCode::UNAUTHORIZED),
}
}
2 changes: 1 addition & 1 deletion fpx-workers/src/ws/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub async fn ws_connect(State(state): State<WorkerApiState>, headers: HeaderMap)
Err(_) => Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::from(
"An unexpected error occured connecting to the Durable Object",
"An unexpected error occurred connecting to the Durable Object",
))
.unwrap(),
};
Expand Down

0 comments on commit 035c4d9

Please sign in to comment.