Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for base64 decode/encode to rhai #2394

Merged
merged 6 commits into from
Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))

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.
Expand Down Expand Up @@ -86,4 +93,4 @@ By [@Geal](https://github.com/geal) in https://github.com/apollographql/router/p

We've changed the plugin to reduce the chances of generating memory allocations when applying regex-based header propagation rules.

By [@o0Ignition0o](https://github.com/o0Ignition0o) in https://github.com/apollographql/router/pull/2389
By [@o0Ignition0o](https://github.com/o0Ignition0o) in https://github.com/apollographql/router/pull/2389
36 changes: 36 additions & 0 deletions apollo-router/src/plugins/rhai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, Box<EvalAltResult>> {
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
Expand Down Expand Up @@ -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)
Expand All @@ -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::<Context>()
.register_type::<HeaderMap>()
Expand Down Expand Up @@ -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<rhai::EvalAltResult>> {
let dyn_plugin: Box<dyn DynPlugin> = crate::plugin::plugins()
.find(|factory| factory.name == "apollo.rhai")
Expand Down
23 changes: 23 additions & 0 deletions docs/source/customizations/rhai-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down