Skip to content

Commit fe03997

Browse files
authored
Merge pull request #74 from debatecore/73-modify-cors-to-allow-including-credentials
[73] modify cors to allow including credentials
2 parents fe5c383 + 0713216 commit fe03997

File tree

4 files changed

+40
-4
lines changed

4 files changed

+40
-4
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ You may also venture on your own, adapting the following instructions to your ne
1111
Set the following environment variables, via `.env` or your shell:
1212
- `DOCKER_DB_ROOT_PASSWORD` will be used as the password for the database root user.
1313
- `DATABASE_URL` is used for db connection. During development, this is `postgres://tau:tau@localhost:5432/tau`.
14-
- `SECRET` will be used as high entropy data used for generating tokens.
14+
- `FRONTEND_ORIGIN` will be used as an allowed [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) for the purpose of [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS). Must be a valid URL.
1515

1616
Start the database with `docker compose --profile dev (up -d/down)`.
1717
Run the migrations via sqlx-cli with `sqlx run migrate` or by other means.
@@ -22,10 +22,11 @@ Compile and run the project with `cargo`.
2222
For deploying via docker, set the following environment variables:
2323
- `DOCKER_DB_PASSWORD` which will be used as the password for the backend's database access user.
2424
- `DOCKER_DB_ROOT_PASSWORD` will be used as the password for the database root user.
25-
- `SECRET` will be used as high entropy data used for generating tokens.
25+
- `FRONTEND_ORIGIN` will be used as an allowed [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) for the purpose of [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS). Must be a valid URL (`http://localhost:3000` by default).
2626
Then, run `docker compose --profile prod`.
2727

2828
### Optional configuration
29+
- `SECRET` will be used as additional high entropy data used for generating tokens. By default, tau uses system entropy and the current UNIX timestamp.
2930
- `PORT` will be used as the port the server listens on. The default is 2023.
3031

3132
The following example `.env` file is geared for both scenarios:
@@ -34,6 +35,7 @@ DATABASE_URL=postgres://tau:tau@localhost:5432/tau
3435
SECRET=CENTRUMRWLYSONOSTARPOZNANCDNSBCD4L52SPM
3536
DOCKER_DB_ROOT_PASSWORD=superdoopersecretpasswordthatcannotbeleaked
3637
DOCKER_DB_PASSWORD=wedoingsecurityinhere
38+
FRONTEND_ORIGIN=https://example.com
3739
PORT=2019
3840
```
3941

compose.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ services:
1313
- DATABASE_URL=postgres://tau:${DOCKER_DB_PASSWORD}@db-prod:5432/tau
1414
- PORT=${PORT}
1515
- SECRET=${SECRET}
16+
- FRONTEND_ORIGIN=${FRONTEND_ORIGIN}
1617
depends_on:
1718
db-prod:
1819
condition: service_healthy
@@ -49,6 +50,7 @@ services:
4950
- dbrootpassword
5051
environment:
5152
- POSTGRES_PASSWORD_FILE=/run/secrets/dbrootpassword
53+
- FRONTEND_ORIGIN=http://localhost:3000
5254
volumes:
5355
- dbdevdata:/var/lib/postgresql/data
5456
- ./dbinit-dev.sh:/docker-entrypoint-initdb.d/dbinit-dev.sh

src/main.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use axum::Router;
22
use tokio::net::TcpListener;
33
use tower_cookies::CookieManagerLayer;
4-
use tower_http::cors::{Any, CorsLayer};
54
use tracing::error;
65
use users::infradmin::guarantee_infrastructure_admin_exists;
76

@@ -25,7 +24,7 @@ async fn main() {
2524
let app = Router::new()
2625
.merge(routes::routes())
2726
.with_state(state)
28-
.layer(CorsLayer::new().allow_origin(Any).allow_methods(Any))
27+
.layer(setup::configure_cors())
2928
.layer(CookieManagerLayer::new());
3029

3130
let addr = setup::get_socket_addr();

src/setup.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
use axum::http::{header::CONTENT_TYPE, HeaderValue, Method};
12
use sqlx::{Pool, Postgres};
23
use std::net::{Ipv4Addr, SocketAddrV4};
34
use tokio::net::TcpListener;
5+
use tower_http::cors::CorsLayer;
46
use tracing::{error, info, warn, Level};
57
use tracing_subscriber::FmtSubscriber;
68

@@ -9,6 +11,7 @@ use crate::database;
911
const CRYPTO_SECRET_CORRECT: &str = "Cryptographic SECRET is set.";
1012
const CRYPTO_SECRET_NOT_SET: &str = "Cryptographic SECRET is not set. This may lead to increased predictability in token generation.";
1113
const CRYPTO_SECRET_ERROR: &str = "Could not read SECRET. Is it valid UTF-8?";
14+
const FRONTEND_ORIGIN_NOT_SET: &str = "FRONTEND_ORIGIN is not set. Please provide a valid URL leading to an accepted origin.";
1215

1316
pub fn initialise_logging() {
1417
let subscriber = FmtSubscriber::builder()
@@ -94,3 +97,33 @@ pub fn check_secret_env_var() {
9497
},
9598
}
9699
}
100+
101+
pub fn configure_cors() -> CorsLayer {
102+
let default_origin = "http://localhost:3000".to_owned();
103+
let result = std::env::var("FRONTEND_ORIGIN");
104+
105+
#[cfg(not(debug_assertions))]
106+
if result.is_err() {
107+
error!("{}", FRONTEND_ORIGIN_NOT_SET);
108+
panic!();
109+
}
110+
111+
let frontend_origin = result.unwrap_or(default_origin);
112+
info!(
113+
"FRONTEND_ORIGIN set to {}. Requests made from any other origins will be disallowed at browser level",
114+
&frontend_origin
115+
);
116+
let layer = CorsLayer::new()
117+
.allow_origin(frontend_origin.parse::<HeaderValue>().unwrap())
118+
.allow_methods([
119+
Method::GET,
120+
Method::POST,
121+
Method::DELETE,
122+
Method::PATCH,
123+
Method::PUT,
124+
])
125+
.allow_headers([CONTENT_TYPE])
126+
.allow_credentials(true);
127+
128+
return layer;
129+
}

0 commit comments

Comments
 (0)