Developer guide

U.S. CSL API in Rust: screening and error handling

Build U.S. CSL screening in Rust with a complete HTTP example, explicit source selection, idempotency, safe failures, and review handoffs.

On this page

What this Rust integration does

The U.S. Consolidated Screening List combines several export-related screening sources. Its component lists have different purposes and implications. A CSL result should not be presented as a uniform OFAC designation.

The client submits a subject, validates the response, and prints only the screening ID, status, and candidate count. It does not approve a customer, resolve an identity, or make a legal decision. A nonzero exit leaves the local operation incomplete.

Prepare the runtime and a synthetic request

Use a maintained Rust toolchain with Cargo. Save the client as src/main.rs and use the Cargo.toml shown below. This is a blocking CLI or worker example, not a function to run directly inside an async executor task.

Save the following as request.json. Mira Calder is an invented subject and sandbox@1 uses synthetic fixtures, not a current production sanctions search. Set SANCTIONSKIT_API_KEY to your test key in the process environment. Set SCREENING_OPERATION_ID to a new persistent identifier for this operation, and reuse it only for an unchanged retry.

{
  "subject": {
    "name": "Mira Calder",
    "entityType": "person",
    "birthDate": "1984"
  },
  "package": "sandbox@1",
  "retention": "standard"
}

Add the project configuration

Save this as Cargo.toml. These dependencies are for the standalone tutorial, not dependencies to add to SanctionsKit’s website build. Review and lock them under your own maintenance process.

[package]
name = "sanctions-screen"
version = "0.1.0"
edition = "2021"

[dependencies]
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] }
serde_json = "1"

Send the request and validate the result

Save the client as src/main.rs. The endpoint is fixed to SanctionsKit’s HTTPS API. The example rejects redirects, requires explicit authorization before using a live key, and does not retry automatically. Production integrations should preserve the operation state before the first network call.

// Trusted CLI/backend worker. Do not run blocking I/O inside an async executor task.
use reqwest::{blocking::Client, redirect::Policy};
use serde_json::{json, Value};
use std::{env, error::Error, fs, io::Read, time::Duration};

fn run() -> Result<(), Box<dyn Error>> {
    let key = env::var("SANCTIONSKIT_API_KEY")?;
    let operation = env::var("SCREENING_OPERATION_ID")?;
    if operation.is_empty() { return Err("missing operation ID".into()); }
    if !key.starts_with("sk_test_") && !(key.starts_with("sk_live_") && env::var("ALLOW_LIVE_SCREENING").ok().as_deref() == Some("yes")) {
        return Err("live operation not explicitly authorized".into());
    }
    let path = env::args().nth(1).unwrap_or_else(|| "../request.sandbox.json".to_owned());
    let raw = fs::read(path)?;
    if raw.len() > 65_536 { return Err("request file exceeds 64 KiB".into()); }
    let body: Value = serde_json::from_slice(&raw)?;
    if !body.is_object() || body.get("subject").is_none() || body.get("sources").is_some() == body.get("package").is_some() {
        return Err("invalid request object".into());
    }
    let client = Client::builder().connect_timeout(Duration::from_secs(10))
        .timeout(Duration::from_secs(25)).redirect(Policy::none()).build()?;
    let response = client.post("https://www.sanctionskit.com/api/v1/screenings")
        .bearer_auth(&key).header("Idempotency-Key", operation).json(&body).send()?;
    let status_code = response.status();
    let limit = 8 * 1024 * 1024;
    let mut payload = Vec::new();
    response.take((limit + 1) as u64).read_to_end(&mut payload)?;
    if payload.len() > limit { return Err("oversized response".into()); }
    if !status_code.is_success() { return Err("screening HTTP request incomplete".into()); }
    let envelope: Value = serde_json::from_slice(&payload)?;
    let data = envelope.get("data").ok_or("missing response data")?;
    let id = data.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or("missing screening ID")?;
    let status = data.get("status").and_then(Value::as_str).ok_or("missing screening status")?;
    let matches = data.get("matches").and_then(Value::as_array).ok_or("missing matches array")?;
    if !["potential_match", "no_match"].contains(&status) ||
        (status == "no_match" && !matches.is_empty()) || (status == "potential_match" && matches.is_empty()) {
        return Err("inconsistent screening response".into());
    }
    println!("{}", json!({"id":id,"status":status,"candidateCount":matches.len()}));
    Ok(())
}
fn main() {
    if run().is_err() {
        // Do not print parser errors, submitted identity, or the raw response.
        eprintln!("Screening incomplete. Check the operation before retrying.");
        std::process::exit(1);
    }
}

Run the client

Run this from the directory containing request.json and the project files. Keep the API key out of committed files and shell tracing. The tutorial’s request-file limit is 64 KiB and its response parsing limit is 8 MiB; these are client safeguards, not claims about API service limits.

Use Result to carry failures rather than returning a synthetic no-match value. Configure reqwest with TLS, deadlines, and redirect rejection. Validate serde_json Value types before accessing fields. In an async application, use the async client or isolate this blocking work appropriately.

cargo run -- request.json

Change to the required production coverage

The documented SanctionsKit identifier is us-csl. Confirm the current coverage and preserve each returned record’s underlying list identity. Separate-source overlap can occur when a portfolio also selects other U.S. lists; retain provenance rather than silently merging the evidence.

For an authorized production operation, replace the package field with the sources array shown below, supply the actual lawfully held subject details, use a live key, and set ALLOW_LIVE_SCREENING=yes. Keep the complete request in request.json and create a new operation ID. Do not send both sources and package. The fragment below is a coverage change, not a complete request.

{
  "sources": [
    "us-csl"
  ]
}

Preserve the source details a reviewer needs

Keep the component authority, list identity, record reference, and restriction context available to the trade reviewer. Screening a party does not classify goods, determine end use, establish a license requirement, or replace a broader export-control assessment.

Retain the screening ID with your internal subject reference. Retrieve the complete evidence through the documented retained-result workflow when authorized; the console summary deliberately does not print raw identity details. A later analyst decision must not overwrite the original screening outcome.

Handle failures and test the source-specific edge cases

Treat HTTP errors, timeouts, malformed JSON, missing fields, unknown statuses, and unavailable required coverage as incomplete checks. A 401 or 403 needs credential or scope correction. A 409 needs idempotency-conflict handling. A 429 needs its specific rate-limit or usage-cap treatment; it is not a no-match result.

Test organization subjects and candidates from different component lists. Confirm that the application does not transform every CSL candidate into an SDN finding, and that it can retain separate records with similar names from different authorities.

Exercise missing fields and type mismatches without unwrap-based fallback values. Test that a transport error returns Err and that the caller cannot interpret Err as a cleared customer.

  • Verify both valid result states and inconsistent status/matches combinations.
  • Retry an accepted operation only with its original key and unchanged payload.
  • Keep missing identity facts unknown instead of inventing contradictory values.
  • Route potential matches into review before the separate business decision.
  • Keep secrets, submitted names, and raw error bodies out of routine logs.

Official references