cipherstash-client 0.42.0

The official CipherStash SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#![cfg(all(feature = "test-utils", feature = "tokio"))]

mod prelude;

use prelude::*;
use zerokms_protocol::IdentifiedBy;

async fn create_scoped_cipher(
    access_key: &str,
    workspace_id: WorkspaceId,
    client_key: &ClientKey,
    keyset_id: Option<Uuid>,
) -> Arc<ScopedCipher<AccessKeyStrategy>> {
    let strategy = build_access_key_strategy(access_key, workspace_id);
    let client = Arc::new(build_zerokms_with_client_key(strategy, client_key));
    let cipher = ScopedCipher::init(client, keyset_id.map(IdentifiedBy::Uuid))
        .await
        .expect("failed to create scoped cipher");
    Arc::new(cipher)
}

fn create_column_config_with_indexes(indexes: Vec<Index>) -> ColumnConfig {
    let mut config = ColumnConfig::build("test_column");

    for index in indexes {
        config.indexes.push(index);
    }

    config
}

#[tokio::test]
#[ignore = "e2e"]
async fn test_encrypt_and_decrypt_eql_basic() {
    let _temp_config_dir = &*CONFIG_DIR;

    let token = build_mock_token();
    let cts_client = build_cts_client(token);
    let workspace_id = create_workspace(&cts_client).await;
    let access_key = create_access_key(&cts_client, workspace_id).await;

    let strategy = build_access_key_strategy(&access_key, workspace_id);
    let zero_kms = build_zerokms(strategy);

    let keyset = create_keyset(&zero_kms).await;
    let client_key = create_client_key(&zero_kms, &keyset).await;
    let cipher =
        create_scoped_cipher(&access_key, workspace_id, &client_key, Some(keyset.id)).await;

    // Create test data
    let identifier = Identifier::new("users", "email");
    let plaintext_value = cipherstash_client::encryption::Plaintext::from("test@example.com");
    let column_config = create_column_config_with_indexes(vec![Index::new_match()]);

    let prepared = PreparedPlaintext::new(
        Cow::Owned(column_config),
        identifier.clone(),
        plaintext_value.clone(),
        EqlOperation::Store,
    );

    // Encrypt
    let encrypt_opts = EqlEncryptOpts::default();
    let encrypted = encrypt_eql(cipher.clone(), vec![prepared], &encrypt_opts)
        .await
        .expect("failed to encrypt");

    assert_eq!(encrypted.len(), 1);
    let stored = expect_store(&encrypted[0]);
    let payload = expect_encrypted(stored);
    assert_eq!(payload.identifier, identifier);
    assert_eq!(payload.version, EQL_SCHEMA_VERSION);

    // Decrypt
    let decrypt_opts = EqlDecryptOpts::default();
    let stored_ciphertexts: Vec<EqlCiphertext> = encrypted.into_iter().map(into_store).collect();
    let decrypted = decrypt_eql(cipher.clone(), stored_ciphertexts, &decrypt_opts)
        .await
        .expect("failed to decrypt");

    assert_eq!(decrypted.len(), 1);
    assert_eq!(
        String::try_from(decrypted[0].clone()).unwrap(),
        "test@example.com"
    );
}

