PermitPlane Docs
All docs pages

Add licensing to a Rust app

At the end, your Rust app activates a licence key and unlocks its features offline.

From your product page in PermitPlane (app.permitplane.com/ops/vendor/), click Download permitplane.json and Create test key.

1. Install

Download permitplane-core-0.1.0.crate, check it against the sha256 in manifest.json and unpack it next to your project:

Shell
sha256sum permitplane-core-0.1.0.crate
tar xzf permitplane-core-0.1.0.crate

Add it to Cargo.toml:

TOML
[dependencies.permitplane-core]
path = "permitplane-core-0.1.0"
features = ["default-host"]

2. Activate a licence key

Create the client with the built-in host and activate once:

Rust
use permitplane_core::{client::Client, DefaultHost};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = std::fs::read_to_string("permitplane.json")?;
    // Loads the saved state, so a restart needs no request.
    let host = Box::new(DefaultHost::user()?);
    let mut client = Client::new(&config, host)?;

    if client.status().as_str() == "free" {
        // paste your test key here; in your real app, ask the user for it
        client.activate_with_key(
            "PP-7KQ4M-X9T2H-B6WRN-3FJ8D",
            Some("Office PC"),
        )?;
    }
    // ... unlock features here (step 3) ...
    Ok(())
}

3. Unlock features in your app

Turn parts of your app on or off based on what the customer's licence includes. The check reads the signed grant and works offline up to your policy's offline days.

Rust
if client.has_feature("export") {
    enable_export();
} else {
    show_upgrade_offer();
}
Rust
let seats = client.feature_value("seats");
// seats.unlimited, or seats.value

let status = client.status().as_str();
// "free", "trial", "paid", ...
let json = client.status_json();
// {"status":"paid","message":"...","activation_id":"...",...}

4. Keep it current

  • Call client.refresh() on start and every hour.
  • Call client.persist_observations() now and then and before exit.
  • Call client.deactivate() to release the device.

Errors

Every call that can fail returns Result<_, ClientError>. e.code() gives a short name.

ErrorWhat to do
ClientError::InvalidLicenseKeyThe key is mistyped. Ask the user to check it.
Api with code invalid_license_keyThe key is unknown or revoked. Ask for the key from the purchase email.
Api with code device_limitEvery device slot is taken. Deactivate another device first.
Api with code license_expired, license_suspended or license_revokedShow a renew or contact link.
TransportThe network failed. Retry later. Unlocked features keep working.
Rust
use permitplane_core::client::ClientError;

match client.refresh() {
    Ok(()) => {}
    Err(ClientError::Api { code, .. }) => eprintln!("{code}"),
    Err(ClientError::Transport(_)) => { /* retry later */ }
    Err(e) => eprintln!("{}", e.code()),
}

Going further

Reference

Install notes

  • Downloads need no sign-in.
  • On Windows, check a file with Get-FileHash -Algorithm SHA256 <file>. Windows 10 and later include tar.
  • The crate is safe Rust. Only the Windows code of the default-host feature calls system libraries.

Built-in host

DefaultHost::user() gives the client:

  • The saved state and a P-256 installation key, in files protected with DPAPI.
  • The folder %LOCALAPPDATA%\PermitPlane. Files are named per product.
  • A monotonic clock that includes sleep, plus the boot id.
  • WinHTTP with the system proxy and certificate store. It sends HTTPS only, follows no redirects and accepts at most 1 MiB.

For a folder every user of the machine shares, use DefaultHost::new(Scope::Machine, None) with permitplane_core::default_host::Scope. It uses %ProgramData%\PermitPlane, open only to SYSTEM, Administrators and the creating user. Pass Some(dir) for your own folder.

In an installer, create a folder per product first and pass it as dir:

