Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .cargo/mutants.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ exclude_globs = ["packages/stack-encrypt-derive/**"]
# mutant does not compile, because `AutoStrategy` has no `Default`. So the
# entry excludes no mutant that a test could catch.
#
# The two wasm32 `into_future` entries in `pending.rs` match any line for the
# The four wasm32 `into_future` entries in `pending.rs` match any line for the
# same reason. The future that a native `into_future` returns has no
# `Default`, so the native mutant does not compile.
exclude_re = [
Expand All @@ -80,6 +80,8 @@ exclude_re = [
'stack-encrypt/src/cipher\.rs:\d+:\d+: replace client_key_provider -> EnvKeyProvider with Default::default\(\)$',
'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace <impl IntoFuture for Pending<.*>>::into_future -> Self::IntoFuture with Default::default\(\)$',
'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace <impl IntoFuture for Audited<Pending<.*>>>::into_future -> Self::IntoFuture with Default::default\(\)$',
'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace <impl IntoFuture for WithCredential<Pending<.*>>>::into_future -> Self::IntoFuture with Default::default\(\)$',
'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace <impl IntoFuture for Audited<WithCredential<Pending<.*>>>>::into_future -> Self::IntoFuture with Default::default\(\)$',
# stack-encrypt — equivalent.
# An operator and an index are unit structs, whose `Default` is the value
# `clone` and `case_sensitive` already return.
Expand Down
5 changes: 5 additions & 0 deletions .changeset/auth-credential-per-call.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@cipherstash/auth': patch
---

Rebuild on a `stack-auth` whose Rust API can issue the token for a credential passed with the call. The JavaScript API is unchanged: `getToken` and `getTokenForJwt` behave as before, and share one token cache. In Rust, `CredentialAuthStrategy` is the trait for a credential passed with the call, and an `OidcFederationStrategy` can be built with no provider callback (`OidcFederationStrategy::credential_per_call`). Such a strategy has no `get_token`, so a call that brings no credential does not compile. A Rust strategy built with a provider callback takes no JWT from its caller. The Node and wasm bindings therefore build the Rust strategy with `credential_per_call`, keep the `getJwt` callback themselves, and pass a JWT with each call.
54 changes: 34 additions & 20 deletions languages/golang/encrypt/guest/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ use stack_guest_abi::step::{self, Operation, Step};

use crate::io;
use crate::ops::{self, Bytes};
use crate::options::{parse_options, parse_selector, scope_for, KeysetSelector, Side};
use crate::options::{cipher_ref_for, parse_options, parse_selector, KeysetSelector, Side};
#[cfg(not(feature = "deterministic-kms"))]
use crate::status::STATUS_INTERNAL;
#[cfg(not(feature = "deterministic-kms"))]
Expand Down Expand Up @@ -256,12 +256,12 @@ fn cipher_init(config: InitConfig) -> Result<Vec<u8>, u32> {
let initialising = Initialising::begin();
run(Box::pin(async move {
let _initialising = initialising;
install(
builder
.init()
.await
.map_err(|e| crate::status::fail_error(&e))?,
)
let cipher = builder
.init()
.await
.map_err(|e| crate::status::fail_error(&e))?;
let default = default_keyset_id(&cipher).await?;
install(cipher, default)
}))
}

Expand All @@ -278,12 +278,12 @@ fn cipher_init(seed: InitConfig) -> Result<Vec<u8>, u32> {
let initialising = Initialising::begin();
run(Box::pin(async move {
let _initialising = initialising;
install(
builder
.init()
.await
.map_err(|e| crate::status::fail_error(&e))?,
)
let cipher = builder
.init()
.await
.map_err(|e| crate::status::fail_error(&e))?;
let default = default_keyset_id(&cipher).await?;
install(cipher, default)
}))
}

Expand Down Expand Up @@ -318,14 +318,24 @@ fn init_out_of_order() -> u32 {
out_of_order("the cipher is already initialised or initialising, or the instance is shut down")
}

/// Install the built cipher as the instance's and return its default
/// keyset's id.
fn install(cipher: GuestCipher) -> Result<Vec<u8>, u32> {
/// The id of the cipher's default keyset. `init` loaded that keyset, so
/// this makes no request.
async fn default_keyset_id(cipher: &GuestCipher) -> Result<Vec<u8>, u32> {
let id = cipher
.default_keyset()
.keyset_id()
.await
.map_err(|e| crate::status::fail_error(&e))?;
Ok(id.as_bytes().to_vec())
}

/// Install the built cipher as the instance's and return `default`, its
/// default keyset's id.
fn install(cipher: GuestCipher, default: Vec<u8>) -> Result<Vec<u8>, u32> {
// A shutdown that overtook a paused init installs nothing.
if SHUT_DOWN.with(Cell::get) {
return Err(init_out_of_order());
}
let default = cipher.default_keyset().keyset_id().as_bytes().to_vec();
CIPHER.with(|c| *c.borrow_mut() = Some(Rc::new(cipher)));
Ok(default)
}
Expand Down Expand Up @@ -377,7 +387,11 @@ pub unsafe extern "C" fn se_keyset(sel_ptr: *const u8, sel_len: u32) -> u64 {
let cipher = cipher()?;
run(Box::pin(async move {
let keyset = selector.resolve(&cipher).await?;
Ok(keyset.keyset_id().as_bytes().to_vec())
let id = keyset
.keyset_id()
.await
.map_err(|e| crate::status::fail_error(&e))?;
Ok(id.as_bytes().to_vec())
}))
})
}
Expand Down Expand Up @@ -500,8 +514,8 @@ pub unsafe extern "C" fn se_decrypt_record(
ops::validate::record_tree(&record, &plan, options.context.as_ref())?;
let cipher = cipher()?;
run(Box::pin(async move {
let scope = scope_for(&cipher, &options.keyset).await?;
ops::decrypt_record(scope, &record, &plan, options.context).await
let cipher_ref = cipher_ref_for(&cipher, &options.keyset).await?;
ops::decrypt_record(cipher_ref, &record, &plan, options.context).await
}))
})
}
Expand Down
17 changes: 11 additions & 6 deletions languages/golang/encrypt/guest/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ where
/// were sealed under. The output buffer contains plaintext — the ABI layer's
/// ownership rules govern its wiping.
pub async fn decrypt_record<'a, K>(
scope: impl Into<CipherRef<'a, K>>,
cipher_ref: impl Into<CipherRef<'a, K>>,
record: &[u8],
plan: &Bytes,
expected: Option<Label>,
Expand All @@ -225,11 +225,16 @@ where
K: DataKeySource + IndexKeySource + Sync + 'static,
{
let plan = parse_plan(plan)?;
let value =
dynamic::record::decrypt_with(scope, decode_tree(record)?, &plan, expected, &resolver())
.map_err(|e| fail_dynamic(&e))?
.await
.map_err(|e| fail_error(&e))?;
let value = dynamic::record::decrypt_with(
cipher_ref,
decode_tree(record)?,
&plan,
expected,
&resolver(),
)
.map_err(|e| fail_dynamic(&e))?
.await
.map_err(|e| fail_error(&e))?;
encode_frame(value)
}

