OpenTDF-RS
A Rust implementation of the OpenTDF (Trusted Data Format) specification, providing data-centric security that travels with the data.
Overview
OpenTDF-RS enables cryptographic binding of access policies directly to data objects, supporting a Zero Trust security model with continuous verification. This library allows secure data sharing across organizations and industries.
Terminology
- TDF (Trusted Data Format): the format — a ZIP archive holding
manifest.jsonplus an encrypted payload (spec version 4.3.0). "TDF3" is a legacy name for this same ZIP-based format and does not appear in the current spec. - OpenTDF: the project (spec repo, platform, SDKs), sponsored and maintained by Virtru, that publishes the JSON-based TDF specification. The spec's own schema README also uses "OpenTDF" loosely as the name of the ZIP-based format.
- ZTDF (Zero Trust Data Format): a profile of TDF for Five Eyes / ACP 240 use that mandates specific assertions; its detailed spec is maintained outside opentdf/spec. Caveat: the platform CLI (
otdfctl encrypt --tdf-type) defaults toztdfand treatstdf3as an alias for it, so in platform tooling both names simply mean the ZIP-based TDF. - NanoTDF: a compact binary encoding. It was removed from opentdf/spec (PR #63) and opentdf/platform (PR #3013) in January 2026, but remains supported in opentdf-rs.
- TDF-JSON: this crate's own inline-payload JSON container for JSON-RPC protocols (
src/jsonrpc.rs, container version1.0.0; see docs/ZTDF_JSON.md). It is not ZTDF. - TDF-CBOR: this crate's own inline-payload CBOR container (
src/tdf_cbor.rs). It is not ZTDF.
Features
- TDF Archive Creation and Reading
- Cryptographic Operations (AES-256-GCM encryption)
- Policy Binding through HMAC-SHA256
- Streaming Operations for Efficient Data Handling
- Attribute-Based Access Control (ABAC): Fine-grained access control using attributes
- Hierarchical Attributes: Support for attributes with inheritance relationships
- Time-Based Constraints: Policies with validity periods
- Logical Operators: AND, OR, NOT combinations for complex policies
- Comprehensive Audit Logging: Detailed records of access attempts and attribute evaluation
- KAS (Key Access Service) Integration: Full rewrap protocol support for production deployments
- MCP Server with KAS Support: AI agents can decrypt TDF files using KAS
Attribute-Based Access Control (ABAC)
OpenTDF-RS implements ABAC to provide fine-grained access control that is cryptographically bound to protected data.
graph LR
A[User Request] --> B{Evaluate Policy}
B -->|Attributes Match| C[Grant Access]
B -->|Attributes Don't Match| D[Deny Access]
C --> E[Decrypt Data]
D --> F[Log Denial]
style A fill:#e1f5ff
style B fill:#fff4e6
style C fill:#d4edda
style D fill:#f8d7da
style E fill:#d4edda
style F fill:#f8d7da
Core Components
AttributeIdentifier
Represents a uniquely identifiable attribute with namespace and name:
// Create from string in "namespace:name" format
let attr_id = from_string?;
// Or create directly
let attr_id = AttributeIdentifier ;
AttributeValue
Supports multiple data types for flexible attribute representation:
// String value
let value = String;
// Numeric value
let value = Number;
// Boolean value
let value = Boolean;
// Date/time value
let value = DateTime;
// Array values
let value = StringArray;
let value = NumberArray;
Operators
Rich set of comparison operators for attribute evaluation:
| Operator | Description | Example |
|---|---|---|
| Equals | Exact match | department == "ENGINEERING" |
| NotEquals | Negated match | department != "FINANCE" |
| GreaterThan | Numeric comparison | age > 21 |
| GreaterThanOrEqual | Numeric comparison | priority >= 5 |
| LessThan | Numeric comparison | risk < 3 |
| LessThanOrEqual | Numeric comparison | level <= 4 |
| Contains | String contains | name contains "Admin" |
| In | Value in array | department in ["HR", "LEGAL"] |
| AllOf | All array values present | certifications allof ["ISO", "SOC2"] |
| AnyOf | Any array values present | skills anyof ["Rust", "C++"] |
| NotIn | Value not in array | restricted_country notin ["US", "EU"] |
| MinimumOf | Hierarchical minimum | clearance minimumof "SECRET" |
| MaximumOf | Hierarchical maximum | clearance maximumof "TOP_SECRET" |
| Present | Attribute exists | employee_id present |
| NotPresent | Attribute doesn't exist | terminated notpresent |
AttributePolicy
Build complex policy expressions with logical operators:
// Simple condition
let is_executive = condition;
// Logical AND
let and_policy = and;
// Logical OR
let or_policy = or;
// Logical NOT (using operator overloading)
let not_policy = !condition1;
// Complex nested policy
let complex_policy = or;
Policy Structure
Complete policy with time constraints and dissemination:
// Create policy with attribute conditions and recipients
let policy = Policy ;
ABAC Integration with TDF
The new simplified API makes ABAC policy binding effortless:
use ;
use HashMap;
// 1. Create policy with attribute conditions
let clearance = condition;
let department = condition;
// Combine with logical AND
let combined_policy = and;
// Create full policy
let policy = new;
// 2. Encrypt with ABAC policy - just 4 lines!
encrypt
.kas_url
.policy
.to_file?;
// 3. Later: Evaluate access based on user attributes
let user_attrs = from;
let access_granted = combined_policy.evaluate?;
assert!;
Common Policy Patterns
Role-Based Restrictions
// Require specific role
let role_policy = condition;
Multi-Department Access
// Allow access for multiple departments
let dept_policy = condition;
Clearance Level with Time Restriction
// Require minimum clearance and time-bound access
let clearance_policy = condition;
let policy = Policy ;
Location and Network Restrictions
// Require specific location AND secure network
let location_policy = condition;
let network_policy = condition;
let security_policy = and;
Exclude Temporary Contractors
// Employees only (NOT contractors)
let contractor_check = condition;
let employees_only = !contractor_check;
KAS (Key Access Service) Integration
OpenTDF-RS includes full support for the KAS v2 rewrap protocol, enabling production-ready TDF decryption with centralized key management and access control.
Overview
The KAS protocol allows:
- Centralized key management: KAS securely stores and manages encryption keys
- Access control enforcement: KAS validates policies and user attributes before releasing keys
- Audit logging: All key access attempts are logged for compliance
- Zero Trust: Keys are never stored with encrypted data
Protocol Flow
1. Client generates ephemeral EC key pair (P-256)
2. Client builds rewrap request with TDF manifest
3. Client signs request with JWT (ES256)
4. Client POSTs to KAS /kas.AccessService/Rewrap (ConnectRPC) endpoint
5. KAS validates policy and user attributes
6. KAS returns wrapped key + session public key
7. Client unwraps key: ECDH → HKDF → AES-GCM decrypt
8. Client decrypts TDF payload
Basic Usage
The KAS client is enabled by default:
[]
= "0.16"
Creating a KAS Client (v0.13+)
KasClient::new accepts an &OpentdfConfiguration rather than a raw URL string.
use KasClient;
use ;
// Discovery (recommended): reads /.well-known/opentdf-configuration from the platform
let http = new;
let cfg = fetch_well_known.await?;
let kas = new?;
// Direct (skip discovery): build config from a known KAS URL
let cfg = for_kas_connect;
let kas = new?;
Decrypt TDF with KAS
use ;
use OpentdfConfiguration;
async
Manual Decryption
For more control over the decryption process:
use ;
use OpentdfConfiguration;
async
Agent caller key (DPoP)
An agent whose access token names its own key in cnf rewraps with proof of possession:
// Runs inside an async fn returning Result<(), Box<dyn std::error::Error>>
// (or similar), hence the `.await` and `?` below.
use ;
use fetch_well_known;
let http = builder
.timeout
.build?;
let cfg = fetch_well_known.await?;
let mut kas = new?
.with_caller_key; // or CallerKey::P256(..)
let payload_key = kas.rewrap_standard_tdf.await?;
// After refreshing the agent token, bind the new one on the next rewrap:
kas.set_access_token;
Each rewrap then goes to the Connect endpoint /kas.AccessService/Rewrap with Authorization: DPoP <token> and a DPoP proof (htm, htu = the Connect procedure, iat, jti, ath). The signed request token is signed by the same key (EdDSA or ES256). A REST-only configuration is refused. Build agent_signing_key with opentdf::ed25519_dalek so the major version matches.
Testing with Real KAS
Integration tests are available that work with a real KAS server:
# Set environment variables
# Run KAS integration tests
KAS Error Handling
The KAS client provides detailed error information:
use ;
match kas_client.rewrap_standard_tdf.await
Interoperability
⚠️ Compatibility Note: opentdf-rs follows the official OpenTDF specification with camelCase field names in TDF manifests (
encryptionInformation,keyAccess, etc.). OpenTDFKit (Swift) currently uses non-standard snake_case field names and is incompatible. See INTEROPERABILITY.md for detailed compatibility matrix and workarounds.
The Rust KAS client is fully interoperable with:
- platform/sdk (Go): ✅ Fully compatible (spec-compliant)
- otdfctl (Go): ✅ Fully compatible (golden implementation)
- OpenTDF Platform: ✅ Production KAS deployments
- OpenTDFKit (Swift): ❌ Incompatible (uses snake_case - bug in Swift SDK)
TDF files created by spec-compliant SDKs (Go, Rust) can be decrypted across platforms using KAS.
Security Considerations
Cryptographic Algorithms
OpenTDF-RS uses industry-standard cryptographic primitives:
- Symmetric Encryption: AES-256-GCM (Authenticated Encryption with Associated Data)
- Key Wrapping (TDF): RSA-2048 with OAEP padding
- Key Agreement (NanoTDF): ECDH with P-256 curve + HKDF-SHA256
- Policy Binding: HMAC-SHA256
- JWT Signing: ES256 (ECDSA with P-256)
⚠️ SHA-1 Deprecation Notice
RSA-OAEP Padding: The current implementation uses SHA-1 for RSA-OAEP padding to maintain compatibility with the OpenTDF Go SDK (platform). SHA-1 has known collision vulnerabilities (see SHAttered attack).
- Why SHA-1? Required for cross-platform interoperability with existing OpenTDF implementations
- Risk Level: Low in this context (used for padding, not primary security)
- Mitigation: RSA-2048 key size and OAEP construction provide defense-in-depth
- Future: Migration to SHA-256 planned for entire OpenTDF ecosystem
Transport Security
When using KAS in production:
- Always use HTTPS/TLS for KAS communication (never plain HTTP in production)
- Validate TLS certificates - consider certificate pinning for high-security deployments
- Secure OAuth tokens - use short-lived tokens, never hardcode credentials
- Network isolation - deploy KAS in a protected network segment
Key Management Best Practices
- Ephemeral keys: Generated fresh for each KAS request, never reused
- Key rotation: Support for KAS key rotation through multiple key access objects
- Audit logging: All key access attempts should be logged for compliance
- Access policies: Enforce attribute-based access control (ABAC) at KAS layer
Data-at-Rest Security
- TDF archives use authenticated encryption (AES-256-GCM) preventing tampering
- Policy binding cryptographically ties access policies to encrypted data
- Key wrapping ensures payload keys are never stored in plaintext
- Zero Trust: Encryption keys separated from encrypted data
Compliance Considerations
- FIPS 140-2: AES-256-GCM and RSA-2048 are FIPS-approved algorithms
- NIST SP 800-38D: AES-GCM implementation follows NIST guidelines
- Note: SHA-1 usage may impact certain compliance requirements - evaluate for your use case
For security vulnerabilities, please see SECURITY.md (if available) or file an issue.
MCP Server
OpenTDF-RS includes an implementation of the Model Context Protocol (MCP) server, allowing AI assistants and other tools to interact with TDF capabilities via a standardized API.
MCP Server Tools
The MCP server provides the following tools:
| Tool Name | Description |
|---|---|
tdf_create |
Creates a new TDF archive with encrypted data |
tdf_read |
Reads contents from a TDF archive. Supports optional KAS decryption with kas_url and kas_token parameters |
encrypt |
Encrypts data using TDF encryption methods |
decrypt |
Decrypts TDF-encrypted data |
policy_create |
Creates a new policy for TDF encryption |
policy_validate |
Validates a policy against a TDF archive |
attribute_define |
Defines attribute namespaces with optional hierarchies |
user_attributes |
Sets user attributes for testing access control |
access_evaluate |
Evaluates whether a user with attributes can access protected content with detailed audit records |
policy_binding_verify |
Verifies the cryptographic binding of a policy to a TDF |
All access attempts and attribute evaluations are comprehensively logged for compliance and auditing purposes. The audit logging system captures detailed information about each operation, including:
- The requesting entity identifiers
- Complete sets of attributes presented
- Attribute sources and verification status
- Detailed evaluation results for each attribute in the policy
- Final access decisions with timestamps
- Policy version information
Running the MCP Server
To run the MCP server and interact with it via Claude or other MCP-compatible clients:
The server listens on stdio for JSON-RPC messages, making it compatible with tools like Claude Code that use the MCP protocol for communication.
Using with Claude Code
Claude Code can connect to the MCP server to perform TDF operations:
This starts Claude with the MCP server, allowing you to use TDF capabilities directly within the chat interface.
Example commands:
# Create TDF
/mcp opentdf tdf_create {"data": "SGVsbG8gV29ybGQh", "kas_url": "https://kas.example.com", "policy": {"uuid": "sample-uuid", "body": {"attributes": [{"attribute": "gov.example:clearance", "operator": "MinimumOf", "value": "secret"}], "dissem": ["user@example.com"]}}}
# Read TDF (without decryption)
/mcp opentdf tdf_read {"tdf_data": "<base64-encoded-tdf-data>"}
# Read and decrypt TDF using KAS
/mcp opentdf tdf_read {"tdf_data": "<base64-encoded-tdf-data>", "kas_url": "http://10.0.0.138:8080/kas", "kas_token": "your-oauth-token"}
ABAC Testing with MCP
The MCP server supports comprehensive ABAC functionality testing:
# Basic ABAC testing
# Comprehensive attribute access logging test
These scripts demonstrate:
- Attribute namespace definition with hierarchies
- User attribute assignment
- Policy creation with attribute conditions
- TDF creation with policy binding
- Access evaluation based on attributes
- Policy binding verification
- Comprehensive audit logging and compliance reporting
The audit logging test generates detailed compliance reports in the tools/reports directory. See tools/audit-guide.md for more information on the audit logging system.
Development
MCP Server Development
The MCP server implements the JSON-RPC 2.0 protocol over stdio to provide TDF capabilities to clients. When developing or extending the MCP server:
- Tool Definitions: Define tools with both
schemaandinputSchemafields for compatibility - Protocol Version: Use the latest MCP protocol version (currently "2024-11-05")
- Response Format: Ensure all responses follow the JSON-RPC 2.0 specification
- Error Handling: Use standard JSON-RPC error codes (-32xxx)
- Testing: Use
tools/test-mcp.jsto verify functionality
If adding new tools, remember to:
- Add the tool to both the initialize response and listTools response
- Implement proper parameter validation
- Follow the JSON-RPC request/response flow
- Document the tool in this README
Getting Started
Installation
Add to your Cargo.toml (crates.io):
[]
= "0.16"
Feature Flags
┌─────────────────────────────────────────────────────────────────────────────┐
│ Feature Default Description │
├─────────────────────────────────────────────────────────────────────────────┤
│ kas-client ✅ KAS client + aws-lc-rs (FIPS, secure) │
│ kas-client-rustcrypto - KAS client + pure Rust (portable) │
│ rustls-tls ✅ TLS via rustls │
│ native-tls - TLS via OpenSSL/SecureTransport │
└─────────────────────────────────────────────────────────────────────────────┘
Crypto Providers
| Provider | Timing-Safe | FIPS | Portable | WASM |
|---|---|---|---|---|
| aws-lc-rs (default) | ✅ | ✅ | Needs C compiler | ❌ |
| rustcrypto | Patched in rsa 0.10 (RUSTSEC-2023-0071) |
❌ | ✅ Pure Rust | ❌ |
| WebCrypto (WASM only) | ✅ | Browser-dependent | N/A | ✅ |
Common Configurations
# Recommended: Secure defaults (aws-lc-rs + rustls)
= "0.16"
# Pure Rust: No C compiler needed (not FIPS validated)
= { = "0.16", = false, = ["kas-client-rustcrypto"] }
# Native TLS: Use system TLS (OpenSSL on Linux, SecureTransport on macOS)
= { = "0.16", = false, = ["kas-client", "native-tls"] }
# Minimal: Core TDF operations only (no KAS client, no async)
= { = "0.16", = false }
WASM Note
The opentdf-wasm crate uses browser-native WebCrypto for RSA operations—no Rust crypto crate needed, no timing vulnerability.
🚀 What's New in v0.7.0
Version 0.7.0 brings critical security improvements and better feature organization:
- ✅ Constant-time RSA: Default crypto provider changed to aws-lc-rs (FIPS validated)
- ✅ RUSTSEC-2023-0071 Fixed: Timing vulnerability eliminated in default builds
- ✅ cargo-deny Integration: Automated security advisory and license auditing in CI
- ✅ Feature Reorganization: Clearer naming (
kas-client,kas-client-rustcrypto) - ✅ WebCrypto for WASM: Browser builds use native SubtleCrypto API
- ✅ Pure Rust Option:
kas-client-rustcryptofor environments without C compiler
Migration Guide (v0.6.x → v0.7.0)
Feature Renaming:
# Before (v0.6.x)
= { = "0.6", = ["kas"] }
# After (v0.7.0) - "kas" still works but is deprecated
= "0.16" # kas-client is now the default
Pure Rust Builds:
# Before (v0.6.x) - not available
# After (v0.7.0) - explicit pure Rust option
= { = "0.16", = false, = ["kas-client-rustcrypto"] }
What's New in v0.5.0
Version 0.5.0 brings significant DX (Developer Experience) improvements:
- ✅ PolicyBuilder: Fluent API with auto-defaults
- ✅ AttributeFqn: URL-based attribute identifiers
- ✅ Structured Errors: Programmatic error handling with suggestions
- ✅ Prelude Module: Auto-import extension traits
- ✅ TdfDecryptBuilder: Symmetric API for encryption/decryption
- ✅ 40% Fewer Dependencies: Reduced attack surface
- ✅ #[must_use]: Compile-time safety on all builders
Migration Guide (v0.4.x → v0.5.0)
Import Changes:
// Before (v0.4.x)
use ;
// After (v0.5.0) - Use prelude!
use *;
Policy Creation:
// Before (v0.4.x)
let policy = new;
// After (v0.5.0) - PolicyBuilder!
let policy = new
.id_auto
.attribute_fqn?
.dissemination
.build?;
Error Handling:
// Before (v0.4.x)
match err
// After (v0.5.0) - Structured errors!
match err
FQN Support (New in v0.5.0):
use *;
// Parse URL-based attribute identifiers
let fqn = parse?;
assert_eq!;
assert_eq!;
assert_eq!;
Basic Usage
The simplified API makes TDF encryption incredibly easy:
use *;
// Create a policy with the new builder
let policy = new
.id_auto
.dissemination
.build?;
// Encrypt data - fluent API with #[must_use]
encrypt
.kas_url
.policy
.to_file?;
Encrypt a File
use *;
let policy = new
.id_auto
.dissemination
.build?;
encrypt_file
.kas_url
.policy
.mime_type
.build?;
With Attribute-Based Access Control (ABAC)
use *;
// Create policy with FQN-based attributes
let policy = new
.id_auto
.attribute_fqn?
.dissemination
.build?;
// Encrypt with ABAC policy
encrypt
.kas_url
.policy
.to_file?;
WebAssembly (WASM) Support
OpenTDF-RS can be compiled to WebAssembly and run in both browser and Node.js environments. This enables data-centric security directly in web applications without requiring a server-side component.
Installation
From GitHub Packages
Configure npm to use GitHub Packages for @arkavo-org scoped packages:
# Create/update .npmrc
# Install the package
From GitHub Releases
Download pre-built WASM binaries from GitHub Releases.
Quick Start
Browser
import init from '@arkavo-org/opentdf-wasm';
// Initialize the WASM module
await ;
console.log;
// Create a TDF
const data = ; // Base64 encode
const policy = ;
const result = ;
if
Node.js
const = require;
console.log;
const data = Buffer..;
const policy = ;
const result = ;
console.log;
WASM Features
- ✅ TDF archive creation with encryption
- ✅ TDF manifest reading
- ✅ Attribute-Based Access Control (ABAC) policy evaluation
- ✅ Policy creation and validation
- ✅ Works in browser and Node.js environments
- ✅ Optimized for size (~200KB gzipped for web)
Building from Source
# Install wasm-pack
# Build for web
# Build for Node.js
GitHub Releases
WASM artifacts are automatically built and published for:
- Feature branches: Built on every push for testing (artifacts retained 7 days)
- Main branch: Built and retained as latest artifacts (90 days)
- Tagged releases: Full releases with downloadable archives and checksums
Download options:
opentdf-wasm-web.tar.gz- Web browser targetopentdf-wasm-node.tar.gz- Node.js targetopentdf-wasm-combined.tar.gz- Both targets in one archive
All releases include SHA256 checksums for verification.
For complete WASM documentation, see crates/wasm/README.md.
Performance Benchmarks
OpenTDF-RS includes comprehensive performance benchmarks for in-memory TDF operations, demonstrating production-ready performance across various file sizes.
Quick Summary
| Operation | 1 KB | 100 KB | 1 MB |
|---|---|---|---|
| TDF Creation | 38.9 µs | 838 µs | 10.5 ms |
| TDF Reading | 7.8 µs | 60.6 µs | 580 µs |
| Encryption | 26.7 µs | 625 µs | 5.78 ms |
| Archive Building | 5.5 µs | 53.1 µs | 514 µs |
Throughput: ~100 MiB/s sustained for complete TDF creation operations
Running Benchmarks
# Run all benchmarks
# View HTML reports
Key Results
- Fast Small File Operations: <40µs overhead for 1KB files
- Scalable Performance: Consistent throughput from 1KB to 1MB+
- In-Memory Operations: 1.86 GiB/s archive building (no filesystem bottleneck)
- WASM Compatible: Zero filesystem dependencies, ideal for browser/WASI
For detailed benchmark results and analysis, see BENCHMARKS.md.
WASI (WebAssembly System Interface) Support
OpenTDF-RS works seamlessly in WASI environments, enabling secure TDF operations in sandboxed WebAssembly runtimes like Wasmtime.
What is WASI?
WASI provides a standardized system interface for WebAssembly, offering:
- Sandboxed execution with capability-based security
- Cross-platform portability
- Native-like performance
- No filesystem dependencies required
Quick Start
# Install WASI target
# Install Wasmtime
|
# Build and run the test
Example Output
=== OpenTDF WASI Example ===
Original data: Hello from WASI! This is confidential data.
Data size: 43 bytes
Creating policy...
Policy created with UUID: c27f405b-d208-4610-ae24-f58c464714c1
Encrypting data...
Encryption successful!
Building TDF archive in memory...
TDF archive created!
Archive size: 1544 bytes
Reading TDF archive from memory...
Archive opened successfully
=== WASI Test Complete ===
✓ TDF creation (in-memory) - SUCCESS
✓ TDF reading (in-memory) - SUCCESS
✓ No filesystem operations required!
What This Demonstrates
- ✅ Complete TDF Lifecycle: Creation, encryption, and reading entirely in memory
- ✅ Zero Filesystem Access: All operations use
io::Cursor<Vec<u8>> - ✅ WASI Sandbox: Secure cryptographic operations in capability-based environment
- ✅ Cross-Platform: Same binary runs on Linux, macOS, Windows with Wasmtime
Performance
- Binary Size: ~2.1 MB (optimized WASM)
- Execution Time: <50ms total
- Memory Usage: ~5MB peak
- Startup Time: <10ms
For complete WASI documentation and advanced usage, see tests/wasi/README.md.
License
This project is licensed under [LICENSE].