-
Notifications
You must be signed in to change notification settings - Fork 9
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
base: main
Are you sure you want to change the base?
Changes from 6 commits
17f869d
5b692d3
7a279b4
21d34c4
f6ada23
eff1d64
3eef626
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
[build] | ||
target = "wasm32-unknown-unknown" |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
/target | ||
Cargo.lock |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
[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] | ||
base64 = "0.22.1" | ||
extism-pdk = "1.1.0" | ||
serde = { version = "1.0.197", features = ["derive"] } | ||
serde_json = "1.0.125" |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
BSD 3-Clause License | ||
|
||
Copyright (c) 2024, Extism | ||
|
||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions are met: | ||
|
||
1. Redistributions of source code must retain the above copyright notice, this | ||
list of conditions and the following disclaimer. | ||
|
||
2. Redistributions in binary form must reproduce the above copyright notice, | ||
this list of conditions and the following disclaimer in the documentation | ||
and/or other materials provided with the distribution. | ||
|
||
3. Neither the name of the copyright holder nor the names of its | ||
contributors may be used to endorse or promote products derived from | ||
this software without specific prior written permission. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
#!/bin/sh | ||
cargo build --target wasm32-unknown-unknown |
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; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
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>> { | ||
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>>> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
let a = "oauth_access_token"; | ||
match get_cookies_by_host("www.fitbit.com") { | ||
Ok(cookies) => { | ||
log!(LogLevel::Info, "cookies: {cookies:?}"); | ||
match cookies.get(a) { | ||
Some(token) => { | ||
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))); | ||
} | ||
_ => log!(LogLevel::Error, "TODO"), | ||
} | ||
} | ||
Err(err) => log!(LogLevel::Error, "{:?}", err), | ||
} | ||
Ok(Json(None)) | ||
} |
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>, | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
use std::collections::HashMap; | ||
|
||
use config::get; | ||
use extism_pdk::*; | ||
|
||
pub fn get_cookies_by_host(hostname: &str) -> Result<HashMap<String, String>, String> { | ||
let cookies_result = get("cookies"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If the function would return let cookies = get("cookies")?; But even without it we can do let cookies = get("cookies").map_err(|err| err.to_string())?; |
||
|
||
// Check if the cookies were retrieved successfully | ||
let cookies_json = match cookies_result { | ||
Ok(Some(json_str)) => json_str, | ||
Ok(None) => return Err("No cookies found in the configuration.".to_string()), | ||
Err(e) => return Err(format!("Error retrieving cookies: {}", e)), | ||
}; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Then this becomes let cookies = cookies.ok_or_else(|| "No cookies found in the configuration.".to_string())?; |
||
|
||
// Parse the JSON string directly into a HashMap | ||
let cookies: HashMap<String, HashMap<String, String>> = | ||
serde_json::from_str(&cookies_json).map_err(|e| format!("Failed to parse JSON: {}", e))?; | ||
|
||
// Attempt to find the hostname in the map | ||
if let Some(host_cookies) = cookies.get(hostname) { | ||
Ok(host_cookies.clone()) | ||
} else { | ||
Err(format!("Cannot find cookies for {}", hostname)) | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here we can do cookies
.get(hostname)
.cloned()
.ok_or_else(|| format!("Cannot find cookies for {}", hostname)) |
||
} |
There was a problem hiding this comment.
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 aanyhow::Result<()>
. Then you can also add error messages similarly to how you do inutils.rs
.