secrecy-0.8.0/.cargo_vcs_info.json0000644000000001120000000000000124670ustar { "git": { "sha1": "a34b56b770de12734056456acef370fe3f39e2b6" } } secrecy-0.8.0/CHANGELOG.md000064400000000000000000000072130000000000000130570ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## 0.8.0 (2021-07-18) NOTE: This release includes an MSRV bump to Rust 1.51. Please use `secrecy = "0.7.0"` if you would like to support older Rust versions. ### Added - impl `From` for `Secret` ([#482]) ### Changed - Bump `bytes` to v1.0 ([#592]) - Switch to `resolver = "2"`; MSRV 1.51 ([#755]) [#482]: https://github.com/iqlusioninc/crates/pull/482 [#592]: https://github.com/iqlusioninc/crates/pull/592 [#755]: https://github.com/iqlusioninc/crates/pull/755 ## 0.7.0 (2020-07-08) ### Added - Re-export zeroize ([#466]) - `rustdoc` improvements ([#464], [#465]) ### Changed - Have `DebugSecret` take a formatter ([#467]) - Make `FromStr` impl for `SecretString` be `Infallible` ([#323]) ### Fixed - Use `SerializableSecret` in `Serialize` bounds ([#463]) [#467]: https://github.com/iqlusioninc/crates/pull/467 [#466]: https://github.com/iqlusioninc/crates/pull/466 [#465]: https://github.com/iqlusioninc/crates/pull/465 [#464]: https://github.com/iqlusioninc/crates/pull/464 [#463]: https://github.com/iqlusioninc/crates/pull/463 [#323]: https://github.com/iqlusioninc/crates/pull/323 ## 0.6.0 (2019-12-12) - Impl `CloneableSecret` for `Secret<[T; N]>` where `T: Clone` ([#311]) - Impl `DebugSecret` for `[T; N]` where `N` <= 64 ([#310]) - Impl `FromStr` for `SecretString` ([#309]) - Upgrade to `bytes` v0.5 ([#301], [#308], [#312]) [#312]: https://github.com/iqlusioninc/crates/pull/312 [#311]: https://github.com/iqlusioninc/crates/pull/311 [#310]: https://github.com/iqlusioninc/crates/pull/310 [#309]: https://github.com/iqlusioninc/crates/pull/309 [#308]: https://github.com/iqlusioninc/crates/pull/308 [#301]: https://github.com/iqlusioninc/crates/pull/301 ## 0.5.2 (2019-12-18) - Backport Impl `FromStr` for `SecretString` ([#309]) [#309]: https://github.com/iqlusioninc/crates/pull/309 ## 0.5.1 (2019-11-30) - Change default `DebugSecret` string to `[REDACTED]` ([#290]) [#290]: https://github.com/iqlusioninc/crates/pull/290 ## 0.5.0 (2019-10-13) - Upgrade to `zeroize` v1.0.0 ([#279]) [#279]: https://github.com/iqlusioninc/crates/pull/279 ## 0.4.1 (2019-10-13) - Upgrade to `zeroize` v1.0.0-pre ([#268]) [#268]: https://github.com/iqlusioninc/crates/pull/268 ## 0.4.0 (2019-09-03) - Add `SerializableSecret` ([#262]) - Add (optional) concrete `SecretBytes` type ([#258], [#259], [#260], [#261]) [#262]: https://github.com/iqlusioninc/crates/pull/262 [#261]: https://github.com/iqlusioninc/crates/pull/261 [#260]: https://github.com/iqlusioninc/crates/pull/260 [#259]: https://github.com/iqlusioninc/crates/pull/259 [#258]: https://github.com/iqlusioninc/crates/pull/258 ## 0.3.1 (2019-08-26) - Impl `CloneableSecret` for `String` ([#256]) [#256]: https://github.com/iqlusioninc/crates/pull/256 ## 0.3.0 (2019-08-20) - Add support for `alloc` types ([#253]) - `zeroize` v0.10.0 ([#248]) - Add a default impl for `DebugSecret` trait ([#241]) [#253]: https://github.com/iqlusioninc/crates/pull/253 [#248]: https://github.com/iqlusioninc/crates/pull/248 [#241]: https://github.com/iqlusioninc/crates/pull/241 ## 0.2.2 (2019-06-28) - README.md: add Gitter badges; update image links ([#221]) [#221]: https://github.com/iqlusioninc/crates/pull/221 ## 0.2.1 (2019-06-04) - `zeroize` v0.9.0 ([#215]) [#215]: https://github.com/iqlusioninc/crates/pull/215 ## 0.2.0 (2019-05-29) - Add `CloneableSecret` marker trait ([#210]) [#210]: https://github.com/iqlusioninc/crates/pull/210 ## 0.1.0 (2019-05-23) - Initial release secrecy-0.8.0/Cargo.toml0000644000000027300000000000000104750ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "secrecy" version = "0.8.0" authors = ["Tony Arcieri "] description = "Wrapper types and traits for secret management which help ensure\nthey aren't accidentally copied, logged, or otherwise exposed\n(as much as possible), and also ensure secrets are securely wiped\nfrom memory when dropped.\n" homepage = "https://github.com/iqlusioninc/crates/" readme = "README.md" keywords = ["clear", "memory", "secret", "secure", "wipe"] categories = ["cryptography", "memory-management", "no-std", "os"] license = "Apache-2.0 OR MIT" repository = "https://github.com/iqlusioninc/crates/tree/main/secrecy" resolver = "2" [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies.bytes] version = "1" optional = true [dependencies.serde] version = "1" optional = true [dependencies.zeroize] version = "1.4" default-features = false [features] alloc = ["zeroize/alloc"] default = ["alloc"] secrecy-0.8.0/Cargo.toml.orig000064400000000000000000000020760000000000000141370ustar 00000000000000[package] name = "secrecy" description = """ Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped. """ version = "0.8.0" # Also update html_root_url in lib.rs when bumping this authors = ["Tony Arcieri "] license = "Apache-2.0 OR MIT" edition = "2018" homepage = "https://github.com/iqlusioninc/crates/" repository = "https://github.com/iqlusioninc/crates/tree/main/secrecy" readme = "README.md" categories = ["cryptography", "memory-management", "no-std", "os"] keywords = ["clear", "memory", "secret", "secure", "wipe"] [dependencies] zeroize = { version = "1.4", path = "../zeroize", default-features = false } # optional dependencies bytes = { version = "1", optional = true } serde = { version = "1", optional = true } [features] default = ["alloc"] alloc = ["zeroize/alloc"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] secrecy-0.8.0/LICENSE-APACHE000064400000000000000000000261360000000000000131770ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. secrecy-0.8.0/LICENSE-MIT000064400000000000000000000020510000000000000126750ustar 00000000000000MIT License Copyright (c) 2019 iqlusion 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 permission notice shall be included in all copies or substantial portions of 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 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. secrecy-0.8.0/README.md000064400000000000000000000060050000000000000125230ustar 00000000000000# secrecy.rs 🤐 iqlusion [![Crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] ![Apache 2.0/MIT Licensed][license-image] ![MSRV][rustc-image] [![Safety Dance][safety-image]][safety-link] [![Build Status][build-image]][build-link] A simple secret-keeping library for Rust. [Documentation][docs-link] ## About **secrecy** is a *simple*, safe (i.e. `forbid(unsafe_code)` library which provides wrapper types and traits for secret management in Rust, namely the `Secret` type for wrapping another value in a "secret cell" which attempts to limit exposure (only available through a special `ExposeSecret` trait). This helps to ensure secrets aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensures secrets are securely wiped from memory when dropped. ## Minimum Supported Rust Version Rust **1.51** or newer. In the future, we reserve the right to change MSRV (i.e. MSRV is out-of-scope for this crate's SemVer guarantees), however when we do it will be accompanied by a minor version bump. ## serde support Optional `serde` support for parsing owned secret values is available, gated under the `serde` cargo feature. It uses the `Deserialize` and `DeserializeOwned` traits to implement deserializing secret types which also impl these traits. This doesn't guarantee `serde` (or code providing input to `serde`) won't accidentally make additional copies of the secret, but does the best it can with what it is given and tries to minimize risk of exposure as much as possible. ## License Copyright © 2019-2021 iqlusion **secrecy** is distributed under the terms of either the MIT license or the Apache License (Version 2.0), at your option. See [LICENSE] (Apache License, Version 2.0) file in the `iqlusioninc/crates` toplevel directory of this repository or [LICENSE-MIT] for details. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. [//]: # (badges) [crate-image]: https://img.shields.io/crates/v/secrecy.svg [crate-link]: https://crates.io/crates/secrecy [docs-image]: https://docs.rs/secrecy/badge.svg [docs-link]: https://docs.rs/secrecy/ [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [rustc-image]: https://img.shields.io/badge/rustc-1.51+-blue.svg [safety-image]: https://img.shields.io/badge/unsafe-forbidden-success.svg [safety-link]: https://github.com/rust-secure-code/safety-dance/ [build-image]: https://github.com/iqlusioninc/crates/actions/workflows/secrecy.yml/badge.svg [build-link]: https://github.com/iqlusioninc/crates/actions/workflows/secrecy.yml [//]: # (general links) [LICENSE]: https://github.com/iqlusioninc/crates/blob/main/LICENSE [LICENSE-MIT]: https://github.com/iqlusioninc/crates/blob/main/secrecy/LICENSE-MIT secrecy-0.8.0/src/boxed.rs000064400000000000000000000004610000000000000135020ustar 00000000000000//! `Box` types containing secrets use super::{DebugSecret, Secret}; use alloc::boxed::Box; use zeroize::Zeroize; /// `Box` types containing a secret value #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub type SecretBox = Secret>; impl DebugSecret for Box {} secrecy-0.8.0/src/bytes.rs000064400000000000000000000054330000000000000135330ustar 00000000000000//! Optional `Secret` wrapper type for the `bytes::BytesMut` crate. use super::ExposeSecret; use bytes::BytesMut; use core::fmt; use zeroize::Zeroize; #[cfg(all(feature = "bytes", feature = "serde"))] use serde::de::{self, Deserialize}; /// Instance of [`BytesMut`] protected by a type that impls the [`ExposeSecret`] /// trait like `Secret`. /// /// Because of the nature of how the `BytesMut` type works, it needs some special /// care in order to have a proper zeroizing drop handler. #[derive(Clone)] #[cfg_attr(docsrs, doc(cfg(feature = "bytes")))] pub struct SecretBytesMut(BytesMut); impl SecretBytesMut { /// Wrap bytes in `SecretBytesMut` pub fn new(bytes: impl Into) -> SecretBytesMut { SecretBytesMut(bytes.into()) } } impl ExposeSecret for SecretBytesMut { fn expose_secret(&self) -> &BytesMut { &self.0 } } impl fmt::Debug for SecretBytesMut { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SecretBytesMut([REDACTED])") } } impl From for SecretBytesMut { fn from(bytes: BytesMut) -> SecretBytesMut { SecretBytesMut::new(bytes) } } impl Drop for SecretBytesMut { fn drop(&mut self) { self.0.resize(self.0.capacity(), 0); self.0.as_mut().zeroize(); debug_assert!(self.0.as_ref().iter().all(|b| *b == 0)); } } #[cfg(all(feature = "bytes", feature = "serde"))] impl<'de> Deserialize<'de> for SecretBytesMut { fn deserialize>(deserializer: D) -> Result { struct SecretBytesVisitor; impl<'de> de::Visitor<'de> for SecretBytesVisitor { type Value = SecretBytesMut; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("byte array") } #[inline] fn visit_bytes(self, v: &[u8]) -> Result where E: de::Error, { let mut bytes = BytesMut::with_capacity(v.len()); bytes.extend_from_slice(v); Ok(SecretBytesMut(bytes)) } #[inline] fn visit_seq(self, mut seq: V) -> Result where V: de::SeqAccess<'de>, { // 4096 is cargo culted from upstream let len = core::cmp::min(seq.size_hint().unwrap_or(0), 4096); let mut bytes = BytesMut::with_capacity(len); use bytes::BufMut; while let Some(value) = seq.next_element()? { bytes.put_u8(value); } Ok(SecretBytesMut(bytes)) } } deserializer.deserialize_bytes(SecretBytesVisitor) } } secrecy-0.8.0/src/lib.rs000064400000000000000000000206750000000000000131600ustar 00000000000000//! [`Secret`] wrapper type for more carefully handling secret values //! (e.g. passwords, cryptographic keys, access tokens or other credentials) //! //! # Goals //! //! - Make secret access explicit and easy-to-audit via the //! [`ExposeSecret`] trait. This also makes secret values immutable which //! helps avoid making accidental copies (e.g. reallocating the backing //! buffer for a `Vec`) //! - Prevent accidental leakage of secrets via channels like debug logging //! - Ensure secrets are wiped from memory on drop securely //! (using the [`zeroize`] crate) //! //! Presently this crate favors a simple, `no_std`-friendly, safe i.e. //! `forbid(unsafe_code)`-based implementation and does not provide more advanced //! memory protection mechanisms e.g. ones based on `mlock(2)`/`mprotect(2)`. //! We may explore more advanced protection mechanisms in the future. //! //! # `Box`, `String`, and `Vec` wrappers //! //! Most users of this crate will simply want [`Secret`] wrappers around Rust's //! core collection types: i.e. `Box`, `String`, and `Vec`. //! //! When the `alloc` feature of this crate is enabled (which it is by default), //! [`SecretBox`], [`SecretString`], and [`SecretVec`] type aliases are //! available. //! //! There's nothing particularly fancy about these: they're just the simple //! composition of `Secret>`, `Secret`, and `Secret>`! //! However, in many cases they're all you will need. //! //! # Advanced usage //! //! If you are hitting limitations on what's possible with the collection type //! wrappers, you'll want to define your own newtype which lets you customize //! the implementation: //! //! ```rust //! use secrecy::{CloneableSecret, DebugSecret, Secret, Zeroize}; //! //! #[derive(Clone)] //! pub struct AccountNumber(String); //! //! impl Zeroize for AccountNumber { //! fn zeroize(&mut self) { //! self.0.zeroize(); //! } //! } //! //! /// Permits cloning //! impl CloneableSecret for AccountNumber {} //! //! /// Provides a `Debug` impl (by default `[[REDACTED]]`) //! impl DebugSecret for AccountNumber {} //! //! /// Use this alias when storing secret values //! pub type SecretAccountNumber = Secret; //! ``` //! //! # `serde` support //! //! When the `serde` feature of this crate is enabled, the [`Secret`] type will //! receive a [`Deserialize`] impl for all `Secret` types where //! `T: DeserializeOwned`. This allows *loading* secret values from data //! deserialized from `serde` (be careful to clean up any intermediate secrets //! when doing this, e.g. the unparsed input!) //! //! To prevent exfiltration of secret values via `serde`, by default `Secret` //! does *not* receive a corresponding [`Serialize`] impl. If you would like //! types of `Secret` to be serializable with `serde`, you will need to impl //! the [`SerializableSecret`] marker trait on `T`. #![no_std] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc(html_root_url = "https://docs.rs/secrecy/0.8.0")] #![forbid(unsafe_code)] #![warn(missing_docs, rust_2018_idioms, unused_qualifications)] #[cfg(feature = "alloc")] extern crate alloc; #[cfg(feature = "alloc")] mod boxed; #[cfg(feature = "bytes")] mod bytes; #[cfg(feature = "alloc")] mod string; #[cfg(feature = "alloc")] mod vec; pub use zeroize::{self, Zeroize}; #[cfg(feature = "alloc")] pub use self::{boxed::SecretBox, string::SecretString, vec::SecretVec}; #[cfg(feature = "bytes")] pub use self::bytes::SecretBytesMut; use core::{ any, fmt::{self, Debug}, }; #[cfg(feature = "serde")] use serde::{de, ser, Deserialize, Serialize}; /// Wrapper type for values that contains secrets, which attempts to limit /// accidental exposure and ensure secrets are wiped from memory when dropped. /// (e.g. passwords, cryptographic keys, access tokens or other credentials) /// /// Access to the secret inner value occurs through the [`ExposeSecret`] trait, /// which provides an `expose_secret()` method for accessing the inner secret /// value. pub struct Secret where S: Zeroize, { /// Inner secret value inner_secret: S, } impl Secret where S: Zeroize, { /// Take ownership of a secret value pub fn new(secret: S) -> Self { Secret { inner_secret: secret, } } } impl ExposeSecret for Secret where S: Zeroize, { fn expose_secret(&self) -> &S { &self.inner_secret } } impl From for Secret where S: Zeroize, { fn from(secret: S) -> Self { Self::new(secret) } } impl Clone for Secret where S: CloneableSecret, { fn clone(&self) -> Self { Secret { inner_secret: self.inner_secret.clone(), } } } impl Debug for Secret where S: Zeroize + DebugSecret, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Secret(")?; S::debug_secret(f)?; f.write_str(")") } } impl Drop for Secret where S: Zeroize, { fn drop(&mut self) { // Zero the secret out from memory self.inner_secret.zeroize(); } } /// Marker trait for secrets which are allowed to be cloned pub trait CloneableSecret: Clone + Zeroize {} /// Implement `CloneableSecret` on arrays of types that impl `Clone` and /// `Zeroize`. macro_rules! impl_cloneable_secret_for_array { ($($size:expr),+) => { $( impl CloneableSecret for [T; $size] {} )+ }; } // TODO(tarcieri): const generics impl_cloneable_secret_for_array!( 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 ); /// Expose a reference to an inner secret pub trait ExposeSecret { /// Expose secret: this is the only method providing access to a secret. fn expose_secret(&self) -> &S; } /// Debugging trait which is specialized for handling secret values pub trait DebugSecret { /// Format information about the secret's type. /// /// This can be thought of as an equivalent to [`Debug::fmt`], but one /// which by design does not permit access to the secret value. fn debug_secret(f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.write_str("[REDACTED ")?; f.write_str(any::type_name::())?; f.write_str("]") } } /// Implement `DebugSecret` on arrays of types that impl `Debug`. macro_rules! impl_debug_secret_for_array { ($($size:expr),+) => { $( impl DebugSecret for [T; $size] {} )+ }; } // TODO(tarcieri): const generics impl_debug_secret_for_array!( 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 ); /// Marker trait for secret types which can be [`Serialize`]-d by [`serde`]. /// /// When the `serde` feature of this crate is enabled and types are marked with /// this trait, they receive a [`Serialize` impl][1] for `Secret`. /// (NOTE: all types which impl `DeserializeOwned` receive a [`Deserialize`] /// impl) /// /// This is done deliberately to prevent accidental exfiltration of secrets /// via `serde` serialization. /// /// If you are working with [`SecretString`] or [`SecretVec`], not that /// by design these types do *NOT* impl this trait. /// /// If you really want to have `serde` serialize those types, use the /// [`serialize_with`][2] attribute to specify a serializer that exposes the secret. /// /// [1]: https://docs.rs/secrecy/latest/secrecy/struct.Secret.html#implementations /// [2]: https://serde.rs/field-attrs.html#serialize_with #[cfg(feature = "serde")] #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] pub trait SerializableSecret: Serialize {} #[cfg(feature = "serde")] impl<'de, T> Deserialize<'de> for Secret where T: Zeroize + Clone + de::DeserializeOwned + Sized, { fn deserialize(deserializer: D) -> Result where D: de::Deserializer<'de>, { T::deserialize(deserializer).map(Secret::new) } } #[cfg(feature = "serde")] impl Serialize for Secret where T: Zeroize + SerializableSecret + Serialize + Sized, { fn serialize(&self, serializer: S) -> Result where S: ser::Serializer, { self.expose_secret().serialize(serializer) } } secrecy-0.8.0/src/string.rs000064400000000000000000000007620000000000000137130ustar 00000000000000//! Secret strings use super::{CloneableSecret, DebugSecret, Secret}; use alloc::str::FromStr; use alloc::string::{String, ToString}; /// Secret strings #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub type SecretString = Secret; impl DebugSecret for String {} impl CloneableSecret for String {} impl FromStr for SecretString { type Err = core::convert::Infallible; fn from_str(src: &str) -> Result { Ok(SecretString::new(src.to_string())) } } secrecy-0.8.0/src/vec.rs000064400000000000000000000005630000000000000131610ustar 00000000000000//! Secret `Vec` types use super::{CloneableSecret, DebugSecret, Secret}; use alloc::vec::Vec; use zeroize::Zeroize; /// `Vec` types containing secret value #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub type SecretVec = Secret>; impl CloneableSecret for Vec {} impl DebugSecret for Vec {}