Expand Down
19 changes: 13 additions & 6 deletions languages/golang/encrypt/guest/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@

use stack_encrypt::CipherRef;
use stack_encrypt::{KeysetCipher, Label, StackCipher};
use stack_kms::{IdentifiedBy, IndexKeySource};
use stack_kms::{DataKeySource, IdentifiedBy, IndexKeySource};
use uuid::Uuid;
use zerokms_protocol::Name;

Expand Down Expand Up @@ -221,21 +221,28 @@ impl KeysetSelector {
/// default without a round trip, a name or id through the cipher's
/// cache (a first use is one `load-keyset` call). `Any` is not a keyset
/// and is [`STATUS_ENCODING`] here; opening exports resolve it through
/// [`scope_for`] instead.
/// [`cipher_ref_for`] instead.
///
/// A keyset selected by name or id is loaded here, so one that ZeroKMS
/// does not know fails the call that selected it, with that error.
pub async fn resolve<'c, K>(
&self,
cipher: &'c StackCipher<K>,
) -> Result<KeysetCipher<'c, K>, u32>
where
K: IndexKeySource,
K: DataKeySource + IndexKeySource + Sync,
{
let by: IdentifiedBy = match self {
KeysetSelector::Default => return Ok(cipher.default_keyset()),
KeysetSelector::Any => return Err(malformed(r#"{"any"} is not a keyset"#)),
KeysetSelector::Name(name) => IdentifiedBy::Name(name.clone()),
KeysetSelector::Id(id) => IdentifiedBy::Uuid(*id),
};
cipher.keyset(by).await.map_err(|e| fail_error(&e))
// Selecting makes no request. Reading the id loads the keyset, and
// the handle keeps it.
let keyset = cipher.keyset(by);
let _ = keyset.keyset_id().await.map_err(|e| fail_error(&e))?;
Ok(keyset)
}
}

Expand All @@ -246,12 +253,12 @@ impl KeysetSelector {
/// - For one keyset, the result is that keyset's cipher. That cipher only
/// opens leaves from its own keyset. The cipher refuses any other leaf
/// before it retrieves any key.
pub async fn scope_for<'c, K>(
pub async fn cipher_ref_for<'c, K>(
cipher: &'c StackCipher<K>,
selector: &KeysetSelector,
) -> Result<CipherRef<'c, K>, u32>
where
K: IndexKeySource,
K: DataKeySource + IndexKeySource + Sync,
{
match selector {
KeysetSelector::Any => Ok(CipherRef::from(cipher)),
Expand Down
2 changes: 1 addition & 1 deletion languages/golang/encrypt/guest/src/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
//! Go caller can distinguish a bad token from a tampered ciphertext without
//! parsing strings; 11 is a term-derivation failure (a caller-input
//! condition, e.g. match text that yields no tokens); 12 is a keyset-scoped
//! open refusing a leaf whose keyset id is not the scope's — a host's own
//! open refusing a leaf whose keyset id is not the caller's — a host's own
//! constraint, checked before the leaf is authenticated and so not a
//! statement about tampering.
//!
Expand Down
15 changes: 8 additions & 7 deletions languages/golang/encrypt/guest/tests/leak.rs
Original file line number Diff line number Diff line change
Expand Up @@ -527,9 +527,7 @@ fn scenarios() -> Vec<(&'static str, Tree)> {
(
"a record opened through another keyset",
failure("foreign keyset", &["stack_encrypt::foreign_keyset"], || {
let globex =
block_on(cipher.keyset(IdentifiedBy::Name("globex".to_owned().into())))
.expect("keyset");
let globex = cipher.keyset(IdentifiedBy::Name("globex".to_owned().into()));
let record = sealed(&cipher, &plan_under(label("email")));
block_on(ops::decrypt_record(
globex,
Expand Down Expand Up @@ -854,9 +852,8 @@ fn a_keyset_not_found_carries_its_help_and_request_kind() {
#[test]
fn a_foreign_keyset_carries_both_keyset_ids() {
let cipher = cipher();
let globex =
block_on(cipher.keyset(IdentifiedBy::Name("globex".to_owned().into()))).expect("keyset");
let globex_id = globex.keyset_id();
let globex = cipher.keyset(IdentifiedBy::Name("globex".to_owned().into()));
let globex_id = block_on(globex.keyset_id()).unwrap();
let record = sealed(&cipher, &plan_under(label("email")));
let error = failure("foreign", &["stack_encrypt::foreign_keyset"], || {
block_on(ops::decrypt_record(
Expand All @@ -870,6 +867,10 @@ fn a_foreign_keyset_carries_both_keyset_ids() {
assert_eq!(text(get(fields, "expected")), Some(globex_id.to_string()));
assert_eq!(
text(get(fields, "found")),
Some(cipher.default_keyset().keyset_id().to_string())
Some(
block_on(cipher.default_keyset().keyset_id())
.unwrap()
.to_string()
)
);
}
15 changes: 8 additions & 7 deletions languages/golang/encrypt/guest/tests/native_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use stack_encrypt::{
};
use stack_encrypt::{Controlled, Protected};
use stack_encrypt_guest::ops::{self, TERM_EQUALITY, TERM_MATCH, TERM_OPE, TERM_ORE};
use stack_encrypt_guest::options::{scope_for, KeysetSelector};
use stack_encrypt_guest::options::{cipher_ref_for, KeysetSelector};
use stack_encrypt_guest::status::{
STATUS_AUTH, STATUS_CONTEXT_MISMATCH, STATUS_ENCODING, STATUS_FOREIGN_KEYSET, STATUS_TERM,
};
Expand Down Expand Up @@ -941,14 +941,14 @@ fn an_empty_plan_context_is_refused_before_anything_is_sealed() {
}

// =============================================================================
// Keysets: the scope a call selects
// Keysets: the keyset a call selects
// =============================================================================

fn keyset_named<'c>(
cipher: &'c StackCipher<Counting>,
name: &str,
) -> stack_encrypt::KeysetCipher<'c, Counting> {
block_on(cipher.keyset(IdentifiedBy::Name(name.to_string().into()))).expect("select keyset")
cipher.keyset(IdentifiedBy::Name(name.to_string().into()))
}

/// A record batch whose rows were sealed under different keysets opens
Expand Down Expand Up @@ -1017,14 +1017,15 @@ fn a_mixed_keyset_record_batch_opens_through_any_one_call_per_keyset() {
#[test]
fn each_opening_selector_names_its_keyset() {
let cipher = cipher();
let acme = keyset_named(&cipher, "acme").keyset_id();
let keyset_of =
|selector: KeysetSelector| block_on(scope_for(&cipher, &selector)).map(|r| r.keyset_id());
let acme = block_on(keyset_named(&cipher, "acme").keyset_id()).unwrap();
let keyset_of = |selector: KeysetSelector| {
block_on(cipher_ref_for(&cipher, &selector)).map(|r| r.keyset_id())
};

assert_eq!(keyset_of(KeysetSelector::Any), Ok(None));
assert_eq!(
keyset_of(KeysetSelector::Default),
Ok(Some(cipher.default_keyset().keyset_id()))
Ok(Some(block_on(cipher.default_keyset().keyset_id()).unwrap()))
);
let name = zerokms_protocol::Name::try_from("acme")
.ok()
Expand Down
Loading
Loading