Skip to content

Commit

Permalink
add support for base64 decode/encode to rhai (#2394)
Browse files Browse the repository at this point in the history
- 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`
  • Loading branch information
garypen authored Jan 18, 2023
1 parent 1cad5ad commit 86268ca
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
8 changes: 7 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), [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.
Expand Down Expand Up @@ -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
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

0 comments on commit 86268ca

Please sign in to comment.