Clavem

How to validate a license key in a Rust app

POST the key and the saved instance id to /v1/licenses/validate with ureq, with http_status_as_error turned off so a 404 or 429 keeps its body and headers. Map the reply to an enum, store the key with the keyring crate, and fall back to the saved token when there is no answer.

The calls are the same in every language. What changes is how each language fails. In Rust the questions are which HTTP crate to use, how its errors are shaped, and what to do when the operating system has no credential store. This page covers the online validate call; the signed-token fallback is in offline verification in Rust. A Tauri app that wants the same logic behind commands has its own page: license key validation in Tauri.

# Cargo.toml
ureq = { version = "3", features = ["json"] }
serde_json = "1"
keyring = { version = "3", features = ["apple-native", "windows-native", "sync-secret-service"] }

A client that returns an outcome

The code was built with ureq 3.5 and keyring 3.6. Outcome is the only type the rest of the app sees:

use serde_json::{json, Value};
use std::time::Duration;

#[derive(Debug)]
pub enum Outcome {
    Valid { token: String },
    /// 200 with valid: false. Expired or disabled. Keep the key: a renewal can revive it.
    NotValid { reason: String, token: Option<String> },
    /// 404: unknown key, or this device's activation is gone.
    Unknown { reason: String },
    /// Offline, timeout, 429, 5xx or an unreadable reply. Not a verdict on the license.
    NoAnswer { retry_after: Option<Duration> },
}

pub struct Reply { pub status: u16, pub body: Value, pub retry_after: Option<Duration> }

pub struct Client { base: String, agent: ureq::Agent }

impl Client {
    pub fn new(base: &str) -> Self {
        let agent: ureq::Agent = ureq::Agent::config_builder()
            .timeout_global(Some(Duration::from_secs(8)))
            .http_status_as_error(false) // keep the body and headers of 4xx and 5xx replies
            .user_agent("Inkwell/3.2")
            .build()
            .into();
        Self { base: base.trim_end_matches('/').to_string(), agent }
    }

    /// POST /v1/licenses/<action>. Err means there was no HTTP answer at all.
    pub fn post(&self, action: &str, body: Value) -> Result<Reply, ureq::Error> {
        let mut res = self.agent.post(&format!("{}/v1/licenses/{action}", self.base)).send_json(body)?;
        let retry_after = res.headers().get("retry-after")
            .and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok()).map(Duration::from_secs);
        let status = res.status().as_u16();
        let body = res.body_mut().read_json::<Value>().unwrap_or(Value::Null);
        Ok(Reply { status, body, retry_after })
    }

    pub fn validate(&self, key: &str, instance_id: Option<&str>) -> Outcome {
        let mut body = json!({ "license_key": key });
        if let Some(id) = instance_id { body["instance_id"] = json!(id); }
        let Ok(reply) = self.post("validate", body) else { return Outcome::NoAnswer { retry_after: None } };

        let message = reply.body["error"].as_str().unwrap_or("This license is not valid.").to_string();
        match reply.status {
            200 => match (reply.body["valid"].as_bool(), reply.body["token"].as_str().map(str::to_string)) {
                (Some(true), Some(token)) => Outcome::Valid { token },
                (Some(_), token) => Outcome::NotValid { reason: message, token },
                (None, _) => Outcome::NoAnswer { retry_after: None },
            },
            404 => Outcome::Unknown { reason: message },
            429 | 503 => Outcome::NoAnswer { retry_after: reply.retry_after },
            _ => Outcome::NoAnswer { retry_after: None },
        }
    }
}

What each answer means

Reply Outcome App action
200, valid: true Valid Save the new token, which restarts the 14-day window.
200, valid: false NotValid Save the token, show reason, keep the key.
404 Unknown Delete the saved license and ask for the key again.
429, 503 NoAnswer Use the saved token. Retry after retry_after.
Timeout, DNS failure NoAnswer Same, with no wait hint.
400 NoAnswer A bug in your request. Log it, do not blame the customer.

