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

WIP: Example plugin in Rust #11

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions examples/fitbit-rs/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "wasm32-unknown-unknown"
2 changes: 2 additions & 0 deletions examples/fitbit-rs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
Cargo.lock
15 changes: 15 additions & 0 deletions examples/fitbit-rs/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "fitbit-rs"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["cdylib"]

[dependencies]
anyhow = "1.0.89"
base64 = "0.22.1"
extism-pdk = "1.1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Binary file added examples/fitbit-rs/assets/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions examples/fitbit-rs/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/sh
cargo build --target wasm32-unknown-unknown
11 changes: 11 additions & 0 deletions examples/fitbit-rs/src/host_functions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use extism_pdk::*;

#[host_fn]
extern "ExtismHost" {
pub fn redirect(url: &str);
}

#[host_fn]
extern "ExtismHost" {
pub fn notarize(params: &str) -> String;
}
107 changes: 107 additions & 0 deletions examples/fitbit-rs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
use std::{collections::HashMap, vec};

use base64::{engine::general_purpose, Engine as _};
use config::get;
use extism_pdk::*;

mod types;
use types::{PluginConfig, RequestConfig, RequestObject, StepConfig};
mod host_functions;
use host_functions::{notarize, redirect};
mod utils;
use utils::get_cookies_by_host;

#[plugin_fn]
pub fn config() -> FnResult<Json<PluginConfig<'static>>> {
let icon: String = format!(
"data:image/png;base64,{}",
general_purpose::STANDARD.encode(include_bytes!("../assets/icon.png"))
);

let config = PluginConfig {
title: "Fitbit Profile",
description: "Notarize ownership of a fitbit profile",
steps: vec![
StepConfig {
title: "Open the Fitbit dashboard",
description: Some("Login to your account if you haven't already"),
cta: "Go to fitbit.com",
action: "start",
prover: false,
},
StepConfig {
title: "Notarize fitbit profile",
cta: "Notarize",
action: "two",
prover: true,
description: None,
},
],
host_functions: vec!["redirect", "notarize"],
cookies: vec!["www.fitbit.com"],
headers: vec!["www.fitbit.com"],
requests: vec![RequestObject {
url: "https://web-api.fitbit.com/1/user/*/profile.json",
method: "GET",
}],
notary_urls: None,
proxy_urls: None,
icon,
};
Ok(Json(config))
}

#[plugin_fn]
pub fn start() -> FnResult<Json<bool>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of a bool it would be nicer to have a anyhow::Result<()>. Then you can also add error messages similarly to how you do in utils.rs.

let dashboard_url = "https://www.fitbit.com/dashboard";
let tab_url = get("tabUrl");

let Ok(Some(url)) = tab_url else {
return Ok(Json(false));
};

if url != dashboard_url {
unsafe {
let _ = redirect(dashboard_url);
};
return Ok(Json(false));
}

Ok(Json(true))
}

#[plugin_fn]
pub fn two() -> FnResult<Json<Option<String>>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function never returns an error, but logs it. Is this because of the plugin_fn constraints?

let cookies = get_cookies_by_host("www.fitbit.com")?;
log!(LogLevel::Info, "cookies: {cookies:?}");

let token = cookies
.get("oauth_access_token")
.ok_or_else(|| Error::msg("oauth_access_token not found"))?;
log!(LogLevel::Info, "found token: {token:?}");
let bearer_header = format!("Bearer {}", token);
let headers: HashMap<&str, &str> = [
("authorization", bearer_header.as_str()),
("Accept-Encoding", "identity"),
("Connection", "close"),
]
.into_iter()
.collect();
let secret_headers = vec![bearer_header.as_str()];
let request = RequestConfig {
url: "https://web-api.fitbit.com/1/user/4G7WVQ/profile.json",
method: "GET",
headers,
secret_headers,
};

let request_json = serde_json::to_string(&request)?;
log!(LogLevel::Info, "request: {:?}", &request_json);
let id = unsafe {
let id = notarize(&request_json);
log!(LogLevel::Info, "Notarization result: {:?}", id);
id?
};

return Ok(Json(Some(id)));
}
52 changes: 52 additions & 0 deletions examples/fitbit-rs/src/types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use std::collections::HashMap;

use extism_pdk::*;
use serde::{Deserialize, Serialize};

#[derive(FromBytes, Deserialize, PartialEq, Debug, Serialize, ToBytes)]
#[serde(rename_all = "camelCase")]
#[encoding(Json)]
pub struct PluginConfig<'a> {
th4s marked this conversation as resolved.
Show resolved Hide resolved
pub title: &'a str,
pub description: &'a str,
pub icon: String,
pub steps: Vec<StepConfig<'a>>,
pub host_functions: Vec<&'a str>,
pub cookies: Vec<&'a str>,
pub headers: Vec<&'a str>,
pub requests: Vec<RequestObject<'a>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub notary_urls: Option<Vec<&'a str>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub proxy_urls: Option<Vec<&'a str>>,
}

#[derive(FromBytes, Deserialize, PartialEq, Debug, Serialize, ToBytes)]
#[serde(rename_all = "camelCase")]
#[encoding(Json)]
pub struct StepConfig<'a> {
pub title: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<&'a str>,
pub cta: &'a str,
pub action: &'a str,
pub prover: bool,
}

#[derive(FromBytes, Deserialize, PartialEq, Debug, Serialize, ToBytes)]
#[serde(rename_all = "camelCase")]
#[encoding(Json)]
pub struct RequestObject<'a> {
pub url: &'a str,
pub method: &'a str,
}

#[derive(FromBytes, Deserialize, PartialEq, Debug, Serialize, ToBytes)]
#[serde(rename_all = "camelCase")]
#[encoding(Json)]
pub struct RequestConfig<'a> {
pub url: &'a str,
pub method: &'a str,
pub headers: HashMap<&'a str, &'a str>,
pub secret_headers: Vec<&'a str>,
}
19 changes: 19 additions & 0 deletions examples/fitbit-rs/src/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use std::collections::HashMap;

use anyhow::Context;
use config::get;
use extism_pdk::*;

pub fn get_cookies_by_host(hostname: &str) -> Result<HashMap<String, String>, Error> {
// Get Cookies via Extism
let cookies_json: String = get("cookies")?.context("No cookies found in the configuration.")?;

// Parse the JSON string directly into a HashMap
let cookies: HashMap<String, HashMap<String, String>> = serde_json::from_str(&cookies_json)?;

// Attempt to find the hostname in the map
cookies
.get(hostname)
.cloned()
.context(format!("Cannot find cookies for {}", hostname))
}
9 changes: 9 additions & 0 deletions examples/fitbit-rs/testing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Testing

1. start notary server (**TLS off** for local testing, check version!)
2. Start proxy server:
```
websocat --binary -v ws-l:0.0.0.0:55688 tcp:web-api.fitbit.com:443
```
3. `cargo build --release`
4. Load plugin in browser extension