#[tokio::test]
#[ignore = "e2e"]
async fn test_encrypt_eql_with_multiple_index_types() {
    let _temp_config_dir = &*CONFIG_DIR;

    let token = build_mock_token();
    let cts_client = build_cts_client(token);
    let workspace_id = create_workspace(&cts_client).await;
    let access_key = create_access_key(&cts_client, workspace_id).await;

    let strategy = build_access_key_strategy(&access_key, workspace_id);
    let zero_kms = build_zerokms(strategy);

    let keyset = create_keyset(&zero_kms).await;
    let client_key = create_client_key(&zero_kms, &keyset).await;
    let cipher =
        create_scoped_cipher(&access_key, workspace_id, &client_key, Some(keyset.id)).await;

    // Create column config with multiple index types
    let identifier = Identifier::new("cms", "doc_text");
    let plaintext_value = cipherstash_client::encryption::Plaintext::from("the quick brown fox");
    let column_config = create_column_config_with_indexes(vec![
        Index::new_match(),
        Index::new_ore(),
        Index::new_unique(),
    ]);

    let prepared = PreparedPlaintext::new(
        Cow::Owned(column_config),
        identifier.clone(),
        plaintext_value,
        EqlOperation::Store,
    );

    // Encrypt
    let encrypt_opts = EqlEncryptOpts::default();
    let encrypted = encrypt_eql(cipher.clone(), vec![prepared], &encrypt_opts)
        .await
        .expect("failed to encrypt");

    assert_eq!(encrypted.len(), 1);

    // Verify indexes were generated
    let payload = expect_encrypted(expect_store(&encrypted[0]));
    assert!(
        payload.bloom_filter.is_some(),
        "Match index should be present"
    );
    assert!(
        payload.ore_block_u64_8_256.is_some(),
        "ORE index should be present"
    );
    assert!(payload.hmac_256.is_some(), "Unique index should be present");
}

#[tokio::test]
#[ignore = "e2e"]
async fn test_encrypt_eql_in_query_mode() {
    let _temp_config_dir = &*CONFIG_DIR;

    let token = build_mock_token();
    let cts_client = build_cts_client(token);
    let workspace_id = create_workspace(&cts_client).await;
    let access_key = create_access_key(&cts_client, workspace_id).await;

    let strategy = build_access_key_strategy(&access_key, workspace_id);
    let zero_kms = build_zerokms(strategy);

    let keyset = create_keyset(&zero_kms).await;
    let client_key = create_client_key(&zero_kms, &keyset).await;
    let cipher =
        create_scoped_cipher(&access_key, workspace_id, &client_key, Some(keyset.id)).await;

    // Create query mode encryption
    let identifier = Identifier::new("users", "name");
    let plaintext_value = cipherstash_client::encryption::Plaintext::from("Alice");
    let match_index = Index::new_match();
    let column_config = create_column_config_with_indexes(vec![match_index.clone()]);

    let prepared = PreparedPlaintext::new(
        Cow::Owned(column_config),
        identifier.clone(),
        plaintext_value,
        EqlOperation::Query(
            &match_index.index_type,
            cipherstash_client::encryption::QueryOp::Default,
        ),
    );

    // Encrypt in query mode
    let encrypt_opts = EqlEncryptOpts::default();
    let encrypted = encrypt_eql(cipher.clone(), vec![prepared], &encrypt_opts)
        .await
        .expect("failed to encrypt in query mode");

    assert_eq!(encrypted.len(), 1);
    let query = expect_query(&encrypted[0]);
    let encrypted_query = expect_query_encrypted(query);
    assert_eq!(encrypted_query.identifier, identifier);

    // In query mode there's no ciphertext field — just the matching index term.
    assert!(
        matches!(encrypted_query.term, RootQueryTerm::BloomFilter { .. }),
        "Query mode should produce a bloom-filter root query term, got {:?}",
        encrypted_query.term
    );
}

