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, D::Error> { + let Some(number) = Option::::deserialize(input)? else { + return Ok(None); + }; + if number.as_i64() == Some(-1) { + return Ok(None); + } + number + .as_u64() + .map(Some) + .ok_or_else(|| serde::de::Error::custom("invalid license ID")) +} + +fn optional_ip<'de, D: Deserializer<'de>>( + input: D, +) -> std::result::Result, D::Error> { + Option::::deserialize(input)? + .filter(|ip| !ip.is_empty()) + .map(|ip| ip.parse().map_err(serde::de::Error::custom)) + .transpose() +} + +fn nullable_string<'de, D: Deserializer<'de>>(input: D) -> std::result::Result { + Ok(Option::::deserialize(input)?.unwrap_or_default()) +} + +// A restricted machine list can contain a single null entry when no device matches. +fn activation_list<'de, D: Deserializer<'de>>( + input: D, +) -> std::result::Result, D::Error> { + Ok(Option::>>::deserialize(input)? + .unwrap_or_default() + .into_iter() + .flatten() + .collect()) +} + +fn data_object_list<'de, D: Deserializer<'de>>( + input: D, +) -> std::result::Result, D::Error> { + Ok(Option::>::deserialize(input)?.unwrap_or_default()) +} + +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 LicenseKey { + /// Returns the first data object with this exact, case-sensitive name in the license. + pub fn data_object(&self, name: &str) -> Option<&DataObject> { + self.data_objects.iter().find(|object| object.name == name) + } + + /// Converts the stored Unix expiry timestamp to the platform's system time. + pub fn expires_at(&self) -> Result { + UNIX_EPOCH + .checked_add(Duration::from_secs(self.expires)) + .ok_or_else(|| { + Error::Custom("license expiry is outside the platform's SystemTime range".into()) + }) + } + + /// Checks the signature of the original response returned by the server. + pub fn has_valid_signature( + &self, + public_key: impl TryInto, + ) -> Result { + verify_signature( + &self.license_key_bytes, + &self.signature_bytes, + &public_key.try_into()?, + ) + } + + /// Saves the original signed payload in the string-signature format shared by the SDKs. + /// Changes to the model fields do not change the saved payload. + pub fn save_as_string(&self) -> Result { + if self.license_key_bytes.is_empty() || self.signature_bytes.is_empty() { + return Err(Error::MissingSignature); + } + let mut response = serde_json::json!({ + "licenseKey": STANDARD.encode(&self.license_key_bytes), + "signature": STANDARD.encode(&self.signature_bytes), + "result": 0, + "message": "" + }); + if let Some(metadata) = &self.response_metadata { + response["metadata"] = metadata.clone(); + } + Ok(response.to_string()) + } + + /// Loads a signed response from Rust, Python or .NET (SignMethod=1). + /// Supply a maximum signature age to limit offline use. License expiry is a separate policy. + pub fn load_from_string( + rsa_public_key: &str, + saved: &str, + max_age: Option, + ) -> Result { + let response: KeyActivateResponse = serde_json::from_str(saved)?; + let public_key = RsaKeyValue::from_xml_str(rsa_public_key)?.try_into()?; + let license = response.into_license(Some(&public_key))?; + if let Some(max_age) = max_age { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|_| Error::SignatureAge)?; + license.check_signature_age(now, max_age)?; + } + Ok(license) + } + + fn check_signature_age(&self, now: Duration, max_age: Duration) -> Result<()> { + let age = now + .checked_sub(Duration::from_secs(self.sign_date)) + .ok_or(Error::SignatureAge)?; + if age > max_age { + return Err(Error::SignatureAge); + } + Ok(()) + } + + /// Checks a node-locked activation against the application's device ID. + /// Use this for licenses with Maximum Number of Machines greater than zero. + pub fn is_on_right_machine(&self, machine_code: &str) -> bool { + // Restricted responses can hide the machine limit while returning this device. + !machine_code.is_empty() + && self + .activated_machines + .iter() + .any(|machine| machine.mid == machine_code) + } +} + +fn verify_signature(data: &[u8], signature: &[u8], public_key: &PublicKey) -> Result { + if signature.is_empty() || data.is_empty() { + return Ok(false); + } + let mut verifier = + openssl::sign::Verifier::new(openssl::hash::MessageDigest::sha256(), public_key)?; + verifier.update(data)?; + Ok(verifier.verify(signature)?) +} + +impl TryFrom for LicenseKey { + type Error = Error; + + fn try_from(value: KeyActivateResponse) -> Result { + value.into_license(None) + } +} + +impl KeyActivateResponse { + fn into_license(self, public_key: Option<&PublicKey>) -> Result { + self.0.into_result()?.into_license(public_key) + } +} + +impl LicenseResponse { + pub(crate) fn into_license(self, public_key: Option<&PublicKey>) -> Result { + match self.license_key { + None => Err(Error::Custom( + "licenseKey field is required for success result".into(), + )), + Some(LicenseKeyResponse::Json(license)) if public_key.is_none() => Ok(license), + Some(LicenseKeyResponse::Json(_)) => Err(Error::MissingSignature), + Some(LicenseKeyResponse::Base64(encoded)) => { + let data = STANDARD.decode(encoded)?; + let signature = STANDARD.decode(self.signature.unwrap_or_default())?; + if let Some(public_key) = public_key { + if signature.is_empty() { + return Err(Error::MissingSignature); + } + if !verify_signature(&data, &signature, public_key)? { + return Err(Error::InvalidSignature); + } + } + let mut license: LicenseKey = serde_json::from_slice(&data)?; + license.license_key_bytes = data; + license.signature_bytes = signature; + license.response_metadata = self.metadata; + Ok(license) + } + } + } +} + +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(transparent)] +pub struct KeyActivateResponse(ApiResponse); + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct LicenseResponse { + #[serde(alias = "LicenseKey")] + license_key: Option, + #[serde(alias = "Signature")] + signature: Option, + #[serde(alias = "Metadata")] + metadata: Option, +} + +#[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::*; + use crate::client::TokenizedParams; + + #[test] + fn signature_age_includes_the_boundary_and_rejects_future_dates() { + let license = LicenseKey::load_from_string( + include_str!("../examples/data/public-key.xml"), + include_str!("../examples/data/license.skm"), + None, + ) + .unwrap(); + let signed_at = Duration::from_secs(license.sign_date); + let window = Duration::from_secs(60); + assert!( + license + .check_signature_age(signed_at + window, window) + .is_ok() + ); + assert!( + license + .check_signature_age(signed_at + window + Duration::from_secs(1), window) + .is_err() + ); + assert!( + license + .check_signature_age(signed_at - Duration::from_secs(1), window) + .is_err() + ); + } + + #[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/models/customer_licenses.rs b/src/models/customer_licenses.rs new file mode 100644 index 0000000..d9db84b --- /dev/null +++ b/src/models/customer_licenses.rs @@ -0,0 +1,100 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::{DataObject, nullable_string}; + +/// Both customer lookups return basic license records by default. +#[derive(Clone, Copy, Debug, Default, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct CustomerLicenseOptions { + /// Include customer information, device registrations, and data objects. + pub detailed: bool, + /// Include activation counts and license status, keyed by global license ID. + pub metadata: bool, +} + +#[derive(Debug)] +pub struct CustomerLicenses { + pub license_keys: Vec, + pub metadata: Option>, +} + +/// An unsigned listing entry. Call Key::activate or Key::get_key to verify the selected license. +/// The customer API returns dates as ISO 8601 strings. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomerLicense { + pub product_id: u64, + #[serde(alias = "ID")] + pub id: i32, + pub global_id: u64, + pub key: String, + pub created: String, + pub expires: String, + pub period: i32, + #[serde(rename = "f1")] + pub feature1: bool, + #[serde(rename = "f2")] + pub feature2: bool, + #[serde(rename = "f3")] + pub feature3: bool, + #[serde(rename = "f4")] + pub feature4: bool, + #[serde(rename = "f5")] + pub feature5: bool, + #[serde(rename = "f6")] + pub feature6: bool, + #[serde(rename = "f7")] + pub feature7: bool, + #[serde(rename = "f8")] + pub feature8: bool, + pub block: bool, + #[serde(default, deserialize_with = "nullable_string")] + pub notes: String, + pub customer: Option, + pub activated_machines: Option>, + pub data_objects: Option>, + pub max_no_of_machines: Option, + pub allowed_machines: Option, + pub trial_activation: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ListedCustomer { + pub id: u64, + pub name: Option, + pub email: Option, + pub company_name: Option, + pub created: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomerLicenseMachine { + #[serde(default, deserialize_with = "nullable_string")] + pub mid: String, + pub ip: Option, + pub time: Option, + pub friendly_name: Option, + pub floating_expires: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomerLicenseMetadata { + pub activated_machines: u32, + pub license_status: CustomerLicenseStatus, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomerLicenseStatus { + pub is_valid: bool, + /// The API returns 0 for none, 1 for expired, and 2 for blocked. + pub reason_for_invalidity: i32, + pub trial: bool, + pub time_limited: bool, + pub time_left: i32, +} diff --git a/src/models/requests.rs b/src/models/requests.rs new file mode 100644 index 0000000..fc0ab8b --- /dev/null +++ b/src/models/requests.rs @@ -0,0 +1,67 @@ +use serde::Serialize; + +/// Selects the registration to release when deactivating a license. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DeactivationMode { + NodeLocked, + Floating, +} + +/// Initial values for a new data object. +#[derive(Clone, Debug, Default, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct NewDataObject<'a> { + pub name: &'a str, + pub string_value: &'a str, + pub int_value: i32, + pub check_for_duplicates: bool, +} + +/// Owner used by the administrative add and list endpoints. +#[derive(Clone, Copy, Debug)] +pub enum DataObjectOwner { + Account, + Product(u64), + /// The license's global ID ([`LicenseKey::global_id`](super::LicenseKey::global_id)). + License(u64), +} + +/// An object ID or a unique name on the license. Methods also accept a `u64` or `&str` directly. +#[derive(Clone, Copy, Debug, Serialize)] +pub enum DataObjectSelector<'a> { + Id(u64), + Name(&'a str), +} + +impl From for DataObjectSelector<'_> { + fn from(id: u64) -> Self { + Self::Id(id) + } +} + +impl<'a> From<&'a str> for DataObjectSelector<'a> { + fn from(name: &'a str) -> Self { + Self::Name(name) + } +} + +/// A single usage event. Supply both `product_id` and `key` to associate it with +/// a license. Standalone events can omit both. +#[derive(Clone, Debug, Default, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct RegisterEvent<'a> { + pub product_id: Option, + pub key: Option<&'a str>, + pub machine_code: Option<&'a str>, + #[serde(skip_serializing_if = "str::is_empty")] + pub feature_name: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + pub event_name: &'a str, + /// For a monetary event, the Web API represents 25.30 as 2530. + pub value: Option, + pub currency: Option<&'a str>, + /// Additional event data, encoded as a JSON string. + pub metadata: Option<&'a str>, + /// A non-empty GUID. Reuse it only for retries of the same occurrence. + pub client_event_id: Option<&'a str>, +} diff --git a/tests/license_files.rs b/tests/license_files.rs new file mode 100644 index 0000000..1032660 --- /dev/null +++ b/tests/license_files.rs @@ -0,0 +1,178 @@ +use std::time::{Duration, UNIX_EPOCH}; + +use base64::{Engine, engine::general_purpose::STANDARD}; +use cryptolens::{Error, KeyActivateResponse, RsaKeyValue, models::LicenseKey}; +use serde_json::{Value, json}; + +const PUBLIC_KEY: &str = include_str!("../examples/data/public-key.xml"); +const SIGNED_RESPONSE: &str = include_str!("../examples/data/license.skm"); + +fn response() -> Value { + serde_json::from_str(SIGNED_RESPONSE).unwrap() +} + +fn signed_payload() -> Value { + let bytes = STANDARD + .decode(response()["licenseKey"].as_str().unwrap()) + .unwrap(); + serde_json::from_slice(&bytes).unwrap() +} + +#[test] +fn preserves_the_original_signed_payload_across_sdk_formats() { + let original = response(); + let dotnet = json!({ + "LicenseKey": original["licenseKey"], "Signature": original["signature"], + "Result": 0, "Message": null, "Metadata": { "sample": 1 } + }); + let mut license = LicenseKey::load_from_string(PUBLIC_KEY, &dotnet.to_string(), None).unwrap(); + assert_eq!(license.id, Some(4)); + license.product_id = 1; + + let saved = license.save_as_string().unwrap(); + let envelope: Value = serde_json::from_str(&saved).unwrap(); + assert_eq!(envelope["licenseKey"], original["licenseKey"]); + assert_eq!(envelope["signature"], original["signature"]); + assert_eq!(envelope["metadata"], dotnet["Metadata"]); + let reloaded = LicenseKey::load_from_string(PUBLIC_KEY, &saved, None).unwrap(); + assert_eq!(reloaded.product_id, 3646); +} + +#[test] +fn offline_load_requires_a_successful_result_and_a_valid_signature() { + let mut saved = response(); + saved["result"] = json!(1); + saved["message"] = json!("Access denied."); + assert!( + matches!(LicenseKey::load_from_string(PUBLIC_KEY, &saved.to_string(), None), + Err(Error::Api(message)) if message == "Access denied.") + ); + + let mut saved = response(); + let mut signature = STANDARD + .decode(saved["signature"].as_str().unwrap()) + .unwrap(); + signature[0] ^= 1; + saved["signature"] = json!(STANDARD.encode(signature)); + assert!(matches!( + LicenseKey::load_from_string(PUBLIC_KEY, &saved.to_string(), None), + Err(Error::InvalidSignature) + )); + saved["signature"] = Value::Null; + assert!(matches!( + LicenseKey::load_from_string(PUBLIC_KEY, &saved.to_string(), None), + Err(Error::MissingSignature) + )); + + saved["licenseKey"] = signed_payload(); + assert!(matches!( + LicenseKey::load_from_string(PUBLIC_KEY, &saved.to_string(), None), + Err(Error::MissingSignature) + )); + let unsigned: LicenseKey = serde_json::from_value(signed_payload()).unwrap(); + assert!(matches!( + unsigned.save_as_string(), + Err(Error::MissingSignature) + )); + assert!(LicenseKey::load_from_string("invalid XML", SIGNED_RESPONSE, None).is_err()); +} + +#[test] +fn explicit_signature_check_accepts_only_the_matching_signature() { + let public_key = || RsaKeyValue::from_xml_str(PUBLIC_KEY).unwrap(); + let original = LicenseKey::load_from_string(PUBLIC_KEY, SIGNED_RESPONSE, None).unwrap(); + assert!(original.has_valid_signature(public_key()).unwrap()); + + let mut altered = response(); + let mut signature = STANDARD + .decode(altered["signature"].as_str().unwrap()) + .unwrap(); + signature[0] ^= 1; + altered["signature"] = json!(STANDARD.encode(signature)); + let unchecked: KeyActivateResponse = serde_json::from_value(altered).unwrap(); + let license = LicenseKey::try_from(unchecked).unwrap(); + assert!(!license.has_valid_signature(public_key()).unwrap()); + + let unsigned: LicenseKey = serde_json::from_value(signed_payload()).unwrap(); + assert!(!unsigned.has_valid_signature(public_key()).unwrap()); +} + +#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] +#[test] +fn machine_code_is_stable_and_is_a_lowercase_sha256_digest() { + let first = cryptolens::helpers::get_machine_code().unwrap(); + let second = cryptolens::helpers::get_machine_code().unwrap(); + assert!(first == second, "The machine code changed between calls"); + assert_eq!(first.len(), 64); + assert!( + first + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + ); +} + +#[test] +fn enforces_maximum_age_on_a_saved_response() { + assert!(matches!( + LicenseKey::load_from_string(PUBLIC_KEY, SIGNED_RESPONSE, Some(Duration::ZERO)), + Err(Error::SignatureAge) + )); +} + +#[test] +fn reads_expiry_and_finds_exact_names_in_license_data() { + let mut license = LicenseKey::load_from_string(PUBLIC_KEY, SIGNED_RESPONSE, None).unwrap(); + assert_eq!( + license + .expires_at() + .unwrap() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(), + license.expires + ); + license.expires = 0; + assert_eq!(license.expires_at().unwrap(), UNIX_EPOCH); + license.expires = u64::MAX; + assert!(license.expires_at().is_err()); + + let mut fields = signed_payload(); + fields["DataObjects"] = json!([ + {"Id": 1, "Name": "projects", "IntValue": 4, "StringValue": null}, + {"Id": 2, "Name": "projects", "IntValue": 8, "StringValue": "other"}, + {"Id": 3, "Name": null, "IntValue": 0, "StringValue": null} + ]); + let license: LicenseKey = serde_json::from_value(fields).unwrap(); + assert_eq!(license.data_object("projects").unwrap().int_value, 4); + assert!(license.data_object("Projects").is_none()); + assert!(license.data_object("missing").is_none()); +} + +#[test] +fn accepts_restricted_ids_private_ip_addresses_and_signed_data_values() { + let mut data = signed_payload(); + data["ID"] = json!(-1); + data["GlobalId"] = json!(-1); + data["ActivatedMachines"][0]["IP"] = json!(""); + data["ActivatedMachines"] + .as_array_mut() + .unwrap() + .push(Value::Null); + data["DataObjects"] = json!([{"Id":1, "Name":"offset", "StringValue":"", "IntValue":-1}]); + let license: LicenseKey = serde_json::from_value(data.clone()).unwrap(); + assert_eq!(license.id, None); + assert_eq!(license.global_id, None); + assert_eq!(license.activated_machines.len(), 2); + assert_eq!(license.activated_machines[0].ip, None); + assert_eq!(license.data_objects[0].int_value, -1); + + data["MaxNoOfMachines"] = json!(0); + data["DataObjects"] = Value::Null; + let restricted: LicenseKey = serde_json::from_value(data.clone()).unwrap(); + assert!(restricted.is_on_right_machine("289jf2afs3")); + assert!(restricted.data_objects.is_empty()); + + data["ActivatedMachines"] = Value::Null; + let unlimited: LicenseKey = serde_json::from_value(data).unwrap(); + assert!(!unlimited.is_on_right_machine("289jf2afs3")); +} diff --git a/tests/live_sample.rs b/tests/live_sample.rs new file mode 100644 index 0000000..36e4e04 --- /dev/null +++ b/tests/live_sample.rs @@ -0,0 +1,415 @@ +//! Run the full suite with `cargo test -- --include-ignored`. +//! See “Testing With a Sample License” in the README for credentials and permissions. + +use std::{env, error::Error, fs, time::Duration}; + +use cryptolens::{ + Client, KeyActivateParams, RsaKeyValue, + methods::{Analytics, Customer, Data, Key}, + models::{ + CustomerLicense, CustomerLicenseOptions, CustomerLicenses, DeactivationMode, LicenseKey, + RegisterEvent, + }, +}; +use serde::Deserialize; +use uuid::Uuid; + +#[path = "live_sample/data_objects.rs"] +mod data_objects; + +type TestResult = Result>; + +fn http_builder() -> reqwest::ClientBuilder { + reqwest::Client::builder() + .timeout(Duration::from_secs(20)) + .redirect(reqwest::redirect::Policy::none()) +} + +struct Sample { + token: String, + product_id: u64, + key: String, +} + +fn required(name: &str) -> TestResult { + env::var(name) + .ok() + .filter(|value| !value.trim().is_empty()) + .ok_or_else(|| format!("Set {name} before running this sample test").into()) +} + +impl Sample { + fn load() -> TestResult { + let token = required("CRYPTOLENS_ACCESS_TOKEN")?; + let product_id = required("CRYPTOLENS_PRODUCT_ID")? + .parse::() + .ok() + .filter(|&id| id > 0) + .ok_or("CRYPTOLENS_PRODUCT_ID must be a positive 32-bit integer")?; + Ok(Self { + token, + product_id: product_id as u64, + key: required("CRYPTOLENS_LICENSE_KEY")?, + }) + } + + fn key_client(&self) -> TestResult<(Key, String)> { + let path = required("CRYPTOLENS_PUBLIC_KEY_FILE")?; + let xml = fs::read_to_string(path) + .map_err(|err| format!("Could not read CRYPTOLENS_PUBLIC_KEY_FILE: {err}"))?; + Ok(( + Key::with_client(http_builder().try_into()?, self.token.as_str(), &xml)?, + xml, + )) + } + + fn verify_saved_license(&self, license: &LicenseKey, public_key: &str) -> TestResult { + let saved = license.save_as_string()?; + let verified = LicenseKey::load_from_string(public_key, &saved, None)?; + assert_eq!(verified.product_id, self.product_id); + if let Some(key) = verified.key { + assert!( + key.eq_ignore_ascii_case(&self.key), + "Unexpected license key" + ); + } + Ok(()) + } + + fn listed_license<'a>(&self, result: &'a CustomerLicenses) -> TestResult<&'a CustomerLicense> { + result + .license_keys + .iter() + .find(|license| { + license.product_id == self.product_id && license.key.eq_ignore_ascii_case(&self.key) + }) + .ok_or_else(|| { + "The customer lookup did not return the sample product and license key".into() + }) + } +} + +#[tokio::test] +#[ignore = "requires a sample license and GetKey permission"] +async fn get_key() -> TestResult { + let sample = Sample::load()?; + let (keys, xml) = sample.key_client()?; + let license = keys.get_key(sample.product_id, &sample.key).await?; + sample.verify_saved_license(&license, &xml) +} + +#[tokio::test] +#[ignore = "registers and releases a test device with Activate, Deactivate, and GetKey permissions"] +async fn activate() -> TestResult { + let sample = Sample::load()?; + let (keys, xml) = sample.key_client()?; + let before = keys.get_key(sample.product_id, &sample.key).await?; + if before.max_no_of_machines.unwrap_or(0) <= 0 { + return Err( + "Deactivation requires a node-locked sample with a visible, positive machine limit" + .into(), + ); + } + + let device = format!("rust-sdk-{}", Uuid::new_v4()); + println!("Sample device for this activation and release: {device}"); + let activation = match keys + .activate(sample.product_id, &sample.key, Some(&device)) + .await + { + Err(error @ cryptolens::Error::Api(_)) => return Err(error.into()), + result => result, + }; + // Check that GetKey exposes this device before using its absence as proof of release. + let visible = if activation.is_ok() { + keys.get_key(sample.product_id, &sample.key) + .await + .map(|license| license.is_on_right_machine(&device)) + } else { + Ok(false) + }; + // Release the generated device even if reading the activation or its confirmation failed. + let release = keys + .deactivate( + sample.product_id, + &sample.key, + &device, + DeactivationMode::NodeLocked, + ) + .await; + let license = activation?; + release?; + sample.verify_saved_license(&license, &xml)?; + assert!( + visible?, + "GetKey did not show the test device before deactivation" + ); + assert!( + license.is_on_right_machine(&device), + "The signed activation did not list the test device" + ); + + let after = keys.get_key(sample.product_id, &sample.key).await?; + assert!( + !after.is_on_right_machine(&device), + "The test device is still registered after deactivation" + ); + Ok(()) +} + +#[tokio::test] +#[ignore = "checks out and releases a short floating seat using the older activation method"] +async fn legacy_activation_and_floating_release() -> TestResult { + let sample = Sample::load()?; + let (keys, xml) = sample.key_client()?; + let before = keys.get_key(sample.product_id, &sample.key).await?; + if before.max_no_of_machines.unwrap_or(0) <= 0 { + return Err( + "The sample license must have a positive machine limit for floating seats".into(), + ); + } + + let device = format!("rust-sdk-float-{}", Uuid::new_v4().simple()); + let seat = format!("floating:{device}"); + let client = Client::try_from(http_builder())?; + let params = KeyActivateParams::builder() + .product_id(sample.product_id) + .key(&sample.key) + .machine_code(&device) + .friendly_name("Rust SDK floating test") + .floating_time_interval(120_u64) + .model_version(3_u64) + .sign(true) + .build()?; + + let activation = client.key_activate(&sample.token, params).await; + if let Err(error @ cryptolens::Error::Api(_)) = activation { + return Err(error.into()); + } + let checks: TestResult = async { + let license = activation?; + if !license.has_valid_signature(RsaKeyValue::from_xml_str(&xml)?)? + || license.product_id != sample.product_id + || !license.is_on_right_machine(&seat) + { + return Err( + "The signed activation did not confirm the floating seat for this product".into(), + ); + } + let active = keys.get_key(sample.product_id, &sample.key).await?; + if !active.is_on_right_machine(&seat) { + return Err("GetKey did not show the checked-out floating seat".into()); + } + Ok(()) + } + .await; + + keys.deactivate( + sample.product_id, + &sample.key, + &device, + DeactivationMode::Floating, + ) + .await + .map_err(|error| format!("Could not release test seat {device}: {error}"))?; + if keys + .get_key(sample.product_id, &sample.key) + .await? + .is_on_right_machine(&seat) + { + return Err(format!("GetKey still shows released test seat {device}").into()); + } + checks +} + +#[tokio::test] +#[ignore = "looks up the signed license's customer with GetKey and GetCustomerLicenses permissions"] +async fn get_customer_licenses() -> TestResult { + let sample = Sample::load()?; + let (keys, _) = sample.key_client()?; + let license = keys.get_key(sample.product_id, &sample.key).await?; + let customer = license + .customer + .ok_or("The signed sample license must include its assigned customer")?; + let result = Customer::with_client(http_builder().try_into()?, sample.token.as_str()) + .get_customer_licenses(customer.id, Default::default()) + .await?; + sample.listed_license(&result)?; + Ok(()) +} + +#[tokio::test] +#[ignore = "requires a sample customer secret and GetCustomerLicensesBySecret permission"] +async fn get_customer_licenses_by_secret() -> TestResult { + let sample = Sample::load()?; + let secret = required("CRYPTOLENS_CUSTOMER_SECRET")?; + let options = CustomerLicenseOptions { + detailed: true, + metadata: true, + }; + let result = Customer::with_client(http_builder().try_into()?, sample.token.as_str()) + .get_customer_licenses_by_secret(&secret, options) + .await?; + let license = sample.listed_license(&result)?; + assert!( + license.customer.is_some(), + "The detailed entry is missing its customer" + ); + assert!( + result + .metadata + .as_ref() + .is_some_and(|entries| entries.contains_key(&license.global_id)), + "Missing metadata for the sample license" + ); + Ok(()) +} + +#[tokio::test] +#[ignore = "requires a sample license and ListDataObjects permission"] +async fn list_data_objects() -> TestResult { + let sample = Sample::load()?; + let data = Data::with_client(http_builder().try_into()?, sample.token); + let objects = data + .list_key_data_objects(sample.product_id, &sample.key, None) + .await?; + if let Some(object) = objects.iter().find(|object| !object.name.is_empty()) { + let matching = data + .list_key_data_objects(sample.product_id, &sample.key, Some(&object.name)) + .await?; + assert!( + matching.iter().any(|candidate| candidate.id == object.id), + "Listing by name did not return the sample data object" + ); + } + Ok(()) +} + +#[tokio::test] +#[ignore = "writes and reads a sample event with RegisterEvent and GetEvents permissions"] +async fn register_event() -> TestResult { + let sample = Sample::load()?; + + let id = Uuid::new_v4().to_string(); + let metadata = serde_json::json!({ "rustSdkSample": id }).to_string(); + let event = RegisterEvent { + product_id: Some(sample.product_id), + key: Some(&sample.key), + feature_name: "Rust SDK sample", + event_name: "integration-test", + client_event_id: Some(&id), + metadata: Some(&metadata), + ..Default::default() + }; + + println!("Sample client event ID: {id}"); + let analytics = Analytics::with_client(http_builder().try_into()?, sample.token.as_str()); + analytics.register_event(&event).await?; + analytics.register_event(&event).await?; + + verify_event_history(&sample, &event).await +} + +#[tokio::test] +#[ignore = "records and reads one standalone usage event using a synthetic device ID"] +async fn register_standalone_event() -> TestResult { + let sample = Sample::load()?; + let id = Uuid::new_v4().to_string(); + let device = format!("rust-sdk-{id}"); + let metadata = serde_json::json!({ "rustSdkSample": id }).to_string(); + let event = RegisterEvent { + machine_code: Some(&device), + feature_name: "Rust SDK sample", + event_name: "standalone-integration-test", + client_event_id: Some(&id), + metadata: Some(&metadata), + ..Default::default() + }; + Analytics::with_client(http_builder().try_into()?, sample.token.as_str()) + .register_event(&event) + .await?; + verify_event_history(&sample, &event).await +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RecordedEvent { + client_event_id: String, + product_id: u64, + key: Option, + machine_code: String, + feature_name: String, + event_name: String, + metadata: String, +} + +async fn verify_event_history(sample: &Sample, event: &RegisterEvent<'_>) -> TestResult { + #[derive(Deserialize)] + struct History { + result: i32, + events: Option>, + } + + let http = http_builder().build()?; + let product_id = event.product_id.map(|id| id.to_string()); + let mut form = vec![ + ("token", sample.token.as_str()), + ( + "Metadata", + event.metadata.ok_or("Missing sample event metadata")?, + ), + ("Limit", "2"), + ]; + if let Some(product_id) = &product_id { + form.push(("ProductId", product_id.as_str())); + } + if let Some(key) = event.key { + form.push(("Key", key)); + } + + // A read replica may take a few seconds to show the committed event. + for attempt in 0..6 { + if attempt > 0 { + tokio::time::sleep(Duration::from_secs(2)).await; + } + let history: History = http + .post("https://api.cryptolens.io/api/ai/GetEvents") + .form(&form) + .send() + .await? + .error_for_status()? + .json() + .await?; + if history.result != 0 { + return Err(format!( + "GetEvents returned result {}. Check GetEvents permission and scope", + history.result + ) + .into()); + } + let records = history + .events + .ok_or("GetEvents response is missing events")?; + match records.as_slice() { + [] => continue, + [row] => { + assert_eq!(Some(row.client_event_id.as_str()), event.client_event_id); + assert_eq!(row.product_id, event.product_id.unwrap_or(0)); + assert!( + row.key + .as_deref() + .unwrap_or_default() + .eq_ignore_ascii_case(event.key.unwrap_or_default()), + "Unexpected license attribution on the event" + ); + assert_eq!(row.machine_code, event.machine_code.unwrap_or_default()); + assert_eq!(row.feature_name, event.feature_name); + assert_eq!(row.event_name, event.event_name); + assert_eq!(Some(row.metadata.as_str()), event.metadata); + return Ok(()); + } + _ => return Err("The identical retry recorded more than one sample event".into()), + } + } + Err("The registered sample event did not appear in GetEvents".into()) +} diff --git a/tests/live_sample/data_objects.rs b/tests/live_sample/data_objects.rs new file mode 100644 index 0000000..8debc26 --- /dev/null +++ b/tests/live_sample/data_objects.rs @@ -0,0 +1,173 @@ +use super::{Sample, TestResult, http_builder}; +use cryptolens::{ + DataObject, Error, Result as SdkResult, + methods::{Data, DataObjectOwner, NewDataObject}, +}; +use uuid::Uuid; + +fn check_value(objects: &[DataObject], name: &str, id: u64, number: i32, text: &str) -> TestResult { + let mut matches = objects.iter().filter(|object| object.name == name); + let object = matches + .next() + .ok_or_else(|| format!("Missing test object {name}"))?; + if matches.next().is_some() || object.id != id { + return Err(format!("Unexpected ID or duplicate name for test object {name}").into()); + } + if object.int_value != number || object.string_value != text { + return Err(format!("Read-back for {name} did not return {number} and {text:?}").into()); + } + Ok(()) +} + +fn expect_bound_rejection(result: SdkResult<()>) -> TestResult { + match result { + Err(Error::Api(message)) if message.to_ascii_lowercase().contains("bound") => Ok(()), + Err(other) => Err(other.into()), + Ok(()) => Err("The API accepted a counter update at its bound".into()), + } +} + +// The unique name also lets us recover the object if the add response was lost. +async fn finish_and_remove_object( + name: &str, + verified_id: Option, + checks: TestResult, + list: impl AsyncFn() -> SdkResult>, + remove: impl AsyncFn(u64) -> SdkResult<()>, +) -> TestResult { + let cleanup: TestResult = async { + let id = if let Some(id) = verified_id { + id + } else { + let objects = list().await?; + let mut matches = objects.iter().filter(|object| object.name == name); + let Some(object) = matches.next() else { + return Ok(()); + }; + if matches.next().is_some() { + return Err("Multiple objects matched the generated test name".into()); + } + object.id + }; + remove(id).await?; + if list() + .await? + .iter() + .any(|object| object.id == id || object.name == name) + { + return Err("The temporary object is still present after removal".into()); + } + Ok(()) + } + .await; + if let Err(error) = cleanup { + let detail = checks + .err() + .map(|e| format!(" Earlier check: {e}.")) + .unwrap_or_default(); + return Err(format!("Cleanup for {name} failed: {error}.{detail}").into()); + } + checks +} + +#[tokio::test] +#[ignore = "creates, changes, and removes a temporary object on the sample license"] +async fn key_values_and_counter_bounds() -> TestResult { + let sample = Sample::load()?; + let data = Data::with_client(http_builder().try_into()?, sample.token); + let product = sample.product_id; + let key = sample.key.as_str(); + let name = format!("rust-sdk-key-{}", Uuid::new_v4().simple()); + let list = async || data.list_key_data_objects(product, key, Some(&name)).await; + let object = NewDataObject { + name: &name, + int_value: 1, + string_value: "created", + check_for_duplicates: true, + }; + let created = data.add_data_object_to_key(product, key, object).await; + if let Err(error @ Error::Api(_)) = created { + return Err(error.into()); + } + let mut verified_id = None; + let checks = async { + let id = created?; + let check = async |number, text: &str| check_value(&list().await?, &name, id, number, text); + check(1, "created").await?; + verified_id = Some(id); + data.set_int_value_to_key(product, key, id, 2).await?; + check(2, "created").await?; + data.set_string_value_to_key(product, key, name.as_str(), "updated & verified") + .await?; + check(2, "updated & verified").await?; + + data.increment_int_value_to_key(product, key, id, 1, Some(3)) + .await?; + check(3, "updated & verified").await?; + expect_bound_rejection( + data.increment_int_value_to_key(product, key, id, 1, Some(3)) + .await, + )?; + check(3, "updated & verified").await?; + + data.decrement_int_value_to_key(product, key, name.as_str(), 1, Some(2)) + .await?; + check(2, "updated & verified").await?; + expect_bound_rejection( + data.decrement_int_value_to_key(product, key, id, 1, Some(2)) + .await, + )?; + check(2, "updated & verified").await + } + .await; + finish_and_remove_object(&name, verified_id, checks, list, async |id| { + data.remove_data_object_to_key(product, key, id).await + }) + .await +} + +#[tokio::test] +#[ignore = "tests general data-object methods on a temporary object owned by the sample license"] +async fn general_methods_on_sample_license() -> TestResult { + let sample = Sample::load()?; + let (keys, _) = sample.key_client()?; + let license = keys.get_key(sample.product_id, &sample.key).await?; + let owner = DataObjectOwner::License( + license + .global_id + .ok_or("GetKey must expose the global license ID")?, + ); + let data = Data::with_client(http_builder().try_into()?, sample.token); + let name = format!("rust-sdk-owner-{}", Uuid::new_v4().simple()); + let list = async || data.list_data_objects(owner, Some(&name)).await; + let object = NewDataObject { + name: &name, + int_value: 1, + string_value: "created", + check_for_duplicates: true, + }; + let created = data.add_data_object(owner, object).await; + if let Err(error @ Error::Api(_)) = created { + return Err(error.into()); + } + let mut verified_id = None; + let checks = async { + let id = created?; + check_value(&list().await?, &name, id, 1, "created")?; + verified_id = Some(id); + data.set_int_value(id, -3).await?; + check_value(&list().await?, &name, id, -3, "created")?; + data.set_string_value(id, "updated & verified").await?; + check_value(&list().await?, &name, id, -3, "updated & verified")?; + + let by_key = data + .list_key_data_objects(sample.product_id, &sample.key, Some(&name)) + .await?; + check_value(&by_key, &name, id, -3, "updated & verified") + } + .await; + finish_and_remove_object(&name, verified_id, checks, list, async |id| { + data.remove_data_object(id).await + }) + .await +}