Skip to content
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
61 changes: 61 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
name: Rust CI

on: [push, pull_request, workflow_dispatch]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
rust:
name: Rust (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-24.04, macos-15, windows-2025]

steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Set up stable Rust
run: rustup toolchain install stable --profile minimal --component rustfmt --component clippy

- name: Install OpenSSL on Windows
if: runner.os == 'Windows'
shell: pwsh
run: |
"VCPKG_ROOT=$env:VCPKG_INSTALLATION_ROOT" >> $env:GITHUB_ENV
& "$env:VCPKG_INSTALLATION_ROOT\vcpkg.exe" install openssl:x64-windows-static-md

- name: Check formatting and lints
if: runner.os == 'Linux'
run: |
cargo +stable fmt --all -- --check
cargo +stable clippy --all-targets --all-features -- -D warnings

- name: Run offline tests
run: cargo +stable test --all-features

- name: Verify the bundled license example
run: cargo +stable run --example from_str

semgrep:
name: Semgrep
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Scan Rust and GitHub Actions
run: >-
pipx run --spec semgrep==1.187.0 semgrep scan
--config p/rust --config p/github-actions
--severity WARNING --severity ERROR --error
--metrics=off .
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ license-file = "LICENSE.md"
homepage = "https://github.com/cryptolens/cryptolens-rust"
documentation = "https://help.cryptolens.io/"
repository = "https://github.com/cryptolens/cryptolens-rust"
version = "0.0.2"
version = "0.1.0"
authors = ["Cryptolens AB"]
edition = "2024"

Expand All @@ -22,6 +22,8 @@ serde_json = { version = "1" }
thiserror = { version = "2.0" }

[dev-dependencies]
mockito = "1"
serde_urlencoded = { version = "0.7.1" }
tokio = { version = "1", features = ["full"] }
uuid = { version = "1", features = ["v4"] }

170 changes: 103 additions & 67 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,84 +1,120 @@
# Cryptolens Client API for Rust
# Cryptolens for Rust

> This library is currently in a beta release.
Activate license keys from Rust and verify saved licenses offline. You'll need the OpenSSL headers and libraries to build the crate. [OpenSSL setup](https://docs.rs/openssl/latest/openssl/#automatic) · [Devolens API reference](https://app.cryptolens.io/docs/api/v3)