#[tokio::test]
#[ignore = "e2e"]
async fn test_decrypt_eql_with_wrong_keyset() {
    let _temp_config_dir = &*CONFIG_DIR;

    let token = build_mock_token();
    let cts_client = build_cts_client(token);
    let workspace_id = create_workspace(&cts_client).await;
    let access_key = create_access_key(&cts_client, workspace_id).await;

    let strategy = build_access_key_strategy(&access_key, workspace_id);
    let zero_kms = build_zerokms(strategy);

    // Create first keyset and encrypt data
    let keyset1 = create_keyset(&zero_kms).await;
    let client_key1 = create_client_key(&zero_kms, &keyset1).await;
    let cipher1 =
        create_scoped_cipher(&access_key, workspace_id, &client_key1, Some(keyset1.id)).await;

    let identifier = Identifier::new("users", "secret");
    let plaintext_value = cipherstash_client::encryption::Plaintext::from("secret_data");
    let column_config = create_column_config_with_indexes(vec![Index::new_unique()]);

    let prepared = PreparedPlaintext::new(
        Cow::Owned(column_config),
        identifier.clone(),
        plaintext_value,
        EqlOperation::Store,
    );

    let encrypt_opts = EqlEncryptOpts::default();
    let encrypted = encrypt_eql(cipher1.clone(), vec![prepared], &encrypt_opts)
        .await
        .expect("failed to encrypt");

    // Create second keyset and try to decrypt with it
    let keyset2 = create_keyset(&zero_kms).await;
    let client_key2 = create_client_key(&zero_kms, &keyset2).await;
    let cipher2 =
        create_scoped_cipher(&access_key, workspace_id, &client_key2, Some(keyset2.id)).await;

    // Try to decrypt with wrong keyset (should fail)
    let decrypt_opts = EqlDecryptOpts {
        keyset_id: Some(keyset2.id),
        ..Default::default()
    };
    let stored: Vec<EqlCiphertext> = encrypted.into_iter().map(into_store).collect();
    let result = decrypt_eql(cipher2.clone(), stored, &decrypt_opts).await;

    assert!(result.is_err(), "Decryption with wrong keyset should fail");

    // Verify error message mentions the keyset
    let err = result.unwrap_err();
    let err_str = err.to_string();
    assert!(
        err_str.contains("decrypt") || err_str.contains("keyset"),
        "Error should mention decryption or keyset failure: {err_str}"
    );
}

#[tokio::test]
#[ignore = "e2e"]
async fn test_encrypt_eql_multiple_plaintexts() {
    let _temp_config_dir = &*CONFIG_DIR;

    let token = build_mock_token();
    let cts_client = build_cts_client(token);
    let workspace_id = create_workspace(&cts_client).await;
    let access_key = create_access_key(&cts_client, workspace_id).await;

    let strategy = build_access_key_strategy(&access_key, workspace_id);
    let zero_kms = build_zerokms(strategy);

    let keyset = create_keyset(&zero_kms).await;
    let client_key = create_client_key(&zero_kms, &keyset).await;
    let cipher =
        create_scoped_cipher(&access_key, workspace_id, &client_key, Some(keyset.id)).await;

    // Create multiple plaintexts
    let column_config = create_column_config_with_indexes(vec![Index::new_match()]);

    let prepared_plaintexts = vec![
        PreparedPlaintext::new(
            Cow::Borrowed(&column_config),
            Identifier::new("users", "email"),
            cipherstash_client::encryption::Plaintext::from("alice@example.com"),
            EqlOperation::Store,
        ),
        PreparedPlaintext::new(
            Cow::Borrowed(&column_config),
            Identifier::new("users", "email"),
            cipherstash_client::encryption::Plaintext::from("bob@example.com"),
            EqlOperation::Store,
        ),
        PreparedPlaintext::new(
            Cow::Borrowed(&column_config),
            Identifier::new("users", "email"),
            cipherstash_client::encryption::Plaintext::from("charlie@example.com"),
            EqlOperation::Store,
        ),
    ];

    // Encrypt multiple values
    let encrypt_opts = EqlEncryptOpts::default();
    let encrypted = encrypt_eql(cipher.clone(), prepared_plaintexts, &encrypt_opts)
        .await
        .expect("failed to encrypt multiple plaintexts");

    assert_eq!(encrypted.len(), 3);

    // Verify all were encrypted
    for eql in &encrypted {
        let payload = expect_encrypted(expect_store(eql));
        assert_eq!(payload.identifier.table, "users");
        assert_eq!(payload.identifier.column, "email");
    }

    // Decrypt all
    let decrypt_opts = EqlDecryptOpts::default();
    let stored: Vec<EqlCiphertext> = encrypted.into_iter().map(into_store).collect();
    let decrypted = decrypt_eql(cipher.clone(), stored, &decrypt_opts)
        .await
        .expect("failed to decrypt multiple values");

    assert_eq!(decrypted.len(), 3);
    assert_eq!(
        String::try_from(decrypted[0].clone()).unwrap(),
        "alice@example.com"
    );
    assert_eq!(
        String::try_from(decrypted[1].clone()).unwrap(),
        "bob@example.com"
    );
    assert_eq!(
        String::try_from(decrypted[2].clone()).unwrap(),
        "charlie@example.com"
    );
}

