-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(crypto): add crypto module Add crypto module that allows to configure SDK to encrypt and decrypt messages. fix(crypto): fix legacy cryptor Improved security of crypto implementation by adding enhanced AES-CBC cryptor. --------- Co-authored-by: Mateusz Dahlke <[email protected]> Co-authored-by: Xavrax <[email protected]> Co-authored-by: josh-lubliner <[email protected]>
- Loading branch information
1 parent
d917aec
commit f15bb75
Showing
27 changed files
with
1,741 additions
and
247 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,24 @@ | ||
[package] | ||
name = "pubnub" | ||
version = "0.3.0" | ||
version = "0.4.0" | ||
edition = "2021" | ||
license = "MIT" | ||
license-file = "LICENSE" | ||
authors = ["PubNub <[email protected]>"] | ||
description = "PubNub SDK for Rust" | ||
repository = "https://github.com/pubnub/rust" | ||
documentation = "https://docs.rs/pubnub/latest/pubnub" | ||
documentation = "https://docs.rs/pubnub/latest/pubnub" | ||
homepage = "https://www.pubnub.com" | ||
categories = ["api-bindings", "asynchronous", "network-programming", "wasm"] | ||
build = "build.rs" | ||
|
||
[features] | ||
|
||
# Enables all non-conflicting features | ||
full = ["publish", "subscribe", "presence", "access", "serde", "reqwest", "aescbc", "parse_token", "blocking", "std", "tokio"] | ||
full = ["publish", "subscribe", "presence", "access", "serde", "reqwest", "crypto", "parse_token", "blocking", "std", "tokio"] | ||
|
||
# Enables all default features | ||
default = ["publish", "subscribe", "serde", "reqwest", "aescbc", "std", "blocking", "tokio"] | ||
default = ["publish", "subscribe", "serde", "reqwest", "std", "blocking", "tokio"] | ||
|
||
# [PubNub features] | ||
|
||
|
@@ -27,8 +28,8 @@ publish = [] | |
## Enables access manager feature | ||
access = [] | ||
|
||
## Enables AES-CBC encryption | ||
aescbc = ["dep:aes", "dep:cbc", "getrandom"] | ||
## Enables crypto module | ||
crypto = ["dep:aes", "dep:cbc", "getrandom"] | ||
|
||
## Enables token parsing | ||
parse_token = ["dep:ciborium"] | ||
|
@@ -48,7 +49,7 @@ tokio = ["dep:tokio"] | |
blocking = ["reqwest?/blocking"] | ||
|
||
## Enables std library | ||
std = ["derive_builder/std", "log/std", "uuid/std", "base64/std", "spin/std", "snafu/std", "hmac/std", "sha2/std", "time/std", "bytes?/std", "getrandom/std", "rand/default", "serde?/std", "serde_json?/std", "ciborium?/std", "futures?/std", "futures?/async-await", "dep:async-channel"] | ||
std = ["derive_builder/std", "log/std", "uuid/std", "base64/std", "spin/std", "snafu/std", "hmac/std", "sha2/std", "time/std", "bytes?/std", "getrandom/std", "rand/default", "serde?/std", "serde_json?/std", "ciborium?/std", "futures?/std", "futures?/async-await", "dep:async-channel"] | ||
|
||
## Enables very specific implementations for different platforms. | ||
## | ||
|
@@ -60,13 +61,13 @@ std = ["derive_builder/std", "log/std", "uuid/std", "base64/std", "spin/std", "s | |
## https://docs.rs/portable_atomic | ||
## and | ||
## https://docs.rs/critical-section/latest/critical_section/ | ||
extra_platforms = ["spin/portable_atomic", "dep:portable-atomic"] | ||
extra_platforms = ["spin/portable_atomic", "dep:portable-atomic"] | ||
|
||
# [Internal features] (not intended for use outside of the library) | ||
contract_test = ["parse_token", "publish", "access"] | ||
full_no_std = ["serde", "reqwest", "aescbc", "parse_token", "blocking", "publish", "access", "subscribe", "tokio", "presence"] | ||
full_no_std_platform_independent = ["serde", "aescbc", "parse_token", "blocking", "publish", "access", "subscribe", "presence"] | ||
pubnub_only = ["aescbc", "parse_token", "blocking", "publish", "access", "subscribe", "presence"] | ||
contract_test = ["parse_token", "publish", "access", "crypto"] | ||
full_no_std = ["serde", "reqwest", "crypto", "parse_token", "blocking", "publish", "access", "subscribe", "tokio", "presence"] | ||
full_no_std_platform_independent = ["serde", "crypto", "parse_token", "blocking", "publish", "access", "subscribe", "presence"] | ||
pubnub_only = ["crypto", "parse_token", "blocking", "publish", "access", "subscribe", "presence"] | ||
mock_getrandom = ["getrandom/custom"] | ||
# TODO: temporary treated as internal until we officially release it | ||
subscribe = ["dep:futures"] | ||
|
@@ -139,6 +140,10 @@ name = "contract_test" | |
harness = false | ||
required-features = ["contract_test"] | ||
|
||
[[example]] | ||
name = "crypto" | ||
required-features = ["default", "crypto"] | ||
|
||
[[example]] | ||
name = "publish" | ||
required-features = ["default"] | ||
|
@@ -194,4 +199,3 @@ required-features = ["default", "presence"] | |
[[example]] | ||
name = "presence_state_blocking" | ||
required-features = ["default", "blocking", "presence"] | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,29 @@ | ||
The MIT License (MIT) | ||
PubNub Software Development Kit License Agreement | ||
Copyright © 2023 PubNub Inc. All rights reserved. | ||
|
||
Copyright (c) 2023 PubNub Inc. | ||
Subject to the terms and conditions of the license, you are hereby granted | ||
a non-exclusive, worldwide, royalty-free license to (a) copy and modify | ||
the software in source code or binary form for use with the software services | ||
and interfaces provided by PubNub, and (b) redistribute unmodified copies | ||
of the software to third parties. The software may not be incorporated in | ||
or used to provide any product or service competitive with the products | ||
and services of PubNub. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
The above copyright notice and this license shall be included | ||
in or with all copies or substantial portions of the software. | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
This license does not grant you permission to use the trade names, trademarks, | ||
service marks, or product names of PubNub, except as required for reasonable | ||
and customary use in describing the origin of the software and reproducing | ||
the content of this license. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. | ||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF | ||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO | ||
EVENT SHALL PUBNUB OR THE AUTHORS OR COPYRIGHT HOLDERS OF THE SOFTWARE BE | ||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF | ||
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | ||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
|
||
https://www.pubnub.com/ | ||
https://www.pubnub.com/terms |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,8 +17,9 @@ | |
This is the official PubNub Rust SDK repository. | ||
|
||
[PubNub](https://www.pubnub.com/) takes care of the infrastructure and APIs needed for the realtime | ||
communication layer of your application. Work on your app's logic and let PubNub handle sending and receiving | ||
data across the world in less than 100ms. | ||
communication layer of your application. Work on your app's logic and let | ||
PubNub handle sending and receiving data across the world in less than | ||
100ms. | ||
|
||
## Getting started | ||
|
||
|
@@ -35,11 +36,11 @@ Add `pubnub` to your Rust project in the `Cargo.toml` file: | |
```toml | ||
# default features | ||
[dependencies] | ||
pubnub = "0.3.0" | ||
pubnub = "0.4.0" | ||
|
||
# all features | ||
[dependencies] | ||
pubnub = { version = "0.3.0", features = ["full"] } | ||
pubnub = { version = "0.4.0", features = ["full"] } | ||
``` | ||
|
||
### Example | ||
|
@@ -125,24 +126,25 @@ You can find more examples in our [examples](https://github.com/pubnub/rust/tree | |
|
||
## Features | ||
|
||
The `pubnub` crate is split into multiple features. You can enable or disable them in the `Cargo.toml` file, like so: | ||
The `pubnub` crate is split into multiple features. You can enable or | ||
disable them in the `Cargo.toml` file, like so: | ||
|
||
```toml | ||
# only blocking and access + default features | ||
[dependencies] | ||
pubnub = { version = "0.3.0", features = ["blocking", "access"] } | ||
pubnub = { version = "0.4.0", features = ["blocking", "access"] } | ||
|
||
# only parse_token + default features | ||
[dependencies] | ||
pubnub = { version = "0.3.0", features = ["parse_token"] } | ||
pubnub = { version = "0.4.0", features = ["parse_token"] } | ||
``` | ||
|
||
### Available features | ||
|
||
| Feature name | Description | Available PubNub APIs | | ||
| :------------ | :---------- | :------------- | | ||
| `full` | Enables all non-conflicting features | Configuration, Publish, Subscribe, Access Manager, Parse Token, Presence | | ||
| `default` | Enables default features: `publish`, `subscribe`, `serde`, `reqwest`, `aescbc`, `std` | Configuration, Publish, Subscribe | | ||
| `full` | Enables all non-conflicting features | Configuration, Publish, Subscribe, Access Manager, Parse Token, Presence, Crypto Module | | ||
| `default` | Enables default features: `publish`, `subscribe`, `serde`, `reqwest`, `std` | Configuration, Publish, Subscribe | | ||
| `publish` | Enables Publish API | Configuration, Publish | | ||
| `access` | Enables Access Manager API | Configuration, Access Manager | | ||
| `parse_token` | Enables parsing Access Manager tokens | Configuration, Parse Token | | ||
|
@@ -152,7 +154,7 @@ pubnub = { version = "0.3.0", features = ["parse_token"] } | |
| `serde` | Uses [serde](https://github.com/serde-rs/serde) for serialization | n/a | | ||
| `reqwest` | Uses [reqwest](https://github.com/seanmonstar/reqwest) as a transport layer | n/a | | ||
| `blocking` | Enables blocking executions of APIs | n/a | | ||
| `aescbc` | Enables AES-CBC encryption | n/a | | ||
| `crypto` | Enables crypto module for data encryption and decryption | n/a | | ||
| `std` | Enables `std` library | n/a | | ||
|
||
## Documentation | ||
|
@@ -162,52 +164,61 @@ pubnub = { version = "0.3.0", features = ["parse_token"] } | |
|
||
## Wasm support | ||
|
||
The `pubnub` crate is compatible with WebAssembly. You can use it in your Wasm project. | ||
The `pubnub` crate is compatible with WebAssembly. You can use it in your | ||
Wasm project. | ||
|
||
## `no_std` support | ||
|
||
The `pubnub` crate is `no_std` compatible. To use it in a `no_std` environment, you have to disable the default | ||
features and enable the ones you need, for example: | ||
The `pubnub` crate is `no_std` compatible. To use it in a `no_std` | ||
environment, you have to disable the default features and enable the ones | ||
you need, for example: | ||
|
||
```toml | ||
[dependencies] | ||
pubnub = { version = "0.3.0", default-features = false, features = ["serde", "publish", | ||
pubnub = { version = "0.4.0", default-features = false, features = ["serde", "publish", | ||
"blocking"] } | ||
``` | ||
|
||
### Limitations | ||
|
||
The `no_std` support is limited by the implementation details of the SDK. | ||
|
||
The SDK uses the `alloc` crate to allocate memory for some operations, which means that | ||
certain targets aren't supported. Additionally, as we provide a synchronous API, we use | ||
some parts of the `alloc::sync` module, which is also not supported in certain `no_std` environments. | ||
The SDK uses the `alloc` crate to allocate memory for some operations, which | ||
means that certain targets aren't supported. Additionally, as we provide a | ||
synchronous API, we use some parts of the `alloc::sync` module, which is | ||
also not supported in certain `no_std` environments. | ||
|
||
Some SDK features aren't supported in a `no_std` environment: | ||
|
||
* partially `access` module (because of lack of timestamp support) | ||
* partially `reqwest` transport (because of the reqwest implementation details) | ||
* partially `subscribe` module (because of the spawning tasks and time dependence) | ||
* partially `presence` module (because of the spawning tasks and time dependence) | ||
* partially `reqwest` transport (because of the reqwest implementation | ||
details) | ||
* partially `subscribe` module (because of the spawning tasks and time | ||
dependence) | ||
* partially `presence` module (because of the spawning tasks and time | ||
dependence) | ||
* `std` feature (because of the `std` library) | ||
|
||
We depend on a random number generator to generate data for debugging purposes. | ||
If you want to use the SDK in a `no_std` environment, you'll have to provide | ||
your own random number generator implementation for certain targets. | ||
We depend on a random number generator to generate data for debugging | ||
purposes. If you want to use the SDK in a `no_std` environment, you'll have | ||
to provide your own random number generator implementation for certain | ||
targets. | ||
|
||
See more: | ||
|
||
* [`getrandom` crate](https://docs.rs/getrandom/latest/getrandom/) | ||
* [no_std examples](https://github.com/pubnub/rust/tree/master/examples/no_std/) | ||
|
||
If you're having problems compiling this crate for more exotic targets, you can try to use the | ||
`extra_platforms` feature. Be aware that this feature is **not supported** and we do not recommend using it. | ||
If you're having problems compiling this crate for more exotic targets, you | ||
can try to use the `extra_platforms` feature. Be aware that this feature is | ||
**not supported** and we do not recommend using it. | ||
|
||
For more information about this feature. refer to [Cargo.toml](https://github.com/pubnub/rust/blob/master/Cargo.toml) in the `[features]` section. | ||
|
||
## Support | ||
|
||
If you **need help** or have a **general question**, contact [email protected]. | ||
If you **need help** or have a **general question**, contact | ||
[email protected]. | ||
|
||
## License | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
use pubnub::core::CryptoProvider; | ||
use pubnub::providers::crypto::CryptoModule; | ||
use pubnub::{Keyset, PubNubClientBuilder}; | ||
use std::env; | ||
|
||
/// This example demonstrates how data can be manually encrypted or | ||
/// automatically as part of PubNubClient instance when publish / subscribe is | ||
/// used. | ||
/// | ||
/// The following example consists of two parts: a manual _encryption_ and | ||
/// _decryption_ demonstration, and an automated _encryption_ and _decryption_ | ||
/// demonstration, as part of a configured `PubNubClientInstance`. | ||
|
||
#[tokio::main] | ||
async fn main() -> Result<(), Box<dyn snafu::Error>> { | ||
let source_data: Vec<u8> = "Hello world!".into(); | ||
let use_random_iv = true; | ||
let cipher = "enigma"; | ||
|
||
// ----------------------------------------- | ||
// Manual encryption and decryption example. | ||
// | ||
|
||
// Crypto module with legacy AES-CBC cryptor (with enhanced AES-CBC decrypt | ||
// support). | ||
let legacy_crypto_module = CryptoModule::new_legacy_module(cipher, use_random_iv)?; | ||
let legacy_encrypt_result = legacy_crypto_module.encrypt(source_data.clone()); | ||
|
||
println!("encrypt with legacy AES-CBC result: {legacy_encrypt_result:?}"); | ||
|
||
// Crypto module with enhanced AES-CBC cryptor (with legacy AES-CBC decrypt | ||
// support). | ||
let crypto_module = CryptoModule::new_aes_cbc_module(cipher, use_random_iv)?; | ||
let encrypt_result = crypto_module.encrypt(source_data.clone()); | ||
|
||
println!("encrypt with enhanced AES-CBC result: {encrypt_result:?}"); | ||
|
||
// Decrypt data created with legacy AES-CBC crypto module. | ||
let legacy_decrypt_result = crypto_module.decrypt(legacy_encrypt_result.ok().unwrap())?; | ||
assert_eq!(legacy_decrypt_result, source_data); | ||
|
||
// Decrypt data created with enhanced AES-CBC crypto module. | ||
let decrypt_result = legacy_crypto_module.decrypt(encrypt_result.ok().unwrap())?; | ||
assert_eq!(decrypt_result, source_data); | ||
|
||
// -------------------------------------------- | ||
// Automated encryption and decryption example. | ||
// | ||
|
||
// Setup client with crypto module | ||
let publish_key = env::var("SDK_PUB_KEY")?; | ||
let subscribe_key = env::var("SDK_SUB_KEY")?; | ||
|
||
let client = PubNubClientBuilder::with_reqwest_transport() | ||
.with_keyset(Keyset { | ||
subscribe_key, | ||
publish_key: Some(publish_key), | ||
secret_key: None, | ||
}) | ||
.with_user_id("user_id") | ||
.with_cryptor(crypto_module) | ||
.build()?; | ||
|
||
// publish encrypted string | ||
let result = client | ||
.publish_message("hello world!") | ||
.channel("my_channel") | ||
.r#type("text-message") | ||
.execute() | ||
.await?; | ||
|
||
println!("publish result: {:?}", result); | ||
|
||
Ok(()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
//! # Crypto provider module | ||
//! | ||
//! This module contains the [`CryptoProvider`] trait, which is used to | ||
//! implement a module that can be used to configure [`PubNubClientInstance`] or | ||
//! for manual data encryption and decryption. | ||
|
||
use crate::{ | ||
core::PubNubError, | ||
lib::{alloc::vec::Vec, core::fmt::Debug}, | ||
}; | ||
|
||
/// Crypto provider trait. | ||
pub trait CryptoProvider: Debug + Send + Sync { | ||
/// Encrypt provided data. | ||
/// | ||
/// # Errors | ||
/// Should return an [`PubNubError::Encryption`] if provided data can't be | ||
/// _encrypted_ or underlying cryptor misconfigured. | ||
fn encrypt(&self, data: Vec<u8>) -> Result<Vec<u8>, PubNubError>; | ||
|
||
/// Decrypt provided data. | ||
/// | ||
/// # Errors | ||
/// Should return an [`PubNubError::Decryption`] if provided data can't be | ||
/// _decrypted_ or underlying cryptor misconfigured. | ||
fn decrypt(&self, data: Vec<u8>) -> Result<Vec<u8>, PubNubError>; | ||
} |
Oops, something went wrong.