PowerShell
$dir = "$env:ProgramData\PermitPlane\Acme\Widget"
New-Item -ItemType Directory -Force $dir | Out-Null
icacls $dir /inheritance:r `
  /grant:r "*S-1-5-18:(OI)(CI)F" "*S-1-5-32-544:(OI)(CI)F"
  • A folder or file that is a link, or that other accounts can open, fails with HostError.

On Linux and macOS, use your own host.

Use your own storage or HTTP

Implement permitplane_core::client::Host and pass it to Client::new. The host must be Send.

Rust
use permitplane_core::client::{
    Client, Host, HostError, HttpRequest, HttpResponse,
};
use permitplane_core::{MonotonicSample, SignerError};

struct MyHost;

impl Host for MyHost {
    // Load saved licence state; Ok(None) when there is none.
    fn state_load(&self) -> Result<Option<String>, HostError> {
        todo!()
    }
    // Save licence state in protected storage.
    fn state_save(&self, _state: &str) -> Result<(), HostError> {
        todo!()
    }
    // Delete the saved state.
    fn state_clear(&self) -> Result<(), HostError> {
        todo!()
    }
    // Create or load this device's P-256 key; return x then y.
    fn key_init(&self, _ns: &str) -> Result<[u8; 64], HostError> {
        todo!()
    }
    // Sign requests with this device's private key: r then s.
    fn sign_digest(
        &self,
        _digest: &[u8; 32],
    ) -> Result<[u8; 64], SignerError> {
        todo!()
    }
    // Monotonic time, so clock changes can't extend a licence.
    fn observe(&self) -> Result<MonotonicSample, HostError> {
        todo!()
    }
    // Send one HTTPS request; never follow redirects.
    fn http_send(
        &self,
        _request: &HttpRequest,
    ) -> Result<HttpResponse, HostError> {
        todo!()
    }
}

let client = Client::new(&config, Box::new(MyHost))?;
  • The state holds a bearer installation token and the signed grant.
  • Set confident: false in the sample if your clock skips suspend time or has no boot id.
  • Return the server's nonce response header and a numeric Retry-After in the HttpResponse.
  • Bodies larger than MAX_BODY (1 MiB) are rejected.
  • The client adds the request proof, the nonce retry and the idempotency key.
  • It calls only the PermitPlane licensing endpoints on your origin.

Status values

client.status() returns Free, Trial, Paid, OnlineRequired, Expired, RecoveryRequired or SeatUnavailable.

  • After a refresh, a suspended, expired or revoked licence shows in the status.
  • A revoked or released activation also clears the saved state.
  • client.last_error_json() returns {"code":...,"http_status":...,"message":...,"retry_after":...}.

Threading

  • Calls take &mut self. To share one client between threads, wrap it in a Mutex.
  • A host method must not call into the same client.

Floating seats

A floating licence holds a seat as a lease. The client has no timers, so you renew the lease yourself.

Rust
// None = online lease; Some(1..=504) = offline borrow, in hours
if client.checkout_seat(None).is_ok() {
    // status_json(): "lease":{"kind":"online","ttl_seconds":598},"heartbeat_in_seconds":299
    // From your timer, heartbeat_in_seconds after reading the status:
    let _ = client.renew_seat();
}
// Give the seat back early. A borrow cannot be returned.
let _ = client.release_seat();
  • No free seat: checkout_seat fails with Api and the code seats_exhausted.
  • Try again after e.retry_after() seconds.
  • seats_exhausted and lease_required set the status to SeatUnavailable.
  • The next successful checkout sets it back to Paid.

Offline activation

Rust
use permitplane_core::client::OfflineKind;

let request = client
    .create_offline_request(OfflineKind::Activate, Some("Lab PC"))
    .expect("offline request");
// Carry the request to the vendor console. Bring the response back.
client.import_offline_response(&response).expect("import");
  • The client accepts only the response to its pending request.
  • The response must match this installation key.
  • Rejections: request (another request), installation (another machine), import_expired (too late).
  • A rejected file stores nothing.
  • OfflineKind::Deactivate ends local rights at once. Its file frees the seat when the vendor processes it.

Good to know

  • The client never stores the licence key.
  • You can safely retry an activation with the same key and device name after a lost response.
  • persist_observations saves the clock high-water mark.
  • deactivate also clears the local state.
  • For backend checks, permitplane_core::verify_grant verifies a signed grant on its own.
  • Never enable the test-signer feature in a product.