#[tokio::test]
#[ignore = "e2e"]
async fn test_stevec_encryption_has_no_v2_wire_representation() {
    // Under the SteVec envelope wire format (CIP-3551) a document's entries
    // are encrypted under one data key with selector-derived nonces and carry
    // raw AEAD output only — there is no self-contained per-entry record, so a
    // SteVec document cannot be serialized as a v2 `EqlCiphertext`. Encrypting
    // a SteVec column through the v2 path must therefore fail closed; SteVec is
    // v3-only. (The v3 envelope round-trip is covered by the client lib tests
    // and the EQL SQLx suite.) Both index modes fail the same way — the v2
    // assembler rejects any SteVec document before it inspects the mode.
    for mode in [
        cipherstash_config::column::SteVecMode::Compat,
        cipherstash_config::column::SteVecMode::Standard,
    ] {
        let _temp_config_dir = &*CONFIG_DIR;

        let token = build_mock_token();
        let cts_client = build_cts_client(token);
        let workspace_id = create_workspace(&cts_client).await;
        let access_key = create_access_key(&cts_client, workspace_id).await;

        let strategy = build_access_key_strategy(&access_key, workspace_id);
        let zero_kms = build_zerokms(strategy);

        let keyset = create_keyset(&zero_kms).await;
        let client_key = create_client_key(&zero_kms, &keyset).await;
        let cipher =
            create_scoped_cipher(&access_key, workspace_id, &client_key, Some(keyset.id)).await;

        let json_document = json!({ "user": { "name": "Alice Johnson", "age": 28 } });
        let plaintext_value = cipherstash_client::encryption::Plaintext::Json(Some(json_document));

        let ste_vec_index = Index::new(cipherstash_config::column::IndexType::SteVec {
            prefix: "cs_ste_vec_v1".to_string(),
            term_filters: Vec::new(),
            array_index_mode: cipherstash_config::column::ArrayIndexMode::ALL,
            mode,
        });
        let column_config = create_column_config_with_indexes(vec![ste_vec_index]);

        let prepared = PreparedPlaintext::new(
            Cow::Owned(column_config),
            Identifier::new("users", "profile_data"),
            plaintext_value,
            EqlOperation::Store,
        );

        let encrypt_opts = EqlEncryptOpts {
            keyset_id: Some(keyset.id),
            ..Default::default()
        };
        let err = encrypt_eql(cipher.clone(), vec![prepared], &encrypt_opts)
            .await
            .expect_err("v2 SteVec encryption must fail — SteVec is v3-only");
        assert!(
            matches!(err, EqlError::UnsupportedSteVecInV2),
            "expected UnsupportedSteVecInV2, got {err:?} (mode {mode:?})"
        );
    }
}

fn expect_store(output: &EqlOutput) -> &EqlCiphertext {
    match output {
        EqlOutput::Store(c) => c,
        EqlOutput::Query(_) => panic!("expected EqlOutput::Store, got Query"),
    }
}

fn into_store(output: EqlOutput) -> EqlCiphertext {
    match output {
        EqlOutput::Store(c) => c,
        EqlOutput::Query(_) => panic!("expected EqlOutput::Store, got Query"),
    }
}

fn expect_query(output: &EqlOutput) -> &EqlQueryPayload {
    match output {
        EqlOutput::Query(q) => q,
        EqlOutput::Store(_) => panic!("expected EqlOutput::Query, got Store"),
    }
}

fn expect_encrypted(eql: &EqlCiphertext) -> &EncryptedPayload {
    match eql {
        EqlCiphertext::Encrypted(p) => p,
        EqlCiphertext::SteVec(_) => panic!("expected EqlCiphertext::Encrypted, got SteVec"),
    }
}

fn expect_query_encrypted(eql: &EqlQueryPayload) -> &EncryptedQueryPayload {
    match eql {
        EqlQueryPayload::Encrypted(p) => p,
        EqlQueryPayload::SteVec(_) => panic!("expected EqlQueryPayload::Encrypted, got SteVec"),
    }
}