diff --git a/validation/Cargo.lock b/validation/Cargo.lock index 023df70..78e6721 100644 --- a/validation/Cargo.lock +++ b/validation/Cargo.lock @@ -41,6 +41,16 @@ dependencies = [ "libc", ] +[[package]] +name = "api" +version = "0.1.0" +dependencies = [ + "reqwest", + "serde", + "serde_json", + "url", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -204,6 +214,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + [[package]] name = "chrono" version = "0.4.38" @@ -674,6 +690,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", + "webpki-roots", ] [[package]] @@ -958,6 +975,7 @@ dependencies = [ name = "maps-validation" version = "0.1.0" dependencies = [ + "api", "async-nats", "futures", "rbx_asset", @@ -1245,6 +1263,55 @@ dependencies = [ "syn", ] +[[package]] +name = "quinn" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c5fdde3cdae7203427dc4f0a68fe0ed09833edc525a03456b153b79828684" +dependencies = [ + "bytes", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "quinn-proto" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fadfaed2cd7f389d0161bb73eeb07b7b78f8691047a6f3e73caaeae55310a4a6" +dependencies = [ + "bytes", + "rand", + "ring", + "rustc-hash", + "rustls", + "slab", + "thiserror", + "tinyvec", + "tracing", +] + +[[package]] +name = "quinn-udp" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5a626c6807713b15cac82a6acaccd6043c9a5408c24baae07611fec3f243da" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.52.0", +] + [[package]] name = "quote" version = "1.0.37" @@ -1432,7 +1499,10 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", + "quinn", + "rustls", "rustls-pemfile", + "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", @@ -1440,11 +1510,13 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", + "tokio-rustls", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "webpki-roots", "windows-registry", ] @@ -1491,6 +1563,12 @@ version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" +[[package]] +name = "rustc-hash" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "583034fd73374156e66797ed8e5b0d5690409c9226b22d87cb7f19821c05d152" + [[package]] name = "rustc_version" version = "0.4.1" @@ -1917,6 +1995,21 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "tokio" version = "1.41.1" @@ -2205,6 +2298,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841c67bff177718f1d4dfefde8d8f0e78f9b6589319ba88312f567fc5841a958" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "windows-core" version = "0.52.0" diff --git a/validation/Cargo.toml b/validation/Cargo.toml index d3dc5c9..567fe90 100644 --- a/validation/Cargo.toml +++ b/validation/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] +api = { path = "api" } async-nats = "0.38.0" futures = "0.3.31" rbx_asset = { version = "0.2.3", registry = "strafesnet" } diff --git a/validation/api/Cargo.toml b/validation/api/Cargo.toml new file mode 100644 index 0000000..58e7f58 --- /dev/null +++ b/validation/api/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "api" +version = "0.1.0" +edition = "2021" +publish = ["strafesnet"] +repository = "https://git.itzana.me/StrafesNET/maps-service" +license = "MIT OR Apache-2.0" +description = "Browse and manage map submissions in the staging pipeline." +authors = ["Rhys Lloyd "] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +reqwest = { version = "0", features = ["json","rustls-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +url = "2" diff --git a/validation/api/LICENSE-APACHE b/validation/api/LICENSE-APACHE new file mode 100644 index 0000000..a7e77cb --- /dev/null +++ b/validation/api/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/validation/api/LICENSE-MIT b/validation/api/LICENSE-MIT new file mode 100644 index 0000000..468cd79 --- /dev/null +++ b/validation/api/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/validation/api/src/lib.rs b/validation/api/src/lib.rs new file mode 100644 index 0000000..13548a9 --- /dev/null +++ b/validation/api/src/lib.rs @@ -0,0 +1,96 @@ +#[derive(Debug)] +pub enum GetError{ + ParseError(url::ParseError), + Reqwest(reqwest::Error), + JSON(serde_json::Error), +} +impl std::fmt::Display for GetError{ + fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{ + write!(f,"{self:?}") + } +} +impl std::error::Error for GetError{} + +#[derive(serde::Deserialize)] +pub struct ScriptID(i64); + +#[allow(nonstandard_style)] +pub struct GetScriptRequest{ + pub ScriptID:ScriptID, +} +#[allow(nonstandard_style)] +#[derive(serde::Deserialize)] +pub struct ScriptResponse{ + pub ID:i64, + pub Hash:String, + pub Source:String, + pub SubmissionID:i64, +} + +#[derive(serde::Deserialize)] +#[repr(i32)] +pub enum Policy{ + Allowed=0, + Blocked=1, + Delete=2, + Replace=3, +} + +pub struct ScriptPolicyHashRequest{ + pub hash:String, +} +#[allow(nonstandard_style)] +#[derive(serde::Deserialize)] +pub struct ScriptPolicyResponse{ + pub ID:i64, + pub Hash:String, + pub ScriptID:ScriptID, + pub Policy:Policy +} + +#[derive(Clone)] +pub struct Context{ + base_url:String, + client:reqwest::Client, +} + +pub type ReqwestError=reqwest::Error; + +impl Context{ + pub fn new( + base_url:String, + // cert:reqwest::Certificate, + // identity:reqwest::Identity, + )->reqwest::Result{ + Ok(Self{ + base_url, + client:reqwest::Client::builder() + .use_rustls_tls() + //.tls_built_in_root_certs(false) + //.add_root_certificate(cert) + //.identity(identity) + .https_only(true) + .build()?, + }) + } + async fn get(&self,url:impl reqwest::IntoUrl)->Result{ + self.client.get(url) + .send().await + } + pub async fn get_script(&self,config:GetScriptRequest)->Result{ + let url_raw=format!("{}/scripts/{}",self.base_url,config.ScriptID.0); + let url=reqwest::Url::parse(url_raw.as_str()).map_err(GetError::ParseError)?; + + self.get(url).await.map_err(GetError::Reqwest)? + .error_for_status().map_err(GetError::Reqwest)? + .json().await.map_err(GetError::Reqwest) + } + pub async fn get_script_policy_from_hash(&self,config:ScriptPolicyHashRequest)->Result{ + let url_raw=format!("{}/script-policy/hash/{}",self.base_url,config.hash); + let url=reqwest::Url::parse(url_raw.as_str()).map_err(GetError::ParseError)?; + + self.get(url).await.map_err(GetError::Reqwest)? + .error_for_status().map_err(GetError::Reqwest)? + .json().await.map_err(GetError::Reqwest) + } +} diff --git a/validation/src/main.rs b/validation/src/main.rs index bbff7f3..cc906e6 100644 --- a/validation/src/main.rs +++ b/validation/src/main.rs @@ -5,6 +5,7 @@ mod validator; #[allow(dead_code)] #[derive(Debug)] enum StartupError{ + API(api::ReqwestError), Connect(async_nats::ConnectError), Subscribe(async_nats::SubscribeError), } @@ -20,13 +21,18 @@ async fn main()->Result<(),StartupError>{ // talk to roblox let cookie_context=rbx_asset::cookie::CookieContext::new(rbx_asset::cookie::Cookie::new("".to_owned())); + // maps-service api + let api=api::Context::new("https:://localhost:1234/v1".to_owned()).map_err(StartupError::API)?; + // nats let nasty=async_nats::connect("nats").await.map_err(StartupError::Connect)?; // connect to nats let (publisher,validator)=tokio::try_join!( publisher::Publisher::new(nasty.clone(),cookie_context.clone()), - validator::Validator::new(nasty,cookie_context) + // clone nats here because it's dropped within the function scope, + // meanining the last reference is dropped... + validator::Validator::new(nasty.clone(),cookie_context,api) ).map_err(StartupError::Subscribe)?; // publisher thread diff --git a/validation/src/publisher.rs b/validation/src/publisher.rs index 676a1d4..2f9f5b9 100644 --- a/validation/src/publisher.rs +++ b/validation/src/publisher.rs @@ -11,7 +11,6 @@ impl std::fmt::Display for PublishError{ impl std::error::Error for PublishError{} pub struct Publisher{ - nats:async_nats::Client, subscriber:async_nats::Subscriber, roblox_cookie:rbx_asset::cookie::CookieContext, } @@ -22,7 +21,6 @@ impl Publisher{ )->Result{ Ok(Self{ subscriber:nats.subscribe("publish").await?, - nats, roblox_cookie, }) } diff --git a/validation/src/validator.rs b/validation/src/validator.rs index 7095ac0..4087dc1 100644 --- a/validation/src/validator.rs +++ b/validation/src/validator.rs @@ -11,13 +11,23 @@ enum Valid{ Modified(ModelVersion), } +enum Policy{ + Allowed, + Blocked, + Delete, + Replace(String), +} + #[allow(dead_code)] #[derive(Debug)] enum ValidateError{ + Blocked, + NotAllowed, Get(rbx_asset::cookie::GetError), Json(serde_json::Error), ReadDom(ReadDomError), - ApiGetReplacements(api::GetReplacementsError), + ApiGetScriptPolicy(api::GetError), + ApiGetScript(api::GetError), WriteDom(rbx_binary::EncodeError), Upload(rbx_asset::cookie::UploadError), Create(rbx_asset::cookie::CreateError), @@ -30,20 +40,21 @@ impl std::fmt::Display for ValidateError{ impl std::error::Error for ValidateError{} pub struct Validator{ - nats:async_nats::Client, subscriber:async_nats::Subscriber, roblox_cookie:rbx_asset::cookie::CookieContext, + api:api::Context, } impl Validator{ pub async fn new( nats:async_nats::Client, roblox_cookie:rbx_asset::cookie::CookieContext, + api:api::Context, )->Result{ Ok(Self{ subscriber:nats.subscribe("validate").await?, - nats, roblox_cookie, + api, }) } pub async fn run(mut self){ @@ -80,41 +91,60 @@ impl Validator{ // collect unique scripts let script_refs=get_script_refs(&dom); - let mut script_map=std::collections::HashMap::>::new(); + let mut script_map=std::collections::HashMap::::new(); for &script_ref in &script_refs{ if let Some(script)=dom.get_by_ref(script_ref){ if let Some(rbx_dom_weak::types::Variant::String(source))=script.properties.get("Source"){ - script_map.insert(source.clone(),None); + script_map.insert(source.clone(),Policy::Blocked); } } } - // ["local a=true","local b=true"] - let script_list:Vec<&str>=script_map.keys().map(|s|s.as_str()).collect(); - let j=serde_json::to_string(&script_list).map_err(ValidateError::Json)?; - // send all scripts to REST endpoint and receive the replacements - let replacements=self.api.get_replacements(j).await.map_err(ValidateError::ApiGetReplacements)?; - - // assume the iteration order will not change if no keys are inserted or removed - for (map_value,replacement) in script_map.values_mut().zip(replacements){ - *map_value=replacement; + for (source,replacement) in &mut script_map{ + let mut hasher=std::hash::SipHasher::new(); + std::hash::Hash::hash(&source,&mut hasher); + let hash=std::hash::Hasher::finish(&hasher); + let script_policy=self.api.get_script_policy_from_hash(api::ScriptPolicyHashRequest{ + hash:format!("{:x}",hash), + }).await.map_err(ValidateError::ApiGetScriptPolicy)?; + *replacement=match script_policy.Policy{ + api::Policy::Allowed=>Policy::Allowed, + api::Policy::Blocked=>Policy::Blocked, + api::Policy::Delete=>Policy::Delete, + api::Policy::Replace=>{ + let script=self.api.get_script(api::GetScriptRequest{ + ScriptID:script_policy.ScriptID, + }).await.map_err(ValidateError::ApiGetScript)?; + Policy::Replace(script.Source) + }, + }; } // make the replacements - let mut any_replaced=false; + let mut modified=false; for &script_ref in &script_refs{ if let Some(script)=dom.get_by_ref_mut(script_ref){ if let Some(rbx_dom_weak::types::Variant::String(source))=script.properties.get_mut("Source"){ - if let Some(Some(replacement))=script_map.get(source.as_str()){ - any_replaced=true; - *source=replacement.clone(); + match script_map.get(source.as_str()){ + Some(Policy::Blocked)=>return Err(ValidateError::Blocked), + None=>return Err(ValidateError::NotAllowed), + Some(Policy::Allowed)=>(), + Some(Policy::Delete)=>{ + modified=true; + // delete script + unimplemented!(); + }, + Some(Policy::Replace(replacement))=>{ + modified=true; + *source=replacement.clone(); + }, } } } } // reply with validity - Ok(if any_replaced{ + Ok(if modified{ // serialize model (slow!) let mut data=Vec::new(); rbx_binary::to_writer(&mut data,&dom,&[dom.root_ref()]).map_err(ValidateError::WriteDom)?; @@ -137,7 +167,7 @@ impl Validator{ }else{ // create new model let response=self.roblox_cookie.create(rbx_asset::cookie::CreateRequest{ - name:dom.root().name, + name:dom.root().name.clone(), description:"".to_owned(), ispublic:true, allowComments:true, @@ -160,6 +190,10 @@ impl Validator{ } } +fn get_model_version_number()->u64{ + unimplemented!() +} + #[allow(dead_code)] #[derive(Debug)] enum ReadDomError{