This library simplifies access to the [Cryptolens Web API](https://cryptolens.io) from the
Rust programming language.
## Key verification

Several examples are available in the [`examples/`](examples/) directory of this repository.
Use a token with **Activate** permission and your account's RSA public key (XML). For a node-locked license, set **Maximum Number of Machines** above zero.

## Examples
```rust
use cryptolens::{Error, helpers, methods::Key};

let keys = Key::new(access_token, rsa_public_key_xml)?;
let device = helpers::get_machine_code()?;
let license = keys.activate(product_id, license_key, Some(&device)).await?;

if !license.is_on_right_machine(&device) {
return Err(Error::Custom("Device check failed".into()));
}
```

### Activate a license key
`activate` verifies the signature and product ID, plus the key if the response includes it. Before unlocking a feature, check `license.block`, `license.expires_at()?`, and its feature flag. For unlimited devices, pass `None` and skip the device check.

The [`activate`](examples/activate.rs) example activates a license key with `sign(true)` and verifies the signed response with your Cryptolens public key:
- `keys.get_key(product_id, license_key).await?` reads a signed license without using a slot (**Get Key**). A lookup can return a blocked license.
- `keys.deactivate` releases a device or seat (**Deactivate**). Pass `DeactivationMode::NodeLocked` or `DeactivationMode::Floating`.
- `keys.activate_with_params` accepts a `KeyActivateParams` with options such as a friendly name.

Try `cargo run --example activate -- YOUR_LICENSE_KEY` after setting `CRYPTOLENS_ACCESS_TOKEN`, `CRYPTOLENS_PRODUCT_ID`, and `CRYPTOLENS_PUBLIC_KEY_FILE` (the path to the XML file). [Activation example](examples/activate.rs)

## Offline verification

Save the signed license after activation or lookup. Here the app accepts a saved signature up to seven days old.

```rust
use cryptolens::{Client, KeyActivateParams, RsaKeyValue};

#[tokio::main]
async fn main() {
let client = Client::default();

let params = KeyActivateParams::builder()
.product_id(3646u64)
.key("MPDWY-PQAOW-FKSCH-SGAAU")
.machine_code("289jf2afs3")
.sign(true)
.build()
.unwrap();

let token = "YOUR_ACCESS_TOKEN";
let license_key = client.key_activate(token, params).await.unwrap();

let public_key = r#"<RSAKeyValue><Modulus>...</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"#;
let public_key = RsaKeyValue::from_xml_str(public_key).unwrap();

match license_key.has_valid_signature(public_key) {
Ok(true) => {
println!("Successfully activated license key: {}", license_key.key.unwrap());
}
_ => {
println!("Signature check failed. Aborting!");
}
}
use cryptolens::{Error, LicenseKey};
use std::time::Duration;

let saved = license.save_as_string()?;
let max_age = Duration::from_secs(7 * 24 * 60 * 60);
let cached = LicenseKey::load_from_string(rsa_public_key_xml, &saved, Some(max_age))?;
if cached.product_id != product_id {
return Err(Error::ProductMismatch);
}
```

### Load from string for offline verification
Pass `None` for no age limit. Apply the same access checks you use online. Python and .NET use the same signed format (`SignMethod=1`). Try `cargo run --example from_str` with the bundled license. [Offline example](examples/from_str.rs)

## Customer licenses

An ID lookup spans products, so keep its token on your backend. For customers checking their own licenses, use their secret.

```rust
use cryptolens::methods::Customer;

let by_id = Customer::new(backend_token)
.get_customer_licenses(customer_id, Default::default()).await?;
let by_secret = Customer::new(secret_lookup_token)
.get_customer_licenses_by_secret(customer_secret, Default::default()).await?;
```

Both return unsigned records in `license_keys`. Verify the selected key with `get_key` or `activate`. Set `detailed` for devices and data objects, or `metadata` for activation counts and license status.

## Data objects

The [`from_str`](examples/from_str.rs) example shows how to deserialize a previously saved activation response string and verify it offline:
To charge one credit per export, create a `credits` data object on the license and give the token **Decrement Int Value** permission.

```rust
use cryptolens::{KeyActivateResponse, LicenseKey, RsaKeyValue};

fn main() {
let saved_response = r#"{"licenseKey":"...","signature":"...","result":0,"message":""}"#;

let key_activate_response: KeyActivateResponse =
serde_json::from_str(saved_response).unwrap();
let license_key: LicenseKey = key_activate_response.try_into().unwrap();

let public_key = r#"<RSAKeyValue><Modulus>...</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"#;
let public_key = RsaKeyValue::from_xml_str(public_key).unwrap();

match license_key.has_valid_signature(public_key) {
Ok(true) => {
println!("Successfully loaded license key: {}", license_key.key.unwrap());
}
_ => {
println!("Signature check failed. Aborting!");
}
}
}
use cryptolens::methods::Data;

let data = Data::new(access_token);
data.decrement_int_value_to_key(product_id, license_key, "credits", 1, Some(0)).await?;
```

As long as the library is at version `0.0.X` we are not following semantic versioning. Before
moving to version `0.1.0` at least the following needs to be implemented:
At zero, the server rejects the debit. Add credits with `increment_int_value_to_key`. Both calls accept a name or ID and an optional bound. If a request times out, check whether it took effect before retrying.

Read a saved value with `license.data_object("credits")` or fetch current values with `list_key_data_objects`. Use `DataObjectOwner` for account, product, or license objects on your backend. [All data-object methods](src/methods/data.rs)

## Usage events

Use `Analytics::register_event` with **Register Event** permission. Send the product ID and key to track license usage, or a machine code for a standalone event.

With `CRYPTOLENS_ACCESS_TOKEN` and `CRYPTOLENS_PRODUCT_ID` set, run `cargo run --example register_event -- YOUR_LICENSE_KEY`. To retry an event, pass the same GUID as the second argument on every attempt. [Usage example](examples/register_event.rs)

## Testing with a sample license

Run `cargo test` for the offline suite. GitHub Actions also checks formatting, runs Clippy, and scans the Rust code and workflows with Semgrep. [CI workflow](.github/workflows/ci.yml)

<details>
<summary>Run the live tests against your own sample license</summary>

Use a test customer's node-locked license with a free device slot and floating seat. Its signed response must include the global license ID, customer, and activated machines. Leave the token's product and key locks empty for the standalone event.

| Area | Token permissions |
| --- | --- |
| Keys | Activate, Deactivate, Get Key |
| Customers | Get Customer Licenses, Get Customer Licenses By Secret |
| Data objects | Add Data Object, List Data Objects, Set Int Value, Set String Value, Increment Int Value, Decrement Int Value, Remove Data Object |
| Usage | Register Event, Get Events |

Set the sample values once in PowerShell, then run the full suite in the same window.

```powershell
$env:CRYPTOLENS_ACCESS_TOKEN = [Net.NetworkCredential]::new('', (Read-Host 'Access token' -AsSecureString)).Password
$env:CRYPTOLENS_PRODUCT_ID = Read-Host 'Product ID'
$env:CRYPTOLENS_LICENSE_KEY = [Net.NetworkCredential]::new('', (Read-Host 'License key' -AsSecureString)).Password
$env:CRYPTOLENS_PUBLIC_KEY_FILE = Read-Host 'Path to your RSA public key XML'
$env:CRYPTOLENS_CUSTOMER_SECRET = [Net.NetworkCredential]::new('', (Read-Host 'Customer secret' -AsSecureString)).Password

cargo test -- --include-ignored
```

Each run releases its test device and floating seat, removes its two temporary data objects, and records two labeled events in usage history. [Live tests](tests/live_sample.rs)

</details>

## Existing integrations

- **From 0.0.1** you can keep using blocking `KeyActivate` while pinned to that version. To upgrade, use async `Key::activate`, snake_case fields such as `license.key`, and `LicenseKey::load_from_string` for saved licenses.
- **From Git 0.0.2** you can keep `Client::key_activate`, its builder, and the explicit signature check. `Key::with_client` adds automatic verification to a custom HTTP client. Handle `ActivatedMachine::ip` as `Option<IpAddr>`, `DataObject::int_value` as `i32`, and hidden IDs as `None`. Update exhaustive `Error` matches for verification and machine-code errors.

* [ ] Parse server message when an activation fails, and return an appropriate error.
* [ ] Add proper management of errors in third-party libraries.
* [ ] Decide on how to deal with time, should we depend on e.g. the `chrono` crate?
Or should we just expose the time as an integer and let the user deal with this
as we do now?
* [ ] Possibly change capitalization of names to make them more rust-like
Keep your existing machine code when upgrading. The helper matches Python's `GetMachineCode(v=2)` on Linux, macOS, and Windows, and .NET's `GetMachineCodePI(v: 2)` on Windows.
52 changes: 21 additions & 31 deletions examples/activate.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,25 @@
use cryptolens::{Client, KeyActivateParams, RsaKeyValue};
use cryptolens::{helpers, methods::Key};
use std::{env, error::Error, fs};

#[tokio::main]
async fn main() {
let client = Client::default();

let params = KeyActivateParams::builder()
.product_id(3646u64)
.key("MPDWY-PQAOW-FKSCH-SGAAU")
.machine_code("289jf2afs3")
.sign(true)
.build()
.unwrap();

let token = "WyI0NjUiLCJBWTBGTlQwZm9WV0FyVnZzMEV1Mm9LOHJmRDZ1SjF0Vk52WTU0VzB2Il0=";

let license_key = client.key_activate(token, params).await.unwrap();

let public_key = r#"<RSAKeyValue><Modulus>khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"#;

let public_key = RsaKeyValue::from_xml_str(public_key).unwrap();

match &license_key.has_valid_signature(public_key) {
Ok(true) => {}
_ => {
println!("Signature check failed. Aborting!");
return;
}
async fn main() -> Result<(), Box<dyn Error>> {
let access_token = env::var("CRYPTOLENS_ACCESS_TOKEN")?;
let public_key = fs::read_to_string(env::var("CRYPTOLENS_PUBLIC_KEY_FILE")?)?;
let product_id = env::var("CRYPTOLENS_PRODUCT_ID")?.parse()?;
let license_key = env::args()
.nth(1)
.ok_or("Pass the license key as the first argument")?;

let keys = Key::new(access_token, &public_key)?;
let machine_code = helpers::get_machine_code()?;
let license = keys
.activate(product_id, &license_key, Some(&machine_code))
.await?;

// This example is for node-locked licenses (Maximum Number of Machines > 0).
if !license.is_on_right_machine(&machine_code) {
return Err("The signed license does not include this device".into());
}

println!(
"Successfully activated license key: {}",
license_key.key.unwrap()
);
println!("Activation and signature verification succeeded.");
Ok(())
}
1 change: 1 addition & 0 deletions examples/data/license.skm
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"licenseKey":"eyJQcm9kdWN0SWQiOjM2NDYsIklEIjo0LCJLZXkiOiJNUERXWS1QUUFPVy1GS1NDSC1TR0FBVSIsIkNyZWF0ZWQiOjE0OTAzMTM2MDAsIkV4cGlyZXMiOjI0MDA3NTU1OTUsIlBlcmlvZCI6MTAwMDAsIkYxIjpmYWxzZSwiRjIiOmZhbHNlLCJGMyI6ZmFsc2UsIkY0IjpmYWxzZSwiRjUiOmZhbHNlLCJGNiI6ZmFsc2UsIkY3IjpmYWxzZSwiRjgiOmZhbHNlLCJOb3RlcyI6bnVsbCwiQmxvY2siOmZhbHNlLCJHbG9iYWxJZCI6MzE4NzYsIkN1c3RvbWVyIjpudWxsLCJBY3RpdmF0ZWRNYWNoaW5lcyI6W3siTWlkIjoiMjg5amYyYWZzMyIsIklQIjoiMTU4LjE3NC4xODYuNDgiLCJUaW1lIjoxNjEyOTY2MDc2fSx7Ik1pZCI6InRlc3QxMjMiLCJJUCI6IjE1OC4xNzQuMjMuMjI3IiwiVGltZSI6MTY2MTg0MjExOH1dLCJUcmlhbEFjdGl2YXRpb24iOmZhbHNlLCJNYXhOb09mTWFjaGluZXMiOjIsIkFsbG93ZWRNYWNoaW5lcyI6IiIsIkRhdGFPYmplY3RzIjpbXSwiU2lnbkRhdGUiOjE3NjU0NDU2MzF9","signature":"hX7EZByB0/444Sriiub+3gI2KdULyfqXE7w7rwrn+AiR2bG7WvIhPatpphVpxfRXPEPCgpdNU0IbdHCrHTb8qR312NUoX6k3pDnwgAkaFqNqqY+NVhqw9R9H46056z50vqOMza1g60bWTlCwGCsrmODfu7sRAeymqOHahlLS0spz3Jm7Xlitsk30kkJdG32tM356J4LVG1FS8YYysH1xoQxdf6TldJa9GnxaIa37IarUFnC7t+q81fgI7Wnxa3ySV7u6M0Ec6tFlOVBXJ5vbCTvyR6enDfAC2HPXxbOFYPg8T1zpwsxzy4ho5M3lJuAyf/Z5B65hiop9u1TvQ9dVGA==","result":0,"message":""}
1 change: 1 addition & 0 deletions examples/data/public-key.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<RSAKeyValue><Modulus>khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
29 changes: 8 additions & 21 deletions examples/from_str.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,13 @@
use cryptolens::{KeyActivateResponse, LicenseKey, RsaKeyValue};
use cryptolens::models::LicenseKey;

fn main() {
let key_activate_response: KeyActivateResponse = serde_json::from_str(
r#"{"licenseKey":"eyJQcm9kdWN0SWQiOjM2NDYsIklEIjo0LCJLZXkiOiJNUERXWS1QUUFPVy1GS1NDSC1TR0FBVSIsIkNyZWF0ZWQiOjE0OTAzMTM2MDAsIkV4cGlyZXMiOjI0MDA3NTU1OTUsIlBlcmlvZCI6MTAwMDAsIkYxIjpmYWxzZSwiRjIiOmZhbHNlLCJGMyI6ZmFsc2UsIkY0IjpmYWxzZSwiRjUiOmZhbHNlLCJGNiI6ZmFsc2UsIkY3IjpmYWxzZSwiRjgiOmZhbHNlLCJOb3RlcyI6bnVsbCwiQmxvY2siOmZhbHNlLCJHbG9iYWxJZCI6MzE4NzYsIkN1c3RvbWVyIjpudWxsLCJBY3RpdmF0ZWRNYWNoaW5lcyI6W3siTWlkIjoiMjg5amYyYWZzMyIsIklQIjoiMTU4LjE3NC4xODYuNDgiLCJUaW1lIjoxNjEyOTY2MDc2fSx7Ik1pZCI6InRlc3QxMjMiLCJJUCI6IjE1OC4xNzQuMjMuMjI3IiwiVGltZSI6MTY2MTg0MjExOH1dLCJUcmlhbEFjdGl2YXRpb24iOmZhbHNlLCJNYXhOb09mTWFjaGluZXMiOjIsIkFsbG93ZWRNYWNoaW5lcyI6IiIsIkRhdGFPYmplY3RzIjpbXSwiU2lnbkRhdGUiOjE3NjU0NDU2MzF9","signature":"hX7EZByB0/444Sriiub+3gI2KdULyfqXE7w7rwrn+AiR2bG7WvIhPatpphVpxfRXPEPCgpdNU0IbdHCrHTb8qR312NUoX6k3pDnwgAkaFqNqqY+NVhqw9R9H46056z50vqOMza1g60bWTlCwGCsrmODfu7sRAeymqOHahlLS0spz3Jm7Xlitsk30kkJdG32tM356J4LVG1FS8YYysH1xoQxdf6TldJa9GnxaIa37IarUFnC7t+q81fgI7Wnxa3ySV7u6M0Ec6tFlOVBXJ5vbCTvyR6enDfAC2HPXxbOFYPg8T1zpwsxzy4ho5M3lJuAyf/Z5B65hiop9u1TvQ9dVGA==","result":0,"message":""}"#
).unwrap();

let license_key: LicenseKey = key_activate_response.try_into().unwrap();

let public_key = r#"<RSAKeyValue><Modulus>khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"#;

let public_key = RsaKeyValue::from_xml_str(public_key).unwrap();

match license_key.has_valid_signature(public_key) {
Ok(true) => {}
_ => {
println!("Signature check failed. Aborting!");
return;
}
}
fn main() -> cryptolens::Result<()> {
let public_key = include_str!("data/public-key.xml");
let saved_response = include_str!("data/license.skm");
let license = LicenseKey::load_from_string(public_key, saved_response, None)?;

println!(
"Successfully activated license key: {}",
license_key.key.unwrap()
"Verified the saved license for product {}.",
license.product_id
);
Ok(())
}
25 changes: 25 additions & 0 deletions examples/register_event.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use cryptolens::methods::{Analytics, RegisterEvent};
use std::{env, error::Error};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let analytics = Analytics::new(env::var("CRYPTOLENS_ACCESS_TOKEN")?);
let product_id = env::var("CRYPTOLENS_PRODUCT_ID")?.parse()?;
let mut args = env::args().skip(1);
let license_key = args
.next()
.ok_or("Pass the license key as the first argument")?;
let client_event_id = args.next();

let event = RegisterEvent {
product_id: Some(product_id),
key: Some(&license_key),
feature_name: "YearReportGenerator",
event_name: "start",
client_event_id: client_event_id.as_deref(),
..Default::default()
};
analytics.register_event(&event).await?;
println!("Usage event recorded.");
Ok(())
}
Loading
Loading