diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..582fb90
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -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 .
diff --git a/Cargo.toml b/Cargo.toml
index 46280a2..11ee158 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -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"
@@ -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"] }
diff --git a/README.md b/README.md
index 7af7d1b..6b30e7a 100644
--- a/README.md
+++ b/README.md
@@ -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#"...AQAB"#;
- 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#"...AQAB"#;
- 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)
+
+
+Run the live tests against your own sample license
+
+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)
+
+
+
+## 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`, `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.
diff --git a/examples/activate.rs b/examples/activate.rs
index 44412fc..1d0297d 100644
--- a/examples/activate.rs
+++ b/examples/activate.rs
@@ -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#"khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw==AQAB"#;
-
- 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> {
+ 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(())
}
diff --git a/examples/data/license.skm b/examples/data/license.skm
new file mode 100644
index 0000000..c768414
--- /dev/null
+++ b/examples/data/license.skm
@@ -0,0 +1 @@
+{"licenseKey":"eyJQcm9kdWN0SWQiOjM2NDYsIklEIjo0LCJLZXkiOiJNUERXWS1QUUFPVy1GS1NDSC1TR0FBVSIsIkNyZWF0ZWQiOjE0OTAzMTM2MDAsIkV4cGlyZXMiOjI0MDA3NTU1OTUsIlBlcmlvZCI6MTAwMDAsIkYxIjpmYWxzZSwiRjIiOmZhbHNlLCJGMyI6ZmFsc2UsIkY0IjpmYWxzZSwiRjUiOmZhbHNlLCJGNiI6ZmFsc2UsIkY3IjpmYWxzZSwiRjgiOmZhbHNlLCJOb3RlcyI6bnVsbCwiQmxvY2siOmZhbHNlLCJHbG9iYWxJZCI6MzE4NzYsIkN1c3RvbWVyIjpudWxsLCJBY3RpdmF0ZWRNYWNoaW5lcyI6W3siTWlkIjoiMjg5amYyYWZzMyIsIklQIjoiMTU4LjE3NC4xODYuNDgiLCJUaW1lIjoxNjEyOTY2MDc2fSx7Ik1pZCI6InRlc3QxMjMiLCJJUCI6IjE1OC4xNzQuMjMuMjI3IiwiVGltZSI6MTY2MTg0MjExOH1dLCJUcmlhbEFjdGl2YXRpb24iOmZhbHNlLCJNYXhOb09mTWFjaGluZXMiOjIsIkFsbG93ZWRNYWNoaW5lcyI6IiIsIkRhdGFPYmplY3RzIjpbXSwiU2lnbkRhdGUiOjE3NjU0NDU2MzF9","signature":"hX7EZByB0/444Sriiub+3gI2KdULyfqXE7w7rwrn+AiR2bG7WvIhPatpphVpxfRXPEPCgpdNU0IbdHCrHTb8qR312NUoX6k3pDnwgAkaFqNqqY+NVhqw9R9H46056z50vqOMza1g60bWTlCwGCsrmODfu7sRAeymqOHahlLS0spz3Jm7Xlitsk30kkJdG32tM356J4LVG1FS8YYysH1xoQxdf6TldJa9GnxaIa37IarUFnC7t+q81fgI7Wnxa3ySV7u6M0Ec6tFlOVBXJ5vbCTvyR6enDfAC2HPXxbOFYPg8T1zpwsxzy4ho5M3lJuAyf/Z5B65hiop9u1TvQ9dVGA==","result":0,"message":""}
diff --git a/examples/data/public-key.xml b/examples/data/public-key.xml
new file mode 100644
index 0000000..9a50666
--- /dev/null
+++ b/examples/data/public-key.xml
@@ -0,0 +1 @@
+khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw==AQAB
diff --git a/examples/from_str.rs b/examples/from_str.rs
index 67713bb..26c9f4e 100644
--- a/examples/from_str.rs
+++ b/examples/from_str.rs
@@ -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#"khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw==AQAB"#;
-
- 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(())
}
diff --git a/examples/register_event.rs b/examples/register_event.rs
new file mode 100644
index 0000000..b288dca
--- /dev/null
+++ b/examples/register_event.rs
@@ -0,0 +1,25 @@
+use cryptolens::methods::{Analytics, RegisterEvent};
+use std::{env, error::Error};
+
+#[tokio::main]
+async fn main() -> Result<(), Box> {
+ 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(())
+}
diff --git a/src/client/key.rs b/src/client/key.rs
deleted file mode 100644
index 06f8a67..0000000
--- a/src/client/key.rs
+++ /dev/null
@@ -1,348 +0,0 @@
-use std::net::IpAddr;
-
-use base64::{Engine, engine::general_purpose::STANDARD};
-use derive_builder::Builder;
-use serde::{Deserialize, Serialize};
-
-use crate::{Error, Timestamp, client::TokenizedParams};
-
-use super::{Client, Result};
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct LicenseKey {
- #[serde(alias = "ProductId")]
- pub product_id: u64,
- #[serde(alias = "Id")]
- pub id: Option,
- #[serde(alias = "Key")]
- pub key: Option,
- #[serde(alias = "Created")]
- pub created: Timestamp,
- #[serde(alias = "Expires")]
- pub expires: Timestamp,
- #[serde(alias = "Period")]
- pub period: u64,
- #[serde(alias = "F1", alias = "f1")]
- pub feature1: bool,
- #[serde(alias = "F2", alias = "f2")]
- pub feature2: bool,
- #[serde(alias = "F3", alias = "f3")]
- pub feature3: bool,
- #[serde(alias = "F4", alias = "f4")]
- pub feature4: bool,
- #[serde(alias = "F5", alias = "f5")]
- pub feature5: bool,
- #[serde(alias = "F6", alias = "f6")]
- pub feature6: bool,
- #[serde(alias = "F7", alias = "f7")]
- pub feature7: bool,
- #[serde(alias = "F8", alias = "f8")]
- pub feature8: bool,
- #[serde(alias = "Notes")]
- pub notes: Option,
- #[serde(alias = "Block")]
- pub block: bool,
- #[serde(alias = "GlobalId")]
- pub global_id: Option,
- #[serde(alias = "Customer")]
- pub customer: Option,
- #[serde(alias = "ActivatedMachines")]
- pub activated_machines: Vec,
- #[serde(alias = "TrialActivation")]
- pub trial_activation: bool,
- #[serde(alias = "MaxNoOfMachines")]
- pub max_no_of_machines: Option,
- #[serde(alias = "AllowedMachines")]
- pub allowed_machines: Option,
- #[serde(alias = "DataObjects")]
- pub data_objects: Vec,
- #[serde(alias = "SignDate")]
- pub sign_date: Timestamp,
- #[serde(alias = "Signature")]
- pub signature: Option,
-
- #[serde(skip, default)]
- license_key_bytes: Vec,
- #[serde(skip, default)]
- signature_bytes: Vec,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ActivatedMachine {
- #[serde(alias = "Mid")]
- pub mid: String,
- #[serde(alias = "IP")]
- pub ip: IpAddr,
- #[serde(alias = "Time")]
- pub time: Timestamp,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Customer {
- #[serde(alias = "Id")]
- pub id: u64,
- #[serde(alias = "Name")]
- pub name: String,
- #[serde(alias = "Email")]
- pub email: String,
- #[serde(alias = "CompanyName")]
- pub company_name: String,
- #[serde(alias = "Created")]
- pub created: Timestamp,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DataObject {
- #[serde(alias = "Id")]
- pub id: u64,
- #[serde(alias = "Name")]
- pub name: String,
- #[serde(alias = "StringValue")]
- pub string_value: String,
- #[serde(alias = "IntValue")]
- pub int_value: u32,
-}
-
-pub type IntervalInSecs = u64;
-
-#[derive(Debug, Clone, Serialize, Builder)]
-#[serde(rename_all = "PascalCase")]
-#[builder(build_fn(error = "Error"))]
-pub struct KeyActivateParams {
- #[builder(setter(into))]
- pub product_id: u64,
- #[builder(setter(into))]
- pub key: String,
- #[builder(setter(into, strip_option), default)]
- pub sign: Option,
- #[builder(setter(into, strip_option), default)]
- pub machine_code: Option,
- #[builder(setter(into, strip_option), default)]
- pub friendly_name: Option,
- #[builder(setter(into, strip_option), default)]
- pub fields_to_return: Option,
- #[builder(setter(skip), default = 1)]
- sign_method: u64,
- #[builder(setter(into, strip_option), default)]
- pub metadata: Option,
- #[builder(setter(into, strip_option), default)]
- pub floating_time_interval: Option,
- #[builder(setter(into, strip_option), default)]
- pub max_overdraft: Option,
- #[builder(setter(into, strip_option), default)]
- #[serde(rename = "OSInfo")]
- pub os_info: Option,
- #[builder(setter(into, strip_option), default)]
- pub model_version: Option,
- #[serde(rename = "v")]
- #[builder(setter(into, strip_option), default)]
- pub method_version: Option,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "PascalCase")]
-pub struct RsaKeyValue {
- pub modulus: String,
- pub exponent: String,
-}
-
-pub type PublicKey = openssl::pkey::PKey;
-
-impl Client {
- pub async fn key_activate(
- &self,
- token: impl AsRef,
- params: KeyActivateParams,
- ) -> Result {
- let params = TokenizedParams {
- token: token.as_ref(),
- params,
- };
- let res: KeyActivateResponse = self
- .client
- .post("https://app.cryptolens.io/api/key/Activate")
- .form(¶ms)
- .send()
- .await?
- .json()
- .await?;
-
- res.try_into()
- }
-}
-
-impl LicenseKey {
- pub fn has_valid_signature(
- &self,
- public_key: impl TryInto,
- ) -> Result {
- let public_key: PublicKey = public_key.try_into()?;
-
- let mut verifier =
- openssl::sign::Verifier::new(openssl::hash::MessageDigest::sha256(), &public_key)?;
-
- verifier.update(&self.license_key_bytes)?;
- Ok(verifier.verify(&self.signature_bytes)?)
- }
-}
-
-impl TryFrom for LicenseKey {
- type Error = Error;
-
- fn try_from(value: KeyActivateResponse) -> Result {
- if value.result == 1 {
- return Err(Error::Api(value.message));
- };
- Ok(
- match value.license_key.ok_or_else(|| {
- Error::Custom("licenseKey field is required for success result".to_string())
- })? {
- LicenseKeyResponse::Json(license_key) => license_key,
- LicenseKeyResponse::Base64(encoded) => {
- let license_key_bytes = STANDARD.decode(encoded)?;
- let mut license_key: LicenseKey = serde_json::from_slice(&license_key_bytes)?;
- license_key.license_key_bytes = license_key_bytes;
- license_key.signature_bytes =
- STANDARD.decode(value.signature.unwrap_or_default())?;
- license_key
- }
- },
- )
- }
-}
-
-impl RsaKeyValue {
- pub fn from_xml_str(input: &str) -> Result {
- Ok(serde_xml_rs::from_str(input)?)
- }
-}
-
-impl TryFrom for PublicKey {
- type Error = Error;
-
- fn try_from(value: RsaKeyValue) -> std::result::Result {
- let modulus_decoded = STANDARD.decode(&value.modulus)?;
- let exponent_decoded = STANDARD.decode(&value.exponent)?;
-
- let modulus = openssl::bn::BigNum::from_slice(&modulus_decoded)?;
- let exponent = openssl::bn::BigNum::from_slice(&exponent_decoded)?;
-
- let keypair = openssl::rsa::Rsa::from_public_components(modulus, exponent)?;
- Ok(openssl::pkey::PKey::from_rsa(keypair)?)
- }
-}
-
-impl KeyActivateParams {
- pub fn builder() -> KeyActivateParamsBuilder {
- KeyActivateParamsBuilder::default()
- }
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct KeyActivateResponse {
- license_key: Option,
- signature: Option,
- result: u8,
- message: String,
-}
-
-#[allow(clippy::large_enum_variant)]
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase", untagged)]
-enum LicenseKeyResponse {
- Json(LicenseKey),
- Base64(String),
-}
-
-#[cfg(test)]
-mod tests {
-
- use super::*;
-
- #[test]
- fn test_deser_if_sign_method_one() {
- // given
- let input = r#"{"licenseKey":"eyJQcm9kdWN0SWQiOjMsIklEIjo2LCJLZXkiOiJHT1hHWi1WQUNLRS1TUUJZRS1CUlhVUCIsIkNyZWF0ZWQiOiIyMDE0LTAxLTAyVDAwOjAwOjAwIiwiRXhwaXJlcyI6IjIwMTQtMDItMTZUMDA6MDA6MDAiLCJQZXJpb2QiOjQ1LCJGMSI6dHJ1ZSwiRjIiOnRydWUsIkYzIjpmYWxzZSwiRjQiOmZhbHNlLCJGNSI6ZmFsc2UsIkY2IjpmYWxzZSwiRjciOmZhbHNlLCJGOCI6ZmFsc2UsIk5vdGVzIjoidG8gU2NvdCIsIkJsb2NrIjpmYWxzZSwiR2xvYmFsSWQiOjEwMDksIkN1c3RvbWVyIjp7IklkIjoyNywiTmFtZSI6ImN1c3RvbWVyIiwiRW1haWwiOiJhcnRlbUBhcnRlbWxvcy5uZXQiLCJDb21wYW55TmFtZSI6InRlc3QiLCJDcmVhdGVkIjoiMjAxNi0wMS0wNFQxOTo0OTowOS4zMDcifSwiQWN0aXZhdGVkTWFjaGluZXMiOltdLCJUcmlhbEFjdGl2YXRpb24iOmZhbHNlLCJNYXhOb09mTWFjaGluZXMiOi0xLCJBbGxvd2VkTWFjaGluZXMiOm51bGwsIkRhdGFPYmplY3RzIjpbXSwiU2lnbkRhdGUiOiIyMDE3LTA0LTE0VDE0OjE1OjM4IiwiU2lnbmF0dXJlIjpudWxsfQ==","signature":"fVhV2revZTug1HtYcLkSEEMCPk0AkaBWBl4cRYOXlOpHR5S7xNtcY9o+wXRuauNXzGXh5LQcT8Ybo1HJ1LFp3z7sEfoDZZHfckbKbeSOTi+ercuqH26nWdvD2wgKsJsU0Rx6iClyKezNS36azriubdxcVabClFawn65GHexw14AeQlGU1jreAs0N57Dw/jwuBPXGfId64V8daOozVJQFhJVA6B1ZSu01FfxuBQxn2kj+UhjRGMp79JasCu2h1V5End66IHf0jlbgfsRDlWGfik1oK1LhFfkVV9rURSWiINhh1rZn1NM4ELHr/ASXUj1P1PdrtPadobDO+eXDUZhBHQ==","result":0,"message":""}"#;
-
- // when
- let parsed = serde_json::from_str::(input);
-
- // then
- assert!(parsed.is_ok());
- }
-
- #[test]
- fn test_deser_error() {
- // given
- let input = r#"{"result":1,"message":"Unable to authenticate."}"#;
-
- // when
- let parsed: Result = serde_json::from_str::(input)
- .unwrap()
- .try_into();
-
- // then
- assert!(
- matches!(parsed, Err(Error::Api(message)) if message.eq("Unable to authenticate."))
- );
- }
-
- #[test]
- fn test_key_activate_params_ser_minimal() {
- // given
- let params = KeyActivateParams::builder()
- .product_id(1u64)
- .key("key")
- .build()
- .unwrap();
-
- let params = TokenizedParams {
- token: "TOKEN",
- params,
- };
-
- // when
- let url = serde_urlencoded::to_string(¶ms);
-
- // then
- assert_eq!(
- url,
- Ok("token=TOKEN&ProductId=1&Key=key&SignMethod=1".to_string())
- );
- }
-
- #[test]
- fn test_key_activate_params_ser() {
- // given
- let params = KeyActivateParams::builder()
- .product_id(1u64)
- .key("key")
- .sign(true)
- .max_overdraft(4u64)
- .machine_code("code")
- .build()
- .unwrap();
-
- let params = TokenizedParams {
- token: "TOKEN",
- params,
- };
-
- // when
- let url = serde_urlencoded::to_string(¶ms);
-
- // then
- assert_eq!(
- url,
- Ok(
- "token=TOKEN&ProductId=1&Key=key&Sign=true&MachineCode=code&SignMethod=1&MaxOverdraft=4"
- .to_string()
- )
- );
- }
-}
diff --git a/src/client/mod.rs b/src/client/mod.rs
index 1c1ec41..8469113 100644
--- a/src/client/mod.rs
+++ b/src/client/mod.rs
@@ -1,24 +1,90 @@
-use serde::Serialize;
+use serde::{Deserialize, Serialize, de::DeserializeOwned};
-use crate::Error;
+use crate::models::LicenseResponse;
+use crate::{Error, KeyActivateParams, LicenseKey};
pub type Result = std::result::Result;
pub type Timestamp = u64;
-mod key;
+const WEB_API: &str = "https://api.cryptolens.io/api";
-pub use key::*;
-
-#[derive(Debug, Default)]
+#[derive(Clone, Debug)]
pub struct Client {
client: reqwest::Client,
+ api_url: String,
+}
+
+impl Default for Client {
+ fn default() -> Self {
+ Self {
+ client: reqwest::Client::default(),
+ api_url: WEB_API.into(),
+ }
+ }
}
impl Client {
pub fn new() -> Self {
Self::default()
}
+
+ /// Performs an activation with the caller's signing options. For automatic signature
+ /// verification use [`Key::activate`](crate::methods::Key::activate).
+ pub async fn key_activate(
+ &self,
+ token: impl AsRef,
+ params: KeyActivateParams,
+ ) -> Result {
+ self.post::("key/Activate", token.as_ref(), ¶ms)
+ .await?
+ .into_license(None)
+ }
+
+ pub(crate) async fn post(
+ &self,
+ method: &str,
+ access_token: &str,
+ params: &impl Serialize,
+ ) -> Result {
+ let form = TokenizedParams {
+ token: access_token,
+ params,
+ };
+ let response = self
+ .client
+ .post(format!("{}/{method}", self.api_url))
+ .form(&form)
+ .send()
+ .await?;
+ // Error responses can contain a useful message without any success fields.
+ if let Err(http_error) = response.error_for_status_ref() {
+ if let Ok(rejection) = response.json::>().await {
+ rejection.into_result()?;
+ }
+ return Err(http_error.into());
+ }
+ response.json::>().await?.into_result()
+ }
+
+ pub(crate) async fn action(
+ &self,
+ method: &str,
+ access_token: &str,
+ params: &impl Serialize,
+ ) -> Result<()> {
+ self.post::(method, access_token, params)
+ .await?;
+ Ok(())
+ }
+
+ #[cfg(test)]
+ pub(crate) fn local_server(api_url: String) -> Self {
+ Self {
+ api_url,
+ ..Self::default()
+ }
+ }
}
impl TryFrom for Client {
@@ -26,13 +92,38 @@ impl TryFrom for Client {
fn try_from(builder: reqwest::ClientBuilder) -> Result {
let client = builder.build()?;
- Ok(Self { client })
+ Ok(Self {
+ client,
+ api_url: WEB_API.into(),
+ })
}
}
+#[derive(Debug, Deserialize)]
+pub(crate) struct ApiResponse {
+ #[serde(alias = "Result")]
+ result: u8,
+ #[serde(alias = "Message")]
+ message: Option,
+ #[serde(flatten)]
+ data: T,
+}
+
+impl ApiResponse {
+ pub(crate) fn into_result(self) -> Result {
+ match self.result {
+ 0 => Ok(self.data),
+ _ => Err(Error::Api(self.message.unwrap_or_default())),
+ }
+ }
+}
+
+#[derive(Deserialize)]
+pub(crate) struct EmptyResponse {}
+
#[derive(Serialize)]
-struct TokenizedParams<'a, T: Serialize> {
- token: &'a str,
+pub(crate) struct TokenizedParams<'a, T: Serialize> {
+ pub(crate) token: &'a str,
#[serde(flatten)]
- params: T,
+ pub(crate) params: T,
}
diff --git a/src/error.rs b/src/error.rs
index 7d3bc73..9bec6f4 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -11,6 +11,24 @@ pub enum Error {
#[error("api error: {0}")]
Api(String),
+ #[error("the response does not contain a signed license")]
+ MissingSignature,
+
+ #[error("the license signature is invalid")]
+ InvalidSignature,
+
+ #[error("the signed license belongs to a different product")]
+ ProductMismatch,
+
+ #[error("the signed license key does not match the requested key")]
+ LicenseKeyMismatch,
+
+ #[error("the signature is outside the allowed offline time window")]
+ SignatureAge,
+
+ #[error("a machine code could not be obtained on this device")]
+ MachineCodeUnavailable,
+
#[error("base64 decoding error: {0}")]
Decode(#[from] base64::DecodeError),
diff --git a/src/helpers.rs b/src/helpers.rs
new file mode 100644
index 0000000..e00fe1d
--- /dev/null
+++ b/src/helpers.rs
@@ -0,0 +1,101 @@
+//! Device identifiers for node-locked licenses.
+
+use crate::{Error, Result};
+
+/// Computes the machine code used by the Python SDK's `GetMachineCode(v=2)`.
+/// On Windows this also matches .NET's `GetMachineCodePI(v: 2)`. On Linux and
+/// macOS the .NET SDK uses different inputs. Keep an existing application's
+/// machine-code source when migrating its registered devices.
+pub fn get_machine_code() -> Result {
+ let seed = machine_seed()
+ .filter(|s| !s.is_empty())
+ .ok_or(Error::MachineCodeUnavailable)?;
+ Ok(openssl::sha::sha256(seed.as_bytes())
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect())
+}
+
+#[cfg(target_os = "linux")]
+fn machine_seed() -> Option {
+ use std::fs;
+ use std::os::unix::fs::MetadataExt;
+
+ let mut seed = ["/etc/machine-id", "/var/lib/dbus/machine-id"]
+ .iter()
+ .find_map(|path| fs::read_to_string(path).ok())
+ .unwrap_or_default()
+ .trim()
+ .to_owned();
+ // Use the same directory order and follow symlinks just like Python's os.stat.
+ for path in ["/bin", "/etc", "/lib", "/root", "/sbin", "/usr", "/var"] {
+ if let Ok(metadata) = fs::metadata(path) {
+ seed.push_str(&metadata.ino().to_string());
+ }
+ }
+ Some(seed)
+}
+
+#[cfg(target_os = "macos")]
+fn machine_seed() -> Option {
+ let output = std::process::Command::new("/usr/sbin/system_profiler")
+ .arg("SPHardwareDataType")
+ .output()
+ .ok()?;
+ if !output.status.success() {
+ return None;
+ }
+ // Python hashes from the UUID label through the end of the hardware report.
+ let report = String::from_utf8(output.stdout).ok()?;
+ let start = report.find("UUID")?;
+ Some(report[start..].trim().to_owned())
+}
+
+#[cfg(target_os = "windows")]
+fn machine_seed() -> Option {
+ use std::os::windows::process::CommandExt;
+ use std::path::PathBuf;
+ use std::process::Command;
+
+ let system = PathBuf::from(std::env::var_os("SystemRoot")?).join("System32");
+ let read = |program: &str, args: &[&str]| {
+ let output = Command::new(system.join(program))
+ .args(args)
+ .creation_flags(0x08000000) // CREATE_NO_WINDOW for desktop applications
+ .output()
+ .ok()?;
+ if !output.status.success() {
+ return None;
+ }
+ let value = String::from_utf8(output.stdout).ok()?.trim().to_owned();
+ (!value.is_empty()).then_some(value)
+ };
+ let uuid = read(
+ r"WindowsPowerShell\v1.0\powershell.exe",
+ &[
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "(Get-CimInstance -Class Win32_ComputerSystemProduct).UUID",
+ ],
+ );
+ uuid.or_else(|| {
+ let registry = read(
+ "reg.exe",
+ &[
+ "query",
+ r"HKLM\SOFTWARE\Microsoft\Cryptography",
+ "/v",
+ "MachineGuid",
+ "/reg:64",
+ ],
+ )?;
+ let (_, value) = registry.split_once("REG_SZ")?;
+ Some(value.trim().to_owned())
+ })
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
+fn machine_seed() -> Option {
+ None
+}
diff --git a/src/lib.rs b/src/lib.rs
index db202c5..60c3634 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,5 +1,16 @@
+//! Verify online licenses with [`methods::Key`] and reload signed files with
+//! [`models::LicenseKey::load_from_string`].
+//! Look up a customer's licenses by ID or secret with [`methods::Customer`].
+//! Use [`methods::Data`] for custom values and usage counters, and
+//! [`methods::Analytics`] to register feature usage events.
+
mod client;
mod error;
+pub mod helpers;
+pub mod methods;
+pub mod models;
+
pub use client::*;
pub use error::*;
+pub use models::*;
diff --git a/src/methods.rs b/src/methods.rs
new file mode 100644
index 0000000..d8a1a23
--- /dev/null
+++ b/src/methods.rs
@@ -0,0 +1,146 @@
+//! Web API methods for license keys, customers, data objects, and usage analytics.
+
+use serde::Serialize;
+
+use crate::models::{KeyActivateParams, LicenseKey, LicenseResponse, PublicKey, RsaKeyValue};
+use crate::{Client, Error, Result};
+
+mod analytics;
+mod customer;
+mod data;
+pub use crate::models::{
+ CustomerLicenseOptions, DataObjectOwner, DataObjectSelector, DeactivationMode, NewDataObject,
+ RegisterEvent,
+};
+pub use analytics::Analytics;
+pub use customer::Customer;
+pub use data::Data;
+
+#[cfg(test)]
+mod tests;
+
+/// License-key methods. Reuse this handle to share the HTTP client and parsed RSA public key.
+pub struct Key {
+ client: Client,
+ access_token: String,
+ public_key: PublicKey,
+}
+
+impl Key {
+ pub fn new(access_token: impl Into, rsa_public_key: &str) -> Result {
+ Self::with_client(Client::new(), access_token, rsa_public_key)
+ }
+
+ /// Uses an existing HTTP client, for example one configured with a proxy.
+ pub fn with_client(
+ client: Client,
+ access_token: impl Into,
+ rsa_public_key: &str,
+ ) -> Result {
+ Ok(Self {
+ client,
+ access_token: access_token.into(),
+ public_key: RsaKeyValue::from_xml_str(rsa_public_key)?.try_into()?,
+ })
+ }
+
+ /// Activates a key and checks the signed response against the requested product.
+ /// Supply a stable machine code for node-locked licenses. Use `None` for unlimited machines.
+ pub async fn activate(
+ &self,
+ product_id: u64,
+ license_key: &str,
+ machine_code: Option<&str>,
+ ) -> Result {
+ let mut params = KeyActivateParams::builder();
+ params.product_id(product_id).key(license_key);
+ if let Some(machine_code) = machine_code {
+ params.machine_code(machine_code);
+ }
+ self.activate_with_params(params.build()?).await
+ }
+
+ /// Activates with additional options such as a friendly name. Always requests a signed response.
+ pub async fn activate_with_params(&self, mut params: KeyActivateParams) -> Result {
+ params.sign = Some(true);
+ params.model_version.get_or_insert(3);
+ self.request("key/Activate", params.product_id, ¶ms.key, ¶ms)
+ .await
+ }
+
+ /// Releases a device registration or a floating seat. Requires Deactivate permission.
+ pub async fn deactivate(
+ &self,
+ product_id: u64,
+ license_key: &str,
+ machine_code: &str,
+ mode: DeactivationMode,
+ ) -> Result<()> {
+ #[derive(Serialize)]
+ #[serde(rename_all = "PascalCase")]
+ struct Deactivate<'a> {
+ product_id: u64,
+ key: &'a str,
+ machine_code: &'a str,
+ floating: bool,
+ }
+ let params = Deactivate {
+ product_id,
+ key: license_key,
+ machine_code,
+ floating: mode == DeactivationMode::Floating,
+ };
+ self.client
+ .action("key/Deactivate", &self.access_token, ¶ms)
+ .await
+ }
+
+ /// Retrieves a signed license without registering a machine or acquiring a seat.
+ /// GetKey can return a blocked license. Check `block` before granting access.
+ pub async fn get_key(&self, product_id: u64, license_key: &str) -> Result {
+ #[derive(Serialize)]
+ #[serde(rename_all = "PascalCase")]
+ struct GetKeyParams<'a> {
+ product_id: u64,
+ key: &'a str,
+ sign: bool,
+ sign_method: u8,
+ model_version: u8,
+ }
+ let params = GetKeyParams {
+ product_id,
+ key: license_key,
+ sign: true,
+ sign_method: 1,
+ model_version: 3,
+ };
+ self.request("key/GetKey", product_id, license_key, ¶ms)
+ .await
+ }
+
+ async fn request(
+ &self,
+ method: &str,
+ product_id: u64,
+ requested_key: &str,
+ params: &impl Serialize,
+ ) -> Result {
+ let response = self
+ .client
+ .post::(method, &self.access_token, params)
+ .await?;
+ let license = response.into_license(Some(&self.public_key))?;
+ if license.product_id != product_id {
+ return Err(Error::ProductMismatch);
+ }
+ // A field-restricted access token can hide the license-key string.
+ if license
+ .key
+ .as_ref()
+ .is_some_and(|key| !key.eq_ignore_ascii_case(requested_key))
+ {
+ return Err(Error::LicenseKeyMismatch);
+ }
+ Ok(license)
+ }
+}
diff --git a/src/methods/analytics.rs b/src/methods/analytics.rs
new file mode 100644
index 0000000..c4613ae
--- /dev/null
+++ b/src/methods/analytics.rs
@@ -0,0 +1,39 @@
+use crate::models::RegisterEvent;
+use crate::{Client, Error, Result};
+
+/// Usage analytics methods, corresponding to the Web API's AI methods.
+pub struct Analytics {
+ client: Client,
+ access_token: String,
+}
+
+impl Analytics {
+ pub fn new(access_token: impl Into) -> Self {
+ Self::with_client(Client::new(), access_token)
+ }
+
+ pub fn with_client(client: Client, access_token: impl Into) -> Self {
+ Self {
+ client,
+ access_token: access_token.into(),
+ }
+ }
+
+ /// Records one event with RegisterEvent permission. The server deduplicates an
+ /// identical retry with the same client event ID while it retains the original.
+ pub async fn register_event(&self, event: &RegisterEvent<'_>) -> Result<()> {
+ if event.key.is_some_and(|key| !key.is_empty()) && event.product_id.unwrap_or(0) == 0 {
+ return Err(Error::Custom(
+ "RegisterEvent requires a product ID with a license key".into(),
+ ));
+ }
+ if event.client_event_id.is_some_and(|id| id.trim().is_empty()) {
+ return Err(Error::Custom(
+ "ClientEventId must be a non-empty GUID".into(),
+ ));
+ }
+ self.client
+ .action("ai/RegisterEvent", &self.access_token, event)
+ .await
+ }
+}
diff --git a/src/methods/customer.rs b/src/methods/customer.rs
new file mode 100644
index 0000000..e92e6be
--- /dev/null
+++ b/src/methods/customer.rs
@@ -0,0 +1,100 @@
+use serde::{Deserialize, Serialize};
+
+use crate::models::{CustomerLicense, CustomerLicenseOptions, CustomerLicenses};
+use crate::{Client, Error, Result};
+
+/// Looks up the licenses assigned to a customer across products.
+pub struct Customer {
+ client: Client,
+ access_token: String,
+}
+
+#[derive(Serialize)]
+#[serde(untagged, rename_all_fields = "PascalCase")]
+enum Lookup<'a> {
+ Id { customer_id: u64 },
+ Secret { secret: &'a str },
+}
+
+impl Customer {
+ pub fn new(access_token: impl Into) -> Self {
+ Self::with_client(Client::new(), access_token)
+ }
+
+ pub fn with_client(client: Client, access_token: impl Into) -> Self {
+ Self {
+ client,
+ access_token: access_token.into(),
+ }
+ }
+
+ /// Lists licenses by customer ID. Requires GetCustomerLicenses permission.
+ pub async fn get_customer_licenses(
+ &self,
+ customer_id: u64,
+ options: CustomerLicenseOptions,
+ ) -> Result {
+ self.list(Lookup::Id { customer_id }, options).await
+ }
+
+ /// Lists licenses using the supplied customer secret. Requires GetCustomerLicensesBySecret permission.
+ pub async fn get_customer_licenses_by_secret(
+ &self,
+ secret: &str,
+ options: CustomerLicenseOptions,
+ ) -> Result {
+ self.list(Lookup::Secret { secret }, options).await
+ }
+
+ async fn list(
+ &self,
+ lookup: Lookup<'_>,
+ options: CustomerLicenseOptions,
+ ) -> Result {
+ #[derive(Serialize)]
+ #[serde(rename_all = "PascalCase")]
+ struct Request<'a> {
+ #[serde(flatten)]
+ lookup: Lookup<'a>,
+ #[serde(flatten)]
+ options: CustomerLicenseOptions,
+ model_version: u8,
+ }
+
+ #[derive(Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct Response {
+ license_keys: Option>,
+ metadata: Option,
+ }
+
+ let method = match lookup {
+ Lookup::Id { .. } => "customer/GetCustomerLicenses",
+ Lookup::Secret { .. } => "customer/GetCustomerLicensesBySecret",
+ };
+ // Version 1 supports the lightweight list. Version 3 includes floating device details.
+ let request = Request {
+ lookup,
+ options,
+ model_version: if options.detailed { 3 } else { 1 },
+ };
+ let response: Response = self
+ .client
+ .post(method, &self.access_token, &request)
+ .await?;
+ let license_keys = response.license_keys.ok_or_else(|| {
+ Error::Custom("customer license response is missing licenseKeys".into())
+ })?;
+ if options.metadata && response.metadata.is_none() {
+ return Err(Error::Custom(
+ "customer license response is missing requested metadata".into(),
+ ));
+ }
+ // JSON object keys are strings. Decode the global IDs with the JSON map-key deserializer.
+ let metadata = response.metadata.map(serde_json::from_value).transpose()?;
+ Ok(CustomerLicenses {
+ license_keys,
+ metadata,
+ })
+ }
+}
diff --git a/src/methods/data.rs b/src/methods/data.rs
new file mode 100644
index 0000000..37a9602
--- /dev/null
+++ b/src/methods/data.rs
@@ -0,0 +1,328 @@
+use serde::{Deserialize, Serialize, de::DeserializeOwned};
+
+use crate::client::EmptyResponse;
+use crate::models::{DataObjectOwner, DataObjectSelector, NewDataObject};
+use crate::{Client, DataObject, Error, Result};
+
+/// Data-object methods. Use the corresponding Data permission on the access token.
+pub struct Data {
+ client: Client,
+ access_token: String,
+}
+
+#[derive(Clone, Copy, Serialize)]
+#[serde(untagged, rename_all_fields = "PascalCase")]
+enum Target<'a> {
+ Key {
+ product_id: u64,
+ key: &'a str,
+ },
+ Owner {
+ referencer_type: u8,
+ referencer_id: u64,
+ },
+ ById {},
+}
+
+impl From for Target<'_> {
+ fn from(owner: DataObjectOwner) -> Self {
+ let (referencer_type, referencer_id) = match owner {
+ DataObjectOwner::Account => (0, 0),
+ DataObjectOwner::Product(id) => (1, id),
+ DataObjectOwner::License(id) => (2, id),
+ };
+ Self::Owner {
+ referencer_type,
+ referencer_id,
+ }
+ }
+}
+
+#[derive(Serialize)]
+struct DataRequest<'a, P> {
+ #[serde(flatten)]
+ target: Target<'a>,
+ #[serde(flatten)]
+ params: P,
+}
+
+#[derive(Serialize)]
+#[serde(untagged, rename_all_fields = "PascalCase")]
+enum ChangeValue<'a> {
+ Text {
+ string_value: &'a str,
+ },
+ Integer {
+ int_value: i32,
+ },
+ Counter {
+ int_value: i32,
+ enable_bound: bool,
+ bound: Option,
+ },
+ Remove {},
+}
+
+#[derive(Serialize)]
+struct Change<'a, 'b> {
+ #[serde(flatten)]
+ object: DataObjectSelector<'a>,
+ #[serde(flatten)]
+ value: ChangeValue<'b>,
+}
+
+impl Data {
+ pub fn new(access_token: impl Into) -> Self {
+ Self::with_client(Client::new(), access_token)
+ }
+
+ pub fn with_client(client: Client, access_token: impl Into) -> Self {
+ Self {
+ client,
+ access_token: access_token.into(),
+ }
+ }
+
+ /// Lists a license's current data objects, optionally filtering names by substring.
+ pub async fn list_key_data_objects(
+ &self,
+ product_id: u64,
+ key: &str,
+ contains: Option<&str>,
+ ) -> Result> {
+ self.list(Target::Key { product_id, key }, contains).await
+ }
+
+ /// Creates an object on this license and returns its server-assigned ID.
+ pub async fn add_data_object_to_key(
+ &self,
+ product_id: u64,
+ key: &str,
+ object: NewDataObject<'_>,
+ ) -> Result {
+ self.add(Target::Key { product_id, key }, object).await
+ }
+
+ /// Replaces the integer value of a named or numbered object on a license.
+ pub async fn set_int_value_to_key<'a>(
+ &self,
+ product_id: u64,
+ key: &str,
+ object: impl Into>,
+ value: i32,
+ ) -> Result<()> {
+ self.change(
+ "SetIntValue",
+ Target::Key { product_id, key },
+ object.into(),
+ ChangeValue::Integer { int_value: value },
+ )
+ .await
+ }
+
+ /// Replaces the string value of a named or numbered object on a license.
+ pub async fn set_string_value_to_key<'a>(
+ &self,
+ product_id: u64,
+ key: &str,
+ object: impl Into>,
+ value: &str,
+ ) -> Result<()> {
+ self.change(
+ "SetStringValue",
+ Target::Key { product_id, key },
+ object.into(),
+ ChangeValue::Text {
+ string_value: value,
+ },
+ )
+ .await
+ }
+
+ /// Removes an object from this license by ID or unique name.
+ pub async fn remove_data_object_to_key<'a>(
+ &self,
+ product_id: u64,
+ key: &str,
+ object: impl Into>,
+ ) -> Result<()> {
+ self.change(
+ "RemoveDataObject",
+ Target::Key { product_id, key },
+ object.into(),
+ ChangeValue::Remove {},
+ )
+ .await
+ }
+
+ /// Increments a counter when its current value is below the optional upper bound.
+ pub async fn increment_int_value_to_key<'a>(
+ &self,
+ product_id: u64,
+ key: &str,
+ object: impl Into>,
+ amount: u32,
+ upper_bound: Option,
+ ) -> Result<()> {
+ self.adjust(
+ "IncrementIntValue",
+ Target::Key { product_id, key },
+ object.into(),
+ amount,
+ upper_bound,
+ )
+ .await
+ }
+
+ /// Decrements a counter when its current value is above the optional lower bound.
+ pub async fn decrement_int_value_to_key<'a>(
+ &self,
+ product_id: u64,
+ key: &str,
+ object: impl Into>,
+ amount: u32,
+ lower_bound: Option,
+ ) -> Result<()> {
+ self.adjust(
+ "DecrementIntValue",
+ Target::Key { product_id, key },
+ object.into(),
+ amount,
+ lower_bound,
+ )
+ .await
+ }
+
+ /// Lists objects belonging to one account, product, or license.
+ pub async fn list_data_objects(
+ &self,
+ owner: DataObjectOwner,
+ contains: Option<&str>,
+ ) -> Result> {
+ self.list(owner.into(), contains).await
+ }
+
+ /// Creates an account-, product-, or license-level object using an administrative access token.
+ pub async fn add_data_object(
+ &self,
+ owner: DataObjectOwner,
+ object: NewDataObject<'_>,
+ ) -> Result {
+ self.add(owner.into(), object).await
+ }
+
+ /// Updates an object's integer by its globally unique data-object ID.
+ pub async fn set_int_value(&self, id: u64, value: i32) -> Result<()> {
+ self.change(
+ "SetIntValue",
+ Target::ById {},
+ id.into(),
+ ChangeValue::Integer { int_value: value },
+ )
+ .await
+ }
+
+ /// Updates an object's text by its globally unique data-object ID.
+ pub async fn set_string_value(&self, id: u64, value: &str) -> Result<()> {
+ self.change(
+ "SetStringValue",
+ Target::ById {},
+ id.into(),
+ ChangeValue::Text {
+ string_value: value,
+ },
+ )
+ .await
+ }
+
+ /// Removes the object with this globally unique data-object ID.
+ pub async fn remove_data_object(&self, id: u64) -> Result<()> {
+ self.change(
+ "RemoveDataObject",
+ Target::ById {},
+ id.into(),
+ ChangeValue::Remove {},
+ )
+ .await
+ }
+
+ async fn list(&self, target: Target<'_>, contains: Option<&str>) -> Result> {
+ #[derive(Serialize)]
+ #[serde(rename_all = "PascalCase")]
+ struct Filter<'a> {
+ contains: Option<&'a str>,
+ }
+ #[derive(Deserialize)]
+ struct Listed {
+ #[serde(rename = "dataObjects", alias = "DataObjects")]
+ objects: Option>,
+ }
+
+ let response: Listed = self
+ .request("ListDataObjects", target, Filter { contains })
+ .await?;
+ response
+ .objects
+ .ok_or_else(|| Error::Custom("ListDataObjects response is missing dataObjects".into()))
+ }
+
+ async fn add(&self, target: Target<'_>, object: NewDataObject<'_>) -> Result {
+ #[derive(Deserialize)]
+ struct Added {
+ #[serde(alias = "Id")]
+ id: Option,
+ }
+ let response: Added = self.request("AddDataObject", target, object).await?;
+ response
+ .id
+ .ok_or_else(|| Error::Custom("AddDataObject response is missing id".into()))
+ }
+
+ async fn adjust(
+ &self,
+ method: &str,
+ target: Target<'_>,
+ object: DataObjectSelector<'_>,
+ amount: u32,
+ bound: Option,
+ ) -> Result<()> {
+ let int_value = i32::try_from(amount).map_err(|_| {
+ Error::Custom("counter amount exceeds the API's 32-bit signed integer range".into())
+ })?;
+ let value = ChangeValue::Counter {
+ int_value,
+ enable_bound: bound.is_some(),
+ bound,
+ };
+ self.change(method, target, object, value).await
+ }
+
+ async fn change(
+ &self,
+ method: &str,
+ target: Target<'_>,
+ object: DataObjectSelector<'_>,
+ value: ChangeValue<'_>,
+ ) -> Result<()> {
+ let _: EmptyResponse = self
+ .request(method, target, Change { object, value })
+ .await?;
+ Ok(())
+ }
+
+ async fn request(
+ &self,
+ method: &str,
+ target: Target<'_>,
+ params: impl Serialize,
+ ) -> Result {
+ let suffix = match target {
+ Target::Key { .. } => "ToKey",
+ _ => "",
+ };
+ let route = format!("data/{method}{suffix}");
+ self.client
+ .post(&route, &self.access_token, &DataRequest { target, params })
+ .await
+ }
+}
diff --git a/src/methods/tests.rs b/src/methods/tests.rs
new file mode 100644
index 0000000..ac4c686
--- /dev/null
+++ b/src/methods/tests.rs
@@ -0,0 +1,645 @@
+use super::*;
+use mockito::Server;
+
+const PUBLIC_KEY: &str = include_str!("../../examples/data/public-key.xml");
+const SIGNED_RESPONSE: &str = include_str!("../../examples/data/license.skm");
+
+fn test_client(server: &Server) -> Client {
+ Client::local_server(format!("{}/api", server.url()))
+}
+
+fn test_keys(server: &Server) -> Key {
+ Key::with_client(test_client(server), "demo", PUBLIC_KEY).unwrap()
+}
+
+const SUCCESS: &str = r#"{"result":0,"message":null}"#;
+
+async fn form(server: &mut Server, path: &str, body: &str, response: &str) -> mockito::Mock {
+ server
+ .mock("POST", path)
+ .match_header("content-type", "application/x-www-form-urlencoded")
+ .match_body(body)
+ .with_body(response)
+ .create_async()
+ .await
+}
+
+fn listed_license() -> serde_json::Value {
+ serde_json::json!({
+ "productId": 17, "id": 9, "globalId": 5000000001u64, "key": "sample-license",
+ "created": "2024-03-01T10:00:00", "expires": "2027-03-01T10:00:00Z",
+ "period": 30, "block": false, "notes": null,
+ "f1": true, "f2": false, "f3": false, "f4": false, "f5": false,
+ "f6": false, "f7": false, "f8": true
+ })
+}
+
+#[tokio::test]
+async fn customer_id_lookup_reads_basic_licenses_and_empty_lists() {
+ let mut server = Server::new_async().await;
+ let customers = Customer::with_client(test_client(&server), "demo");
+ let path = "/api/customer/GetCustomerLicenses";
+ let body = "token=demo&CustomerId=37&Detailed=false&Metadata=false&ModelVersion=1";
+ let json = serde_json::json!({"result": 0, "licenseKeys": [listed_license()]});
+ let request = form(&mut server, path, body, &json.to_string()).await;
+ let result = customers
+ .get_customer_licenses(37, Default::default())
+ .await
+ .unwrap();
+ request.assert_async().await;
+ let license = &result.license_keys[0];
+ assert_eq!((license.product_id, license.global_id), (17, 5000000001));
+ assert!(license.feature1 && license.feature8);
+ assert_eq!(license.created, "2024-03-01T10:00:00");
+ assert!(license.data_objects.is_none() && result.metadata.is_none());
+
+ let empty = form(&mut server, path, body, r#"{"result":0,"licenseKeys":[]}"#).await;
+ let result = customers
+ .get_customer_licenses(37, Default::default())
+ .await
+ .unwrap();
+ assert!(result.license_keys.is_empty());
+ empty.assert_async().await;
+}
+
+#[tokio::test]
+async fn customer_secret_lookup_reads_details_and_metadata_by_global_id() {
+ use serde_json::json;
+
+ let mut server = Server::new_async().await;
+ let customers = Customer::with_client(test_client(&server), "demo");
+ let mut license = listed_license();
+ license["customer"] =
+ json!({"id":37, "name":"Sample", "email":null, "created":"2024-01-01T00:00:00"});
+ license["activatedMachines"] = json!([{"mid":"floating:sample", "ip":null, "time":null, "friendlyName":"Test", "floatingExpires":"2026-12-01T10:01:00Z"}]);
+ license["dataObjects"] = json!([{"id":99,"name":"credits","intValue":-2,"stringValue":null}]);
+ let metadata = json!({"5000000001":{"activatedMachines":1,"licenseStatus":{"isValid":true,"reasonForInvalidity":0,"trial":false,"timeLimited":true,"timeLeft":12}}});
+ let json = json!({"result":0,"licenseKeys":[license],"metadata":metadata});
+ let request = form(
+ &mut server,
+ "/api/customer/GetCustomerLicensesBySecret",
+ "token=demo&Secret=s%2Be%26c%3D&Detailed=true&Metadata=true&ModelVersion=3",
+ &json.to_string(),
+ )
+ .await;
+ let options = crate::models::CustomerLicenseOptions {
+ detailed: true,
+ metadata: true,
+ };
+ let result = customers
+ .get_customer_licenses_by_secret("s+e&c=", options)
+ .await
+ .unwrap();
+ let license = &result.license_keys[0];
+ assert_eq!(license.customer.as_ref().unwrap().id, 37);
+ assert_eq!(
+ license.activated_machines.as_ref().unwrap()[0].mid,
+ "floating:sample"
+ );
+ assert_eq!(license.data_objects.as_ref().unwrap()[0].int_value, -2);
+ let entry = &result.metadata.as_ref().unwrap()[&license.global_id];
+ assert_eq!(entry.activated_machines, 1);
+ assert_eq!(entry.license_status.time_left, 12);
+ request.assert_async().await;
+}
+
+#[tokio::test]
+async fn customer_lookup_distinguishes_api_errors_from_incomplete_successes() {
+ let mut server = Server::new_async().await;
+ let customers = Customer::with_client(test_client(&server), "demo");
+ let denied = form(
+ &mut server,
+ "/api/customer/GetCustomerLicensesBySecret",
+ "token=demo&Secret=missing&Detailed=false&Metadata=false&ModelVersion=1",
+ r#"{"result":1,"message":"Access denied."}"#,
+ )
+ .await;
+ let result = customers
+ .get_customer_licenses_by_secret("missing", Default::default())
+ .await;
+ assert!(matches!(result, Err(Error::Api(message)) if message == "Access denied."));
+ denied.assert_async().await;
+
+ for (metadata, response, field) in [
+ (false, r#"{"result":0}"#, "licenseKeys"),
+ (true, r#"{"result":0,"licenseKeys":[]}"#, "metadata"),
+ ] {
+ let body =
+ format!("token=demo&CustomerId=37&Detailed=false&Metadata={metadata}&ModelVersion=1");
+ let request = form(
+ &mut server,
+ "/api/customer/GetCustomerLicenses",
+ &body,
+ response,
+ )
+ .await;
+ let options = crate::models::CustomerLicenseOptions {
+ metadata,
+ ..Default::default()
+ };
+ let result = customers.get_customer_licenses(37, options).await;
+ assert!(matches!(result, Err(Error::Custom(message)) if message.contains(field)));
+ request.assert_async().await;
+ }
+}
+
+#[tokio::test]
+async fn deactivation_distinguishes_a_device_from_a_floating_seat() {
+ let mut server = Server::new_async().await;
+ let keys = test_keys(&server);
+ for (mode, floating) in [
+ (DeactivationMode::NodeLocked, false),
+ (DeactivationMode::Floating, true),
+ ] {
+ let body =
+ format!("token=demo&ProductId=42&Key=A%2BB&MachineCode=device+1&Floating={floating}");
+ let request = form(&mut server, "/api/key/Deactivate", &body, SUCCESS).await;
+ keys.deactivate(42, "A+B", "device 1", mode).await.unwrap();
+ request.assert_async().await;
+ }
+}
+
+#[tokio::test]
+async fn low_level_activation_preserves_caller_controlled_signing() {
+ use base64::{Engine, engine::general_purpose::STANDARD};
+ use serde_json::{Value, json};
+
+ let mut server = Server::new_async().await;
+ let saved: Value = serde_json::from_str(SIGNED_RESPONSE).unwrap();
+ let payload = STANDARD
+ .decode(saved["licenseKey"].as_str().unwrap())
+ .unwrap();
+ let unsigned_license: Value = serde_json::from_slice(&payload).unwrap();
+ let response = json!({"result": 0, "licenseKey": unsigned_license});
+ let request = form(
+ &mut server,
+ "/api/key/Activate",
+ "token=demo&ProductId=3646&Key=MPDWY-PQAOW-FKSCH-SGAAU&Sign=false&SignMethod=1",
+ &response.to_string(),
+ )
+ .await;
+
+ let params = KeyActivateParams::builder()
+ .product_id(3646_u64)
+ .key("MPDWY-PQAOW-FKSCH-SGAAU")
+ .sign(false)
+ .build()
+ .unwrap();
+ let license = test_client(&server)
+ .key_activate("demo", params)
+ .await
+ .unwrap();
+ assert_eq!(license.product_id, 3646);
+ assert!(matches!(
+ license.save_as_string(),
+ Err(Error::MissingSignature)
+ ));
+ request.assert_async().await;
+}
+
+#[tokio::test]
+async fn usage_event_preserves_fields_and_id_across_explicit_retries() {
+ let mut server = Server::new_async().await;
+ let analytics = Analytics::with_client(test_client(&server), "analytics");
+ let id = "bcf2127c-5ef2-4bd9-b654-96b14091bd71";
+ let event = RegisterEvent {
+ product_id: Some(3),
+ key: Some("A+B"),
+ machine_code: Some("device 1"),
+ feature_name: "Reports",
+ event_name: "export & save",
+ value: Some(2530),
+ currency: Some("USD"),
+ metadata: Some(r#"{"format":"pdf"}"#),
+ client_event_id: Some(id),
+ };
+ let body = format!(
+ "token=analytics&ProductId=3&Key=A%2BB&MachineCode=device+1&FeatureName=Reports&EventName=export+%26+save&Value=2530&Currency=USD&Metadata=%7B%22format%22%3A%22pdf%22%7D&ClientEventId={id}"
+ );
+ let request = server
+ .mock("POST", "/api/ai/RegisterEvent")
+ .match_body(body.as_str())
+ .expect(2)
+ .with_body(r#"{"Result":0}"#)
+ .create_async()
+ .await;
+ analytics.register_event(&event).await.unwrap();
+ analytics.register_event(&event).await.unwrap();
+ request.assert_async().await;
+}
+
+#[tokio::test]
+async fn standalone_events_need_no_license_and_invalid_attribution_is_rejected() {
+ let mut server = Server::new_async().await;
+ let analytics = Analytics::with_client(test_client(&server), "analytics");
+ let request = form(
+ &mut server,
+ "/api/ai/RegisterEvent",
+ "token=analytics&MachineCode=device",
+ SUCCESS,
+ )
+ .await;
+ analytics
+ .register_event(&RegisterEvent {
+ machine_code: Some("device"),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ request.assert_async().await;
+
+ for invalid in [
+ RegisterEvent {
+ key: Some("key"),
+ ..Default::default()
+ },
+ RegisterEvent {
+ product_id: Some(0),
+ key: Some("key"),
+ ..Default::default()
+ },
+ RegisterEvent {
+ client_event_id: Some(" "),
+ ..Default::default()
+ },
+ ] {
+ assert!(matches!(
+ analytics.register_event(&invalid).await,
+ Err(Error::Custom(_))
+ ));
+ }
+
+ let denied = form(
+ &mut server,
+ "/api/ai/RegisterEvent",
+ "token=analytics&EventName=start",
+ r#"{"result":1,"message":"Access denied."}"#,
+ )
+ .await;
+ let result = analytics
+ .register_event(&RegisterEvent {
+ event_name: "start",
+ ..Default::default()
+ })
+ .await;
+ assert!(matches!(result, Err(Error::Api(message)) if message == "Access denied."));
+ denied.assert_async().await;
+}
+
+#[tokio::test]
+async fn lists_and_creates_license_objects_with_their_returned_ids_and_values() {
+ let mut server = Server::new_async().await;
+ let data = Data::with_client(test_client(&server), "data");
+ let list = form(&mut server, "/api/data/ListDataObjectsToKey", "token=data&ProductId=3&Key=A%2BB&Contains=max+seats",
+ r#"{"result":0,"dataObjects":[{"id":456,"name":"max seats","intValue":-2,"stringValue":null}]}"#).await;
+ let objects = data
+ .list_key_data_objects(3, "A+B", Some("max seats"))
+ .await
+ .unwrap();
+ assert_eq!(
+ (
+ objects[0].id,
+ objects[0].int_value,
+ objects[0].string_value.as_str()
+ ),
+ (456, -2, "")
+ );
+ list.assert_async().await;
+
+ let add = form(&mut server, "/api/data/AddDataObjectToKey", "token=data&ProductId=3&Key=A%2BB&Name=credits&StringValue=a%26b&IntValue=10&CheckForDuplicates=true", r#"{"Result":0,"Id":4294967297}"#).await;
+ let id = data
+ .add_data_object_to_key(
+ 3,
+ "A+B",
+ NewDataObject {
+ name: "credits",
+ int_value: 10,
+ string_value: "a&b",
+ check_for_duplicates: true,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(id, 4294967297);
+ add.assert_async().await;
+}
+
+#[tokio::test]
+async fn license_counter_updates_use_the_server_bound_and_propagate_rejections() {
+ let mut server = Server::new_async().await;
+ let data = Data::with_client(test_client(&server), "data");
+ let add = form(
+ &mut server,
+ "/api/data/IncrementIntValueToKey",
+ "token=data&ProductId=3&Key=key&Id=17&IntValue=2&EnableBound=true&Bound=10",
+ SUCCESS,
+ )
+ .await;
+ data.increment_int_value_to_key(3, "key", 17, 2, Some(10))
+ .await
+ .unwrap();
+ add.assert_async().await;
+ let consume = form(
+ &mut server,
+ "/api/data/DecrementIntValueToKey",
+ "token=data&ProductId=3&Key=key&Name=credits&IntValue=1&EnableBound=true&Bound=0",
+ r#"{"result":1,"message":"Bound reached."}"#,
+ )
+ .await;
+ let result = data
+ .decrement_int_value_to_key(3, "key", "credits", 1, Some(0))
+ .await;
+ assert!(matches!(result, Err(Error::Api(message)) if message == "Bound reached."));
+ consume.assert_async().await;
+ let unbounded = form(
+ &mut server,
+ "/api/data/IncrementIntValueToKey",
+ "token=data&ProductId=3&Key=key&Name=exports&IntValue=1&EnableBound=false",
+ SUCCESS,
+ )
+ .await;
+ data.increment_int_value_to_key(3, "key", "exports", 1, None)
+ .await
+ .unwrap();
+ unbounded.assert_async().await;
+ assert!(matches!(
+ data.increment_int_value_to_key(3, "key", 17, u32::MAX, None)
+ .await,
+ Err(Error::Custom(_))
+ ));
+}
+
+#[tokio::test]
+async fn updates_and_removes_specific_license_objects_by_name_or_id() {
+ let mut server = Server::new_async().await;
+ let data = Data::with_client(test_client(&server), "data");
+ let number = form(
+ &mut server,
+ "/api/data/SetIntValueToKey",
+ "token=data&ProductId=3&Key=key&Name=offset&IntValue=-3",
+ SUCCESS,
+ )
+ .await;
+ let string = form(
+ &mut server,
+ "/api/data/SetStringValueToKey",
+ "token=data&ProductId=3&Key=key&Id=99&StringValue=",
+ SUCCESS,
+ )
+ .await;
+ let remove = form(
+ &mut server,
+ "/api/data/RemoveDataObjectToKey",
+ "token=data&ProductId=3&Key=key&Id=99",
+ SUCCESS,
+ )
+ .await;
+ data.set_int_value_to_key(3, "key", "offset", -3)
+ .await
+ .unwrap();
+ data.set_string_value_to_key(3, "key", 99, "")
+ .await
+ .unwrap();
+ data.remove_data_object_to_key(3, "key", 99).await.unwrap();
+ for request in [number, string, remove] {
+ request.assert_async().await;
+ }
+}
+
+#[tokio::test]
+async fn admin_methods_use_the_owner_for_creation_and_global_object_id_for_writes() {
+ let mut server = Server::new_async().await;
+ let data = Data::with_client(test_client(&server), "admin");
+ for (owner, kind, id) in [
+ (DataObjectOwner::Account, 0, 0),
+ (DataObjectOwner::Product(42), 1, 42),
+ (DataObjectOwner::License(501), 2, 501),
+ ] {
+ let scope = format!("token=admin&ReferencerType={kind}&ReferencerId={id}");
+ let list = form(
+ &mut server,
+ "/api/data/ListDataObjects",
+ &scope,
+ r#"{"result":0,"DataObjects":[]}"#,
+ )
+ .await;
+ assert!(
+ data.list_data_objects(owner, None)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ list.assert_async().await;
+ let add = form(
+ &mut server,
+ "/api/data/AddDataObject",
+ &format!("{scope}&Name=limit&StringValue=&IntValue=0&CheckForDuplicates=false"),
+ r#"{"result":0,"id":19}"#,
+ )
+ .await;
+ assert_eq!(
+ data.add_data_object(
+ owner,
+ NewDataObject {
+ name: "limit",
+ ..Default::default()
+ }
+ )
+ .await
+ .unwrap(),
+ 19
+ );
+ add.assert_async().await;
+ }
+ let update = form(
+ &mut server,
+ "/api/data/SetIntValue",
+ "token=admin&Id=19&IntValue=-1",
+ SUCCESS,
+ )
+ .await;
+ let text = form(
+ &mut server,
+ "/api/data/SetStringValue",
+ "token=admin&Id=19&StringValue=pro",
+ SUCCESS,
+ )
+ .await;
+ let remove = form(
+ &mut server,
+ "/api/data/RemoveDataObject",
+ "token=admin&Id=19",
+ SUCCESS,
+ )
+ .await;
+ data.set_int_value(19, -1).await.unwrap();
+ data.set_string_value(19, "pro").await.unwrap();
+ data.remove_data_object(19).await.unwrap();
+ for request in [update, text, remove] {
+ request.assert_async().await;
+ }
+}
+
+#[tokio::test]
+async fn rejects_incomplete_success_responses_and_surfaces_api_errors_without_data() {
+ let mut server = Server::new_async().await;
+ let data = Data::with_client(test_client(&server), "data");
+ let list = server
+ .mock("POST", "/api/data/ListDataObjectsToKey")
+ .with_body(SUCCESS)
+ .create_async()
+ .await;
+ assert!(matches!(
+ data.list_key_data_objects(1, "key", None).await,
+ Err(Error::Custom(_))
+ ));
+ list.assert_async().await;
+ let add = server
+ .mock("POST", "/api/data/AddDataObjectToKey")
+ .with_body(SUCCESS)
+ .create_async()
+ .await;
+ assert!(matches!(
+ data.add_data_object_to_key(1, "key", NewDataObject::default())
+ .await,
+ Err(Error::Custom(_))
+ ));
+ add.assert_async().await;
+ let rejected = server
+ .mock("POST", "/api/data/ListDataObjects")
+ .with_status(403)
+ .with_body(r#"{"result":1,"message":"Denied"}"#)
+ .create_async()
+ .await;
+ assert!(
+ matches!(data.list_data_objects(DataObjectOwner::Account, None).await, Err(Error::Api(message)) if message == "Denied")
+ );
+ rejected.assert_async().await;
+}
+
+#[tokio::test]
+async fn signed_lookup_returns_the_requested_key_without_a_machine_code() {
+ let mut server = Server::new_async().await;
+ let request = server.mock("POST", "/api/key/GetKey")
+ .match_body("token=demo&ProductId=3646&Key=MPDWY-PQAOW-FKSCH-SGAAU&Sign=true&SignMethod=1&ModelVersion=3")
+ .with_body(SIGNED_RESPONSE).create_async().await;
+ let license = test_keys(&server)
+ .get_key(3646, "MPDWY-PQAOW-FKSCH-SGAAU")
+ .await
+ .unwrap();
+ assert_eq!(license.product_id, 3646);
+ request.assert_async().await;
+}
+
+#[tokio::test]
+async fn activation_rejects_an_unsigned_response_even_on_http_success() {
+ let mut server = Server::new_async().await;
+ let mut response: serde_json::Value = serde_json::from_str(SIGNED_RESPONSE).unwrap();
+ response["signature"] = serde_json::Value::Null;
+ let request = server
+ .mock("POST", "/api/key/Activate")
+ .with_body(response.to_string())
+ .create_async()
+ .await;
+ assert!(matches!(
+ test_keys(&server)
+ .activate(3646, "MPDWY-PQAOW-FKSCH-SGAAU", None)
+ .await,
+ Err(Error::MissingSignature)
+ ));
+ request.assert_async().await;
+}
+
+#[tokio::test]
+async fn activation_requests_and_verifies_a_signed_license() {
+ let mut server = Server::new_async().await;
+ let request = server.mock("POST", "/api/key/Activate")
+ .match_body("token=demo&ProductId=3646&Key=MPDWY-PQAOW-FKSCH-SGAAU&Sign=true&MachineCode=289jf2afs3&SignMethod=1&ModelVersion=3")
+ .with_body(SIGNED_RESPONSE).create_async().await;
+
+ let license = test_keys(&server)
+ .activate(3646, "MPDWY-PQAOW-FKSCH-SGAAU", Some("289jf2afs3"))
+ .await
+ .unwrap();
+ assert_eq!(license.id, Some(4));
+ assert!(license.is_on_right_machine("289jf2afs3"));
+ assert!(!license.is_on_right_machine("other"));
+ request.assert_async().await;
+}
+
+#[tokio::test]
+async fn advanced_activation_always_signs_and_preserves_options() {
+ let mut server = Server::new_async().await;
+ let request = server.mock("POST", "/api/key/Activate")
+ .match_body("token=demo&ProductId=3646&Key=mpdwy-pqaow-fksch-sgaau&Sign=true&FriendlyName=Office&SignMethod=1&ModelVersion=2")
+ .with_body(SIGNED_RESPONSE).create_async().await;
+ let params = KeyActivateParams::builder()
+ .product_id(3646_u64)
+ .key("mpdwy-pqaow-fksch-sgaau")
+ .friendly_name("Office")
+ .model_version(2_u64)
+ .sign(false)
+ .build()
+ .unwrap();
+ test_keys(&server)
+ .activate_with_params(params)
+ .await
+ .unwrap();
+ request.assert_async().await;
+}
+
+#[tokio::test]
+async fn lookup_rejects_a_different_key_for_the_same_product() {
+ let mut server = Server::new_async().await;
+ let request = server
+ .mock("POST", "/api/key/GetKey")
+ .with_body(SIGNED_RESPONSE)
+ .create_async()
+ .await;
+ assert!(matches!(
+ test_keys(&server).get_key(3646, "different key").await,
+ Err(Error::LicenseKeyMismatch)
+ ));
+ request.assert_async().await;
+}
+
+#[tokio::test]
+async fn lookup_uses_get_key_and_rejects_a_response_for_another_product() {
+ let mut server = Server::new_async().await;
+ let request = server
+ .mock("POST", "/api/key/GetKey")
+ .match_body("token=demo&ProductId=42&Key=key&Sign=true&SignMethod=1&ModelVersion=3")
+ .with_body(SIGNED_RESPONSE)
+ .create_async()
+ .await;
+ let result = test_keys(&server).get_key(42, "key").await;
+ assert!(matches!(result, Err(Error::ProductMismatch)));
+ request.assert_async().await;
+}
+
+#[tokio::test]
+async fn preserves_api_rejections_and_http_errors() {
+ let mut server = Server::new_async().await;
+ let keys = test_keys(&server);
+ let rejection = server
+ .mock("POST", "/api/key/Activate")
+ .with_status(403)
+ .with_body(r#"{"result":1,"message":"Access denied."}"#)
+ .create_async()
+ .await;
+ assert!(
+ matches!(keys.activate(3646, "key", None).await, Err(Error::Api(message)) if message == "Access denied.")
+ );
+ rejection.assert_async().await;
+
+ let unavailable = server
+ .mock("POST", "/api/key/GetKey")
+ .with_status(503)
+ .with_body("temporarily unavailable")
+ .create_async()
+ .await;
+ assert!(
+ matches!(keys.get_key(3646, "key").await, Err(Error::Client(err)) if err.status().map(|s| s.as_u16()) == Some(503))
+ );
+ unavailable.assert_async().await;
+}
diff --git a/src/models.rs b/src/models.rs
new file mode 100644
index 0000000..c00ee76
--- /dev/null
+++ b/src/models.rs
@@ -0,0 +1,518 @@
+//! License models, request parameters, and signed license files.
+
+use std::net::IpAddr;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use base64::{Engine, engine::general_purpose::STANDARD};
+use derive_builder::Builder;
+use serde::{Deserialize, Deserializer, Serialize};
+
+use crate::client::ApiResponse;
+use crate::{Error, Result, Timestamp};
+
+mod customer_licenses;
+mod requests;
+pub use customer_licenses::*;
+pub use requests::{
+ DataObjectOwner, DataObjectSelector, DeactivationMode, NewDataObject, RegisterEvent,
+};
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LicenseKey {
+ #[serde(alias = "ProductId")]
+ pub product_id: u64,
+ #[serde(alias = "ID", alias = "Id", default, deserialize_with = "optional_id")]
+ pub id: Option,
+ #[serde(alias = "Key")]
+ pub key: Option,
+ #[serde(alias = "Created")]
+ pub created: Timestamp,
+ #[serde(alias = "Expires")]
+ pub expires: Timestamp,
+ #[serde(alias = "Period")]
+ pub period: u64,
+ #[serde(alias = "F1", alias = "f1")]
+ pub feature1: bool,
+ #[serde(alias = "F2", alias = "f2")]
+ pub feature2: bool,
+ #[serde(alias = "F3", alias = "f3")]
+ pub feature3: bool,
+ #[serde(alias = "F4", alias = "f4")]
+ pub feature4: bool,
+ #[serde(alias = "F5", alias = "f5")]
+ pub feature5: bool,
+ #[serde(alias = "F6", alias = "f6")]
+ pub feature6: bool,
+ #[serde(alias = "F7", alias = "f7")]
+ pub feature7: bool,
+ #[serde(alias = "F8", alias = "f8")]
+ pub feature8: bool,
+ #[serde(alias = "Notes")]
+ pub notes: Option,
+ #[serde(alias = "Block")]
+ pub block: bool,
+ #[serde(alias = "GlobalId", default, deserialize_with = "optional_id")]
+ pub global_id: Option,
+ #[serde(alias = "Customer")]
+ pub customer: Option,
+ #[serde(
+ alias = "ActivatedMachines",
+ default,
+ deserialize_with = "activation_list"
+ )]
+ pub activated_machines: Vec,
+ #[serde(alias = "TrialActivation")]
+ pub trial_activation: bool,
+ #[serde(alias = "MaxNoOfMachines")]
+ pub max_no_of_machines: Option,
+ #[serde(alias = "AllowedMachines")]
+ pub allowed_machines: Option,
+ #[serde(alias = "DataObjects", default, deserialize_with = "data_object_list")]
+ pub data_objects: Vec,
+ #[serde(alias = "SignDate")]
+ pub sign_date: Timestamp,
+ #[serde(alias = "Signature")]
+ pub signature: Option,
+
+ #[serde(skip, default)]
+ license_key_bytes: Vec,
+ #[serde(skip, default)]
+ signature_bytes: Vec,
+ #[serde(skip)]
+ response_metadata: Option,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ActivatedMachine {
+ #[serde(alias = "Mid", deserialize_with = "nullable_string")]
+ pub mid: String,
+ /// Absent when the account does not store IP addresses.
+ #[serde(alias = "IP", default, deserialize_with = "optional_ip")]
+ pub ip: Option,
+ #[serde(alias = "Time")]
+ pub time: Timestamp,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Customer {
+ #[serde(alias = "Id")]
+ pub id: u64,
+ #[serde(alias = "Name", default, deserialize_with = "nullable_string")]
+ pub name: String,
+ #[serde(alias = "Email", default, deserialize_with = "nullable_string")]
+ pub email: String,
+ #[serde(alias = "CompanyName", default, deserialize_with = "nullable_string")]
+ pub company_name: String,
+ #[serde(alias = "Created")]
+ pub created: Timestamp,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DataObject {
+ #[serde(alias = "Id", alias = "ID")]
+ pub id: u64,
+ #[serde(alias = "Name", default, deserialize_with = "nullable_string")]
+ pub name: String,
+ #[serde(alias = "StringValue", default, deserialize_with = "nullable_string")]
+ pub string_value: String,
+ #[serde(alias = "IntValue")]
+ pub int_value: i32,
+}
+
+// The API uses -1 for an ID hidden by the access token.
+fn optional_id<'de, D: Deserializer<'de>>(input: D) -> std::result::Result