From 86268cabb3be8b9db58b4a6865b2d856b4655a6a Mon Sep 17 00:00:00 2001 From: Gary Pennington Date: Wed, 18 Jan 2023 09:57:53 +0000 Subject: [PATCH] add support for base64 decode/encode to rhai (#2394) - Partially Fix #2025 Add support for base64 decode/encode to rhai **Checklist** Complete the checklist (and note appropriate exceptions) before a final PR is raised. - [x] Changes are compatible[^1] - [x] Documentation[^2] completed - [x] Performance impact assessed and acceptable - Tests added and passing[^3] - [x] Unit Tests ~~- [ ] Integration Tests~~ ~~- [ ] Manual Tests~~ **Exceptions** No Exceptions **Notes** [^1]. It may be appropriate to bring upcoming changes to the attention of other (impacted) groups. Please endeavour to do this before seeking PR approval. The mechanism for doing this will vary considerably, so use your judgement as to how and when to do this. [^2]. Configuration is an important part of many changes. Where applicable please try to document configuration examples. [^3]. Tick whichever testing boxes are applicable. If you are adding Manual Tests: - please document the manual testing (extensively) in the Exceptions. - please raise a separate issue to automate the test and label it (or ask for it to be labeled) as `manual test` --- NEXT_CHANGELOG.md | 8 +++++- apollo-router/src/plugins/rhai.rs | 36 +++++++++++++++++++++++++ docs/source/customizations/rhai-api.mdx | 23 ++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index b8b77d8e4d..3454df19eb 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -28,6 +28,13 @@ By [@USERNAME](https://github.com/USERNAME) in https://github.com/apollographql/ # [1.8.1] (unreleased) - 2022-mm-dd ## 🚀 Features + +### Add support for `base64::encode()` / `base64::decode()` in Rhai ([Issue #2025](https://github.com/apollographql/router/issues/2025)) + +Two new functions, `base64::encode()` and `base64::decode()` may now be used to Base64-encode or Base64-decode strings, respectively. + +By [@garypen](https://github.com/garypen) in https://github.com/apollographql/router/pull/2394 + ### Anonymous product usage analytics ([Issue #2124](https://github.com/apollographql/router/issues/2124), [Issue #2397](https://github.com/apollographql/router/issues/2397), [Issue #2412](https://github.com/apollographql/router/issues/2412)) Following up on https://github.com/apollographql/router/pull/1630, the Router transmits anonymous usage telemetry about configurable feature usage which helps guide Router product development. No information is transmitted in our usage collection that includes any request-specific information. Knowing what features and configuration our users are depending on allows us to evaluate opportunity to reduce complexity and remain diligent about the surface area of the Router. The privacy of your and your user's data is of critical importantance to the core Router team and we handle it in accordance with our [privacy policy](https://www.apollographql.com/docs/router/privacy/), which clearly states which data we collect and transmit and offers information on how to opt-out. @@ -144,4 +151,3 @@ To publish a new metric, use tracing macros to generate an event that contains o `histogram.`: Used for histograms (takes f64) By [@bnjjj](https://github.com/bnjjj) in https://github.com/apollographql/router/pull/2417 - diff --git a/apollo-router/src/plugins/rhai.rs b/apollo-router/src/plugins/rhai.rs index 9e81ad6dd9..a3062c9833 100644 --- a/apollo-router/src/plugins/rhai.rs +++ b/apollo-router/src/plugins/rhai.rs @@ -119,6 +119,20 @@ mod subgraph { pub(crate) use crate::services::subgraph::*; } +#[export_module] +mod router_base64_mod { + #[rhai_fn(pure, return_raw)] + pub(crate) fn decode(input: &mut ImmutableString) -> Result> { + String::from_utf8(base64::decode(input.as_bytes()).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string().into()) + } + + #[rhai_fn(pure)] + pub(crate) fn encode(input: &mut ImmutableString) -> String { + base64::encode(input.as_bytes()) + } +} + #[export_module] mod router_plugin_mod { // It would be nice to generate get_originating_headers and @@ -1237,6 +1251,8 @@ impl Rhai { // The macro call creates a Rhai module from the plugin module. let module = exported_module!(router_plugin_mod); + let base64_module = exported_module!(router_base64_mod); + // Configure our engine for execution engine .set_max_expr_depths(0, 0) @@ -1245,6 +1261,8 @@ impl Rhai { }) // Register our plugin module .register_global_module(module.into()) + // Register our base64 module (not global) + .register_static_module("base64", base64_module.into()) // Register types accessible in plugin scripts .register_type::() .register_type::() @@ -2098,6 +2116,24 @@ mod tests { assert_eq!(decoded, "This has an ümlaut in it."); } + #[test] + fn it_can_base64encode_string() { + let engine = Rhai::new_rhai_engine(None); + let encoded: String = engine + .eval(r#"base64::encode("This has an ümlaut in it.")"#) + .expect("can encode string"); + assert_eq!(encoded, "VGhpcyBoYXMgYW4gw7xtbGF1dCBpbiBpdC4="); + } + + #[test] + fn it_can_base64decode_string() { + let engine = Rhai::new_rhai_engine(None); + let decoded: String = engine + .eval(r#"base64::decode("VGhpcyBoYXMgYW4gw7xtbGF1dCBpbiBpdC4=")"#) + .expect("can decode string"); + assert_eq!(decoded, "This has an ümlaut in it."); + } + async fn base_process_function(fn_name: &str) -> Result<(), Box> { let dyn_plugin: Box = crate::plugin::plugins() .find(|factory| factory.name == "apollo.rhai") diff --git a/docs/source/customizations/rhai-api.mdx b/docs/source/customizations/rhai-api.mdx index e2f264e9bf..994db5f634 100644 --- a/docs/source/customizations/rhai-api.mdx +++ b/docs/source/customizations/rhai-api.mdx @@ -165,6 +165,29 @@ fn supergraph_service(service) { } ``` +## base64 encode/decode strings + +Your Rhai customization can use the functions `base64::encode()` and `base64::decode()` to encode/decode strings. `encode()` does not fail, but `decode()` can fail, so always handle exceptions when using the `decode()` function. + +```rhai +fn supergraph_service(service) { + let original = "alice and bob"; + let encoded = base64::encode(original); + // encoded will be "YWxpY2UgYW5kIGJvYgo=" + try { + let and_back = base64::decode(encoded); + // and_back will be "alice and bob" + } + catch(err) + { + // log any errors + log_error(`base64::decode error: ${err}`); + } +} +``` + +Note: You don't need to import the "base64" module. It is imported in the router. + ### Headers with multiple values The simple get/set api for dealing with single value headers is sufficient for most use cases. If you wish to set multiple values on a key then you should do this by supplying an array of values.