lawliet89 / rocket_cors Goto Github PK
View Code? Open in Web Editor NEWCross-origin resource sharing (CORS) for Rocket.rs applications
Home Page: https://lawliet89.github.io/rocket_cors/
License: Apache License 2.0
Cross-origin resource sharing (CORS) for Rocket.rs applications
Home Page: https://lawliet89.github.io/rocket_cors/
License: Apache License 2.0
When trying to follow the fairing example I get the following:
61 | .attach(cors)
| ^^^^ the trait `Fairing` is not implemented for `Cors`
Versions:
rocket = "0.5.0-rc.1"
rocket_contrib = "0.4.10"
rocket_cors = "0.5.2"
Building the CORS object:
let cors = if config.cors.dev_mode {
rocket_cors::CorsOptions::default().to_cors()?
} else {
let allowed_methods = config.cors.allowed_methods.iter()
.map(|f| FromStr::from_str(f).unwrap())
.collect();
rocket_cors::CorsOptions {
allowed_origins: AllowedOrigins::some_exact(&config.cors.allowed_origins),
allowed_methods,
allowed_headers: AllowedHeaders::some(&["Authorization", "Accept", "Content Type"]),
allow_credentials: true,
..Default::default()
}.to_cors()?
};
And the Rocket instance:
rocket::build()
.configure(config::to_rocket(config.clone()))
.mount("/api",
routes![
views::healthcheck::check,
]
)
.attach(cors)
Rocket can be used with stable rust now (see tracking issue rwf2/Rocket#19 ). What are the blockers for compiling rocket_cors on stable rust now - can we start a tracking issue? :)
After I added this cors fairing to allow my subdomain on my production server to access the api on the main domain, now it's not working on localhost anymore because I'm using browsersync with api proxy during development, so even though for browsers this doesn't count as a cors request because it's localhost (it was working on localhost before I added the cors fairing), the rocket cors fairing treats it as a cors request and does not allow requests from localhost at a different port.
So how can I either exclude localhost from the cors rules of this crate completely (like browsers) or allow all ports from localhost to access my api?
Hey there guys,
I may have this one completely wrong but by the looks of it the fairing only handles automagically generating the preflight / OPTIONS request and not the correct headers for other request types. Its not obvious to me the idiomatic way to achieve this. I could obviously go through request but I'm adding CORS to an already existing application so this is going to be a long winded task.
Basically wanted to check if there was some kind of exploiting default headers in rocket rather than manually tweaking all the existing code.
Cheers.
Ash.
I'm trying to get this to work, but don't have any CORS headers in my responses.
At some point I tried the example: cargo run --example fairing
in this repo, but to no avail π’ .
Am I misunderstanding something?
β― http GET http://localhost:8000/
HTTP/1.1 200 OK
content-length: 10
content-type: text/plain; charset=utf-8
date: Sat, 25 Nov 2023 10:10:22 GMT
permissions-policy: interest-cohort=()
server: Rocket
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
Hello CORS
c.f. #29
Also document why the route is there in the first place.
If I'm not mistaken there are two ways right now if one wants to create CorsOptions which differ in some fields from the default option:
let cors_options = CorsOptions{ allow_credentials: true, max_age: Some(100), ..Default::default() };
or
let mut cors_options = CorsOptions::default();
cors_options.allow_credentials = true;
cors_options.max_age = Some(100);
Since the first variant (in my experience) is hardly used at all and the second one is very cumbersome, I would suggest a build pattern so that one could use the following code:
let cors_options = CorsOptions::default().allow_credentails(true).max_age(Some(100));
If you agree with this change, I would implement it and then open a Pull Request.
Rocket just released v0.4.0-rc1. It would be great to have support for that in rocket_cors.
I'm facing a weird scenario with cors, so I built an electron app and when it interacts with my API I get a response back. The electron app uses Axios to handle data fetching and it works
But when I call the same request in my web application
built with (Next Js), I get a 403 error on the options request.
Below is a snippet of what my server looks like. It's fairly simple.
#![feature(proc_macro_hygiene, decl_macro)]
use js_typify_gostruct;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
#[macro_use]
extern crate serde_derive;
use rocket::http::Method;
use rocket::response::status::BadRequest;
use rocket_contrib::json::{Json, JsonValue};
use rocket_cors::{AllowedHeaders, AllowedOrigins, Error};
use rocket::Request;
#[derive(Serialize, Deserialize)]
struct TransformRequest {
contents: String,
}
#[post("/gostruct/to/flow", format = "json", data = "<data>")]
fn transform_go_struct_to_flow(
data: Json<TransformRequest>,
) -> Result<JsonValue, BadRequest<JsonValue>> {
match js_typify_gostruct::transform(data.contents.to_string()) {
Ok(res) => Ok(json!({ "data": res })),
Err(parse_error) => Err(BadRequest(Some(json!({
"status": "error",
"reason": format!("{:?}", parse_error)
})))),
}
}
#[catch(404)]
fn not_found(req: &Request) -> JsonValue {
json!({
"status": "error",
"reason": format!("Sorry, '{}' is not a valid path.", req.uri())
})
}
fn main() -> Result<(), Error> {
let allowed_origins = AllowedOrigins::All;
let cors = rocket_cors::CorsOptions {
allowed_origins,
allowed_methods: vec![Method::Get, Method::Post, Method::Options]
.into_iter()
.map(From::from)
.collect(),
allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
allow_credentials: true,
..Default::default()
}
.to_cors()?;
rocket::ignite()
.mount("/api/v1", routes![index, transform_go_struct_to_flow])
.register(catchers![not_found])
.manage(cors)
.launch();
Ok(())
}
Am I missing something here
I have configured rocket_cors the following way (following the fairing example):
let cors = CorsOptions {
allowed_origins,
allowed_methods: vec![Method::Get, Method::Post, Method::Delete, Method::Patch]
.into_iter()
.map(From::from)
.collect(),
allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
allow_credentials: true,
..Default::default()
}
.to_cors()
.unwrap();
//...//
rocket.build().attach(cors)
However, when I want to make a PATCH call from my yew.rs webapp using reqwasm I get an OPTION 403. What do I miss here?
Rocket with log = "debug" says:
>> CORS Error: Headers are not allowed
GET /cors/403:
>> Matched: GET /cors/<status>
>> Outcome: Failure
>> No 403 catcher registered. Using Rocket default.
>> Response succeeded.
I am using rocket=0.5.0.rc.1 and the master branch of rocket_cors
https://docs.rs/url/1.6.0/url/enum.Origin.html
Also, the specification allows null
origin, although I'm not sure what value there is in implementing this?
There is a problem compiling on the newest Rust nightly. (rustc 1.33.0-nightly (d22fa2d87 2019-01-08))
Compiling rocket_cors v0.4.0-rc.1 (https://github.com/lawliet89/rocket_cors#9cb16ba0)
error[E0254]: the name `log` is defined multiple times
--> /home/jmack/.cargo/git/checkouts/rocket_cors-5d6823f67bcb0532/9cb16ba/src/lib.rs:591:24
|
553 | extern crate log;
| ----------------- previous import of the extern crate `log` here
...
591 | use log::{error, info, log};
| ^^^ `log` reimported here
|
= note: `log` must be defined only once in the type namespace of this module
help: you can use `as` to change the binding name of the import
|
591 | use log::{error, info, log as other_log};
| ^^^^^^^^^^^^^^^^
error: aborting due to previous error
Hello and first of all thanks for rocket_cors !
I use rocket_cors ver. 0.5.2
.
My rocket application has an auth/signin
route.
Here is my main function :
fn main() {
let cors = rocket_cors::CorsOptions::default().to_cors();
match cors {
Ok(cors) => {
EnvironmentImpl::check();
let mut rocket = rocket::ignite().manage(db::init_pool()).attach(cors);
rocket = auth::mount(rocket);
rocket = health::mount(rocket);
rocket.launch();
},
Err(e) => panic!(e)
}
}
When I call it using a frontend app I am developping, it works as expected in local (front on localhost:8080, back on localhost:8000):
π Rocket has launched from http://localhost:8000
OPTIONS /auth/signin:
=> Error: No matching routes for OPTIONS /auth/signin.
=> Warning: Responding with 404 Not Found catcher.
=> CORS Fairing: Turned missing route OPTIONS /auth/signin into an OPTIONS pre-flight request
=> Response succeeded.
POST /auth/signin application/json:
=> Matched: POST /auth/signin (signin)
=> Outcome: Failure
=> Warning: Responding with 404 Not Found catcher.
=> Response succeeded.
Here 404 on POST in normal because I entered random characters in the fields. OPTIONS response being 204 is great !
But when I push my backend to my vps (in a docker container behind an nginx proxy), the server answers a 404 status code to the OPTIONS request (I tried with the front app located on the vps and with the front app located on localhost:8080) :
2020-03-21T15:09:55.872960036Z Rocket has launched from http://0.0.0.0:8000
2020-03-21T15:10:30.013654968Z Error: No matching routes for OPTIONS /auth/signin.
2020-03-21T15:10:30.014170708Z Warning: Responding with 404 Not Found catcher.
As you can see OPTIONS responds 404 instead of 204 as before...
Note that a POST request sent to the remote server using Postman works.
Here is the url of the front-end app if you want to try and see the request :
https://app-dev.kobumi.com/#/login
AllowedOrigins
: AllOrSome<HashSet<Url>>
AllowedMethods
: HashSet<Method>
AllowedHeaders
: AllOrSome<HashSet<HeaderFieldName>>
Is it a good idea to have the configuration in Rocket.toml instead of a separated file?
I will be happy to make a PR :)
The rocket master contains a fix that allows not setting SameSite on a cookie at all, which I need.
But I also depend on this crate.
But this crate depends on rocket 0.3.3 which depends on a different version of the ring crate than rocket master, which gives linking errors. So it will only work if this crate is updated to also depend on rocket master so both depend on the same version of the ring crate.
When using this crate, I get this error, how to solve this?
rocket::router - GET /cors/<status> and GET /<file..> collide!
I need to have the GET /<file..>
route because I'm serving a PWA with all non-api routes corresponding to files on disk.
Why does the cors crate need to create its own route?
Hello.
When I start it with a simple code like the following and access the request endpoint with axios from the front end (Vue) that is started separately, an error occurs in CORS.
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
extern crate rocket_cors;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
fn main() {
let cors = rocket_cors::CorsOptions::default().to_cors();
rocket::ignite()
.mount("/", routes![index])
.manage(cors)
.launch();
}
If you access it directly from the browser, the response will be returned firmly.
The code for axios is below:
const test = await axios.get('http://localhost:8000/');
The errors displayed on the console are:
Do you know why?
nightly-x86_64-apple-darwin (default)
rustc 1.51.0-nightly (c5eae5629 2021-01-11)
[dependencies]
rocket = "0.4.7"
rocket_cors = "0.5.2"
Gate the following dependencies behind feature gates:
serde
, serde_derive
, url_serde
, and unicase_serde
The issue I am having has been with this File on the fixed Options section (fn owned_options) and Cors_Options Section (fn cors_options).
Error 1:
the trait std::convert::From<rocket::http::Method>
is not implemented for `rocket_cors::Method
Probably related issue #48
Error 2:
the trait std::convert::From<std::vec::Vec<rocket::router::route::Route>>
is not implemented for std::vec::Vec<rocket::Route>
.mount("/", rocket_cors::catch_all_options_routes())
Both errors I believe to be related to each other. I am also using rocket 5.0-rc.1 and the master version of rocket_cors.
I'll continue to update if I find a fix during my lunch.
rocket = {version = "0.5.0-rc.1", default-features = false, features = ["json"]}
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
After pulling my hair out a bit trying to get rocket_cors
working with my existing rocket code, I tried checking out the git repo and running cargo run --example fairing
and got the same results.
No headers are ever added. curl
output for the fairing example nets me:
$ curl -v localhost:8000/
* Hostname was NOT found in DNS cache
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:8000
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=utf-8
* Server Rocket is not blacklisted
< Server: Rocket
< Content-Length: 10
< Date: Fri, 21 Jul 2017 15:00:32 GMT
<
* Connection #0 to host localhost left intact
Hello CORS
I'm running the latest nightly rust available from rustup
:
$ rustup update nightly
info: syncing channel updates for 'nightly-x86_64-unknown-linux-gnu'
nightly-x86_64-unknown-linux-gnu unchanged - rustc 1.20.0-nightly (ae98ebfcb 2017-07-20)
$ rustc --version
rustc 1.20.0-nightly (ae98ebfcb 2017-07-20)
Console output from the running example is:
$ cargo run --example fairing
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/examples/fairing`
π§ Configured for development.
=> address: localhost
=> port: 8000
=> log: normal
=> workers: 16
=> secret key: generated
=> limits: forms = 32KiB
=> tls: disabled
π° Mounting '/':
=> GET /
π° Mounting '/cors':
=> GET /cors/<status>
π‘ Fairings:
=> 0 launch:
=> 1 request: CORS
=> 1 response: CORS
π Rocket has launched from http://localhost:8000
Am I missing something? This is exactly the same thing that happens when I try to integrate it with my existing rocket app (nothing at all).
When the response is Err(Status)
Only in the case of using a Responder
.
Currently, build and test are run against the most recent versions of stable and nightly Rust. When Rocket 0.5 is released, its MSRV should be tested against as well.
Hi,
I'm using your really nice crate and more specifically the fairing implementation you provided : https://github.com/lawliet89/rocket_cors/blob/master/examples/fairing.rs
It works well, except for one small thing : I can't find a way to remove the errors from popping:
Error: No matching routes for OPTIONS /api/list.
Warning: Responding with 404 Not Found catcher.
even when the fairing is triggered and the preflight data sent.
I tried adding .mount("/", rocket_cors::catch_all_options_routes())
, changing the rank level of the route, various configuration and nothing worked.
Did I miss something ? Is there a way to get rid of the messages ?
Thanks in advance.
Rocket stable 0.4 was recently released, I have tested and everything works fine for me so hopefully there's just a version bump needed!
error[E0277]: the trait bound `rocket_cors::Cors: rocket::fairing::Fairing` is not satisfied
--> src/main.rs:316:10
|
316 | .attach(cors)
| ^^^^^^ the trait `rocket::fairing::Fairing` is not implemented for `rocket_cors::Cors`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
fn rocket(cors: Cors) -> rocket::Rocket {
rocket::ignite()
.mount("/", routes![get, post])
.attach(cors)
}
fn main() {
let allowed_origins: AllowedOrigins = AllowedOrigins::all();
let allowed_methods: AllowedMethods = ["Get", "Post", "Delete"]
.iter()
.map(|s| FromStr::from_str(s).unwrap())
.collect();
let allowed_headers: AllowedHeaders = AllowedHeaders::all();
let options = rocket_cors::Cors {
allowed_origins: allowed_origins,
allowed_methods: allowed_methods,
allowed_headers: allowed_headers,
allow_credentials: true,
..Default::default()
};
if options.validate().is_err() {
panic!();
}
rocket(options).launch();
}
[[package]]
name = "rocket_cors"
version = "0.3.0"
source = "git+https://github.com/lawliet89/rocket_cors#f4858e1029d280571eb7f6c2f05fa0967c0f6d5b"
dependencies = [
"log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
"rocket 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.78 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.78 (registry+https://github.com/rust-lang/crates.io-index)",
"unicase 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"unicase_serde 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"url_serde 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
Since PR #81 has been merged, the Rocket dependency is pulled from its GitHub master. When Rocket 0.5 is released, this should be switched back to the corresponding version on crates.io.
Great job with this library. I'd love to eventually get some of this code in Rocket's contrib library, but to do so, it'd need to be licensed under dual MIT/Apache-2.0. Would you consider relicensing this library as such?
cc @talg
When building in a dockerfile on stable
, rustdoc breaks.
The dockerfile, building a basic Rocket 5.0-rc1 app.
FROM ekidd/rust-musl-builder:latest
...
RUN rustup target add x86_64-unknown-linux-musl
...
RUN cargo build --release
The Cargo.toml
contains:
[dependencies]
rocket = "0.5.0-rc.1"
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors.git", branch = "master" }
And the build halts when attempting to build rocket_cors
.
Compiling rocket_cors v0.5.2 (https://github.com/lawliet89/rocket_cors.git?branch=master#a062933c)
error[E0710]: an unknown tool name found in scoped lint: `rustdoc::broken_intra_doc_links`
--> /home/rust/.cargo/git/checkouts/rocket_cors-5d6823f67bcb0532/a062933/src/lib.rs:253:5
|
253 | rustdoc::broken_intra_doc_links
| ^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0710`.
error: could not compile `rocket_cors`
Switching to nightly
in the dockerfile works (as is probably expected) - so this is less an 'issue with things as they stand' as a 'thing that needs to be fixed for Rocket 0.5'. Notably, building outside the dockerfile (on Pop_OS/Ubuntu) works fine on stable. It may be related to this issue.
I'm getting build failures after updating to latest nightly.
fuji@antonovka ~/example/rocket_cors $ rustc --version
rustc 1.32.0-nightly (f1e2fa8f0 2018-11-20)
fuji@antonovka ~/example/rocket_cors $ cargo build
Compiling rocket_cors v0.4.0-rc.1 (/Users/fuji/example/rocket_cors)
error[E0254]: the name `log` is defined multiple times
--> src/lib.rs:591:24
|
553 | extern crate log;
| ----------------- previous import of the extern crate `log` here
...
591 | use log::{error, info, log};
| ^^^ `log` reimported here
|
= note: `log` must be defined only once in the type namespace of this module
help: you can use `as` to change the binding name of the import
|
591 | use log::{error, info, log as other_log};
| ^^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0254`.
error: Could not compile `rocket_cors`.
To learn more, run the command again with --verbose.
--> /home/kvin/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket_cors-0.6.0-alpha1/src/fairing.rs:29:18
|
29 | let _ = &__arg2;
| ^^^^^^ not found in this scope
Hello, i keep getting an error on the rocket_cors crate if i use window os, but using my ubuntu os, the code is still error and when i cargo run, the project is running well.
error[E0659]: `log` is ambiguous (name vs any other name during import resolution)
--> C:\Users\Halobro\.cargo\registry\src\github.com-1ecc6299db9ec823\rocket_cors-0.5.1\src\fairing.rs:3:5
|
3 | use log::{error, info, log};
| ^^^ ambiguous name
|
= note: `log` could refer to a crate passed with `--extern`
= help: use `::log` to refer to this crate unambiguously
note: `log` could also refer to the crate imported here
--> C:\Users\Halobro\.cargo\registry\src\github.com-1ecc6299db9ec823\rocket_cors-0.5.1\src\fairing.rs:3:24
|
3 | use log::{error, info, log};
| ^^^
= help: use `self::log` to refer to this crate unambiguously
error[E0659]: `log` is ambiguous (name vs any other name during import resolution)
--> C:\Users\Halobro\.cargo\registry\src\github.com-1ecc6299db9ec823\rocket_cors-0.5.1\src\lib.rs:284:5
|
284 | use log::{debug, error, info, log};
| ^^^ ambiguous name
|
= note: `log` could refer to a crate passed with `--extern`
= help: use `::log` to refer to this crate unambiguously
note: `log` could also refer to the crate imported here
--> C:\Users\Halobro\.cargo\registry\src\github.com-1ecc6299db9ec823\rocket_cors-0.5.1\src\lib.rs:284:31
|
284 | use log::{debug, error, info, log};
| ^^^
= help: use `crate::log` to refer to this crate unambiguously
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0659`.
error: could not compile `rocket_cors`.
On windows os, these errors prevent the project to run. I am looking for any help, thanks and sorry for my bad english.
rocket_cors = "0.5.1"
Hi!
Where i can find an example where is used Rocket Cors & Headers to prevent access to some API's?
Example:
use rocket_cors::{Guard};
#[get("/sensitive")]
pub fn sensitive(cors: Guard<'_>) -> rocket_cors::Responder<&str> {
// check if Headers api-key == my_secret_key
cors.responder("Sensitive content")
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.