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

[PAYG-723] Adds rust tl-signature example #54

Merged
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: 1 addition & 1 deletion rust/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
/target
**/target
Cargo.lock
2 changes: 2 additions & 0 deletions rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ let tl_signature = truelayer_signing::sign_with_pem(kid, private_key)
.sign()?;
```

See [full example](./examples/sign-request/).

## Prerequisites
- OpenSSL (see [here](https://www.openssl.org/) for instructions).

Expand Down
12 changes: 12 additions & 0 deletions rust/examples/sign-request/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "sign-request"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
rand = "0.8.4"
reqwest = "0.11"
tokio = { version = "1.17", features = ["full"] }
truelayer-signing = "0.1.3"
uuid = { version = "0.8", features = ["v4"] }
14 changes: 14 additions & 0 deletions rust/examples/sign-request/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# rust request signature example
Sends a signed request to `https://api.truelayer-sandbox.com/test-signature`.

## Run

Set environment variables:
* `ACCESS_TOKEN` A valid JWT access token for `payments` scope [docs](https://docs.truelayer.com/docs/retrieve-a-token-in-your-server).
* `KID` The certificate/key UUID for associated with your public key uploaded to console.truelayer.com.
* `PRIVATE_KEY` Private key PEM string that matches the `KID` & uploaded public key.
Should have the same format as [this example private key](https://github.com/TrueLayer/truelayer-signing/blob/main/test-resources/ec512-private.pem).

```sh
$ cargo run
```
55 changes: 55 additions & 0 deletions rust/examples/sign-request/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use rand;
use std::env;
use uuid::Uuid;

// the base url to use
const TL_BASE_URL: &str = "https://api.truelayer-sandbox.com";

#[tokio::main]
async fn main() {
// Read required env vars
let kid = env::var("KID").expect("Missing env var KID");
let access_token = env::var("ACCESS_TOKEN").expect("Missing env var ACCESS_TOKEN");
let private_key = env::var("PRIVATE_KEY").expect("Missing env var PRIVATE_KEY");

// A random body string is enough for this request as `/test-signature` endpoint does not
// require any schema, it simply checks the signature is valid against what's received.
let body = format!("body-{}", rand::random::<u32>());

let idempotency_key = Uuid::new_v4().to_string();

// Generate tl-signature
let tl_signature = truelayer_signing::sign_with_pem(kid.as_str(), private_key.as_bytes())
.method("POST") // as we're sending a POST request
.path("/test-signature") // the path of our request
// Optional: /test-signature does not require any headers, but we may sign some anyway.
// All signed headers *must* be included unmodified in the request.
.header("Idempotency-Key", idempotency_key.as_bytes())
.header("X-Bar-Header", b"abc123")
.body(body.as_bytes()) // body of our request
.sign()
.unwrap();

let client = reqwest::Client::new();
// Request body & any signed headers *must* exactly match what was used to generate the signature.
let response = client
.post(format!("{}/test-signature", TL_BASE_URL))
.header("Authorization", format!("Bearer {access_token}"))
.header("Idempotency-Key", idempotency_key)
.header("X-Bar-Header", "abc123")
.header("Tl-Signature", tl_signature)
.body(body)
.send()
.await
.unwrap();

let status = response.status();
let response_body = match status.is_success() {
true => String::from("✓"),
false => response.text().await.unwrap(),
};

// 204 means success
// 401 means either the access token is invalid, or the signature is invalid.
println!("{} {}", status.as_u16(), response_body);
}