A 400 looks like this, captured from the live API with an empty body:

{"valid":false,"error":"license_key: Invalid input: expected string, received undefined"}

When there is no answer

A 503 carries Retry-After: 5 and a 429 carries Retry-After: 60. Retry once for the short wait. Never sit through the long one at launch: use the saved token and try again later.

impl Client {
    pub fn validate_with_retry(&self, key: &str, instance_id: Option<&str>) -> Outcome {
        let outcome = self.validate(key, instance_id);
        if let Outcome::NoAnswer { retry_after: Some(wait) } = outcome {
            if wait <= Duration::from_secs(5) {
                std::thread::sleep(wait);
                return self.validate(key, instance_id);
            }
        }
        outcome
    }
}

Run this on a worker thread so the window appears at once.

Real output

The client run against the live API with the demo key, plus a local stub for the limit cases:

demo key: Valid(token sgt1.eyJ2Ijo...)
unknown key: Unknown { reason: "license_key not found." }
demo key, unknown instance: Unknown { reason: "instance_id not found." }
stub TEST-429: NoAnswer { retry_after: Some(60s) }
stub TEST-503, one retry: NoAnswer { retry_after: Some(5s) } after 5.0 s

Storing the key

use keyring::{Entry, Error};

pub fn set(service: &str, name: &str, value: &str) -> keyring::Result<()> {
    Entry::new(service, name)?.set_password(value)
}

/// Ok(None) when nothing is stored. Other errors, such as a locked keyring, are returned.
pub fn get(service: &str, name: &str) -> keyring::Result<Option<String>> {
    match Entry::new(service, name)?.get_password() {
        Ok(v) => Ok(Some(v)),
        Err(Error::NoEntry) => Ok(None),
        Err(e) => Err(e),
    }
}

Keep one entry per value: key, instance id and token. On macOS this is the Keychain, on Windows the Credential Manager, on Linux the Secret Service. A Linux server, a container or an SSH session usually has none, and get_password returns a platform error rather than NoEntry. Decide what that means for your app before you ship: refuse to run, or fall back to a file in the config directory with 0600 permissions and say so in your docs.

Pitfalls in Rust

  • ureq 3 turns 4xx and 5xx into errors by default, and the error holds only the status. Set http_status_as_error(false) or you lose the 429 Retry-After and the 404 message.
  • timeout_global includes reading the body. It is end-to-end, which is right for a 2 KB validate reply and wrong for a download. See software updates in Rust.
  • ureq blocks. Inside Tokio, wrap it in spawn_blocking, or use reqwest.
  • Enable the keyring features you ship. Each platform store is compiled in only when its feature is on. Run a release build once and confirm a value survives a restart.
  • Do not retry a 429 in a loop. The sample retries once for a 503 (Retry-After: 5) and never for the 60 seconds a 429 asks for.

Doing this with Clavem

The License API needs no secret, so your binary holds nothing sensitive. Plan limits never block validation. The statuses and fields are in the API reference. Seats come from device activation, and the offline path uses the token that every valid and NotValid reply returns.

Questions

Which HTTP crate should a Rust desktop app use for license checks?

ureq is small and blocking, which suits a CLI or a launch-time check on a worker thread. reqwest suits an app that already runs Tokio. Both work, because the License API takes plain JSON POST requests.

Why does ureq return an error for a 404 from the License API?

In ureq 3, 4xx and 5xx statuses become errors by default, and the error does not carry the JSON body. Call http_status_as_error(false) on the agent config and read the status yourself.

Where should a Rust app keep the license key?

In the operating system's credential store through the keyring crate. Enable the platform features in Cargo.toml, and handle the case where no secure store is available, for example a Linux server without a Secret Service.

Sources

  1. ureq 3 ConfigBuilder, timeout_global and http_status_as_error (checked November 2026)
  2. keyring crate documentation, credential store features (checked November 2026)