├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── NOTES_ON_PORT.md ├── README.md ├── examples └── example.rs └── src ├── blocking ├── collection.rs ├── item.rs └── mod.rs ├── collection.rs ├── error.rs ├── item.rs ├── lib.rs ├── proxy ├── collection.rs ├── item.rs ├── mod.rs ├── prompt.rs └── service.rs ├── session.rs ├── ss.rs └── util.rs /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | permissions: 3 | contents: read 4 | 5 | on: 6 | pull_request: 7 | push: 8 | branches: 9 | - master 10 | 11 | env: 12 | CARGO_NET_RETRY: 3 13 | 14 | jobs: 15 | clippy: 16 | name: Clippy 17 | runs-on: ubuntu-latest 18 | 19 | strategy: 20 | matrix: 21 | rust: 22 | - stable 23 | feature: 24 | - rt-async-io-crypto-rust 25 | - rt-async-io-crypto-openssl 26 | - rt-tokio-crypto-rust 27 | - rt-tokio-crypto-openssl 28 | 29 | steps: 30 | - uses: actions/checkout@v4 31 | with: 32 | persist-credentials: false 33 | 34 | - uses: actions-rust-lang/setup-rust-toolchain@v1 35 | with: 36 | toolchain: ${{ matrix.rust }} 37 | components: clippy 38 | 39 | - uses: actions/cache@v4 40 | with: 41 | path: | 42 | ~/.cargo/registry 43 | ~/.cargo/git 44 | target 45 | key: $clippy-cache-${{ steps.toolchain.outputs.rustc_hash }}-${{ hashFiles('**/Cargo.lock') }} 46 | 47 | - name: "Clippy ${{ matrix.rust }}" 48 | run: cargo clippy --features=${{ matrix.feature }} --all-targets --all -- -D clippy::dbg_macro -D warnings -F unused_must_use 49 | 50 | fmt: 51 | name: Rustfmt 52 | runs-on: ubuntu-latest 53 | 54 | steps: 55 | - uses: actions/checkout@v4 56 | with: 57 | persist-credentials: false 58 | 59 | - uses: actions-rust-lang/setup-rust-toolchain@v1 60 | with: 61 | toolchain: stable 62 | components: rustfmt 63 | 64 | - name: "Check formatting" 65 | run: cargo fmt --all -- --check 66 | 67 | test: 68 | name: Tests 69 | runs-on: ubuntu-latest 70 | 71 | strategy: 72 | matrix: 73 | rust: 74 | - stable 75 | feature: 76 | - rt-async-io-crypto-rust 77 | - rt-async-io-crypto-openssl 78 | - rt-tokio-crypto-rust 79 | - rt-tokio-crypto-openssl 80 | 81 | steps: 82 | - uses: actions/checkout@v4 83 | with: 84 | persist-credentials: false 85 | 86 | - uses: actions-rust-lang/setup-rust-toolchain@v1 87 | with: 88 | toolchain: ${{ matrix.rust }} 89 | 90 | - uses: actions/cache@v4 91 | with: 92 | path: | 93 | ~/.cargo/registry 94 | ~/.cargo/git 95 | target 96 | key: $test-cache-${{ steps.toolchain.outputs.rustc_hash }}-${{ hashFiles('**/Cargo.lock') }} 97 | 98 | - name: Install gnome-keyring 99 | run: sudo apt-get install -y gnome-keyring 100 | 101 | - name: Start gnome-keyring 102 | # run gnome-keyring with 'foobar' as password for the login keyring 103 | # this will create a new login keyring and unlock it 104 | # the login password doesn't matter, but the keyring must be unlocked for the tests to work 105 | run: gnome-keyring-daemon --components=secrets --daemonize --unlock <<< 'foobar' 106 | 107 | - name: Run tests 108 | # run tests single-threaded to avoid race conditions 109 | run: cargo test --features=${{ matrix.feature }} -- --test-threads=1 110 | 111 | - name: Run example 112 | run: cargo run --features=${{ matrix.feature }} --example example 113 | 114 | # MSRV, influenced by zbus. 115 | check_msrv: 116 | name: Check MSRV 117 | runs-on: ubuntu-latest 118 | 119 | strategy: 120 | matrix: 121 | feature: 122 | - rt-async-io-crypto-rust 123 | - rt-async-io-crypto-openssl 124 | - rt-tokio-crypto-rust 125 | - rt-tokio-crypto-openssl 126 | 127 | steps: 128 | - uses: actions/checkout@v4 129 | with: 130 | persist-credentials: false 131 | 132 | - uses: actions-rust-lang/setup-rust-toolchain@v1 133 | with: 134 | toolchain: "1.77.0" 135 | components: clippy 136 | 137 | - uses: actions/cache@v4 138 | with: 139 | path: | 140 | ~/.cargo/registry 141 | ~/.cargo/git 142 | target 143 | key: $clippy-cache-${{ steps.toolchain.outputs.rustc_hash }}-${{ hashFiles('**/Cargo.lock') }} 144 | 145 | - name: Generate lockfile 146 | run: | 147 | cargo generate-lockfile 148 | 149 | - name: Clippy MSRV 150 | run: cargo clippy --features=${{ matrix.feature }} --all-targets --all -- -D clippy::dbg_macro -D warnings -F unused_must_use 151 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | target 3 | Cargo.lock 4 | 5 | .vscode/ -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | The detailed list of changes in each release can be found at https://github.com/hwchen/secret-service-rs/releases. -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Walther Chen "] 3 | description = "Library to interface with Secret Service API" 4 | documentation = "https://docs.rs/secret-service" 5 | homepage = "https://github.com/hwchen/secret-service-rs.git" 6 | keywords = ["secret-service", "password", "linux", "keychain"] 7 | license = "MIT OR Apache-2.0" 8 | name = "secret-service" 9 | repository = "https://github.com/hwchen/secret-service-rs.git" 10 | edition = "2021" 11 | version = "5.0.0" 12 | rust-version = "1.77.0" 13 | 14 | # The async runtime features mirror those of `zbus` for compatibility. 15 | [features] 16 | crypto-rust = ["dep:aes", "dep:cbc", "dep:sha2", "dep:hkdf"] 17 | crypto-openssl = ["dep:openssl"] 18 | 19 | rt-async-io-crypto-rust = ["zbus/async-io", "crypto-rust"] 20 | rt-async-io-crypto-openssl = ["zbus/async-io", "crypto-openssl"] 21 | 22 | rt-tokio-crypto-rust = ["zbus/tokio", "crypto-rust"] 23 | rt-tokio-crypto-openssl = ["zbus/tokio", "crypto-openssl"] 24 | 25 | [dependencies] 26 | aes = { version = "0.8", optional = true } 27 | cbc = { version = "0.1", features = ["block-padding", "alloc"] , optional = true } 28 | hkdf = { version = "0.12.0", optional = true } 29 | generic-array = "0.14" 30 | once_cell = "1" 31 | futures-util = "0.3" 32 | num = "0.4.0" 33 | getrandom = "0.2" 34 | serde = { version = "1.0.103", features = ["derive"] } 35 | sha2 = { version = "0.10.0", optional = true } 36 | zbus = { version = "5", default-features = false, features = [ "blocking-api" ] } 37 | openssl = { version = "^0.10.40", optional = true } 38 | 39 | [dev-dependencies] 40 | tokio = { version = "1", features = ["rt", "macros"] } 41 | test-with = { version = "0.8", default-features = false } 42 | 43 | [package.metadata.docs.rs] 44 | features = ["rt-tokio-crypto-rust"] 45 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2025 secret-service Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /NOTES_ON_PORT.md: -------------------------------------------------------------------------------- 1 | # Notes on porting to zbus 2 | 3 | Plan: start a section of code that will be easy convert to zbus, while keeping dbus dependency. I think that this would be `Item`, which is a "leaf" struct (meaning it doesn't create other dbus-connected structs). This way I only have to worry about any data being received, and not so much data being returned. 4 | 5 | Plan, revised: I should still start with Item. However, the place where I'll slide zbus in is a little different then I had thought. This is because my code currently is structured: 6 | - With an `Interface` (which should actually be called a `proxy` that talks to the interface) that is a very low-level implementation of basics like method calls. 7 | - And then all the details of talking to the service interface are handled directly in `Item`'s methods. 8 | 9 | With zbus, I would instead have: 10 | - A derived `dbus_proxy`, which would set up all the boilerplate for talking to a an interface, and then 11 | - Methods in `Item` would generally just be calling the derived `dbus_proxy`. 12 | - This means that with zbus, I should be able to get rid of `Interface`. 13 | 14 | So, my first step should be to replace usage of the `Item` proxy. 15 | 16 | ## First Pass 17 | Creating proxy was nice, and removed a lot of my boilerplate. 18 | 19 | One issue was lifetimes for using a path in creating a new proxy. I had wanted to store the proxy in the `Item` struct, but I needed to borrow the `item_path`, which wouldn't live long enough. I ended up instantiating a new proxy on each `Item` method, which didn't feel as good. 20 | 21 | Now, getting some test errors. One is that session doesn't exist. 22 | 23 | ## Second Pass 24 | First finished creating all the proxies. 25 | 26 | I found `Proxy::new_for_owned` which removed the instantiation of a proxy per-method, now the `Proxy` can be saved in the struct. 27 | 28 | There's a weird issue where on a derived `property` it allows `ObjectPath` in the return, but on methods it requires `OwnedObjectPath`. Seems to work ok, oh well. 29 | 30 | Looks like `SecretStruct` needs to be wrapped in another struct in order to fit the dbus signature, not sure what that's about. 31 | 32 | Otherwise pretty straightforward. Removing the low-level details of creating dbus types allowed me to refactor much more easily. 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Secret Service 2 | 3 | [![crates.io version](https://img.shields.io/crates/v/secret-service.svg)](https://crates.io/crates/secret-service) 4 | [![crate documentation](https://docs.rs/secret-service/badge.svg)](https://docs.rs/secret-service) 5 | ![MSRV](https://img.shields.io/badge/rustc-1.77+-blue.svg) 6 | [![crates.io downloads](https://img.shields.io/crates/d/secret-service.svg)](https://crates.io/crates/secret-service) 7 | ![CI](https://github.com/hwchen/secret-service-rs/workflows/CI/badge.svg) 8 | 9 | A rust library for interacting with the FreeDesktop Secret Service API through DBus. 10 | 11 | ### Basic Usage 12 | 13 | `secret-service` is implemented in pure Rust by default, so it doesn't require any system libraries 14 | such as `libdbus-1-dev` or `libdbus-1-3` on Ubuntu. 15 | 16 | In Cargo.toml: 17 | 18 | When adding the crate, you must select a feature representing your selected runtime and cryptography backend. 19 | For example: 20 | 21 | ```toml 22 | [dependencies] 23 | secret-service = { version = "5.0.0", features = ["rt-tokio-crypto-rust"] } 24 | ``` 25 | 26 | Available feature flags: 27 | - `rt-async-io-crypto-rust`: Uses the `async-std` runtime and pure Rust crytography via `RustCrypto`. 28 | - `rt-async-io-crypto-openssl`: Uses the `async-std` runtime and OpenSSL as the cryptography provider. 29 | - `rt-tokio-crypto-rust`: Uses the `tokio` runtime and pure Rust cryptography via `RustCrypto`. 30 | - `rt-tokio-crypto-openssl`: Uses the `tokio` runtime and OpenSSL as the cryptography provider. 31 | 32 | Note that the `-openssl` feature sets require OpenSSL to be available on your system, or the `bundled` feature 33 | of `openssl` crate must be activated in your `cargo` dependency tree instead. 34 | 35 | In source code (below example is for `--bin`, not `--lib`). This example uses `tokio` as 36 | the async runtime. 37 | 38 | ```rust 39 | use secret_service::SecretService; 40 | use secret_service::EncryptionType; 41 | use std::{collections::HashMap, error::Error}; 42 | 43 | #[tokio::main] 44 | async fn main() -> Result<(), Box> { 45 | // initialize secret service (dbus connection and encryption session) 46 | let ss = SecretService::connect(EncryptionType::Dh).await?; 47 | 48 | // get default collection 49 | let collection = ss.get_default_collection().await?; 50 | 51 | // create new item 52 | collection.create_item( 53 | "test_label", // label 54 | HashMap::from([("test", "test_value")]), // properties 55 | b"test_secret", // secret 56 | false, // replace item with same attributes 57 | "text/plain" // secret content type 58 | ).await?; 59 | 60 | // search items by properties 61 | let search_items = ss.search_items( 62 | HashMap::from([("test", "test_value")]) 63 | ).await?; 64 | 65 | let item = search_items.unlocked.first().ok_or("Not found!")?; 66 | 67 | // retrieve secret from item 68 | let secret = item.get_secret().await?; 69 | assert_eq!(secret, b"test_secret"); 70 | 71 | // delete item (deletes the dbus object, not the struct instance) 72 | item.delete().await?; 73 | Ok(()) 74 | } 75 | ``` 76 | 77 | ### Functionality 78 | 79 | - SecretService: initialize dbus, create plain/encrypted session. 80 | - Collections: create, delete, search. 81 | - Items: create, delete, search, get/set secret. 82 | 83 | ### Changelog 84 | See [the list of GitHub releases and their release notes](https://github.com/hwchen/secret-service-rs/releases) 85 | 86 | ### Versioning 87 | This library is feature complete, has stabilized its API for the most part. However, as this 88 | crate is almost soley reliable on the `zbus` crate, we try and match major version releases 89 | with theirs to handle breaking changes and move with the wider `zbus` ecosystem. 90 | 91 | ## License 92 | 93 | Licensed under either of 94 | 95 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 96 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 97 | 98 | at your option. 99 | 100 | ### Contribution 101 | 102 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 103 | -------------------------------------------------------------------------------- /examples/example.rs: -------------------------------------------------------------------------------- 1 | use secret_service::{EncryptionType, SecretService}; 2 | use std::{collections::HashMap, str}; 3 | 4 | #[tokio::main(flavor = "current_thread")] 5 | async fn main() { 6 | // Initialize secret service 7 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 8 | 9 | // navigate to default collection 10 | let collection = ss.get_default_collection().await.unwrap(); 11 | 12 | let mut properties = HashMap::new(); 13 | properties.insert("test", "test_value"); 14 | 15 | //create new item 16 | collection 17 | .create_item( 18 | "test_label", // label 19 | properties, 20 | b"test_secret", //secret 21 | false, // replace item with same attributes 22 | "text/plain", // secret content type 23 | ) 24 | .await 25 | .unwrap(); 26 | 27 | //println!("New Item: {:?}", new_item); 28 | 29 | // search items by properties 30 | let mut search_properties = HashMap::new(); 31 | search_properties.insert("test", "test_value"); 32 | 33 | let search_items = ss.search_items(search_properties).await.unwrap(); 34 | 35 | //println!("Searched Item: {:?}", search_items); 36 | 37 | // retrieve one item, first by checking the unlocked items 38 | let item = match search_items.unlocked.first() { 39 | Some(item) => item, 40 | None => { 41 | // if there aren't any, check the locked items and unlock the first one 42 | let locked_item = search_items 43 | .locked 44 | .first() 45 | .expect("Search didn't return any items!"); 46 | locked_item.unlock().await.unwrap(); 47 | locked_item 48 | } 49 | }; 50 | 51 | // retrieve secret from item 52 | let secret = item.get_secret().await.unwrap(); 53 | println!("Retrieved secret: {:?}", str::from_utf8(&secret).unwrap()); 54 | assert_eq!(secret, b"test_secret"); 55 | item.delete().await.unwrap(); 56 | } 57 | -------------------------------------------------------------------------------- /src/blocking/collection.rs: -------------------------------------------------------------------------------- 1 | use super::item::Item; 2 | use crate::error::Error; 3 | use crate::proxy::collection::CollectionProxyBlocking; 4 | use crate::proxy::service::ServiceProxyBlocking; 5 | use crate::session::Session; 6 | use crate::ss::{SS_DBUS_NAME, SS_ITEM_ATTRIBUTES, SS_ITEM_LABEL}; 7 | use crate::util::{exec_prompt_blocking, format_secret, lock_or_unlock_blocking, LockAction}; 8 | 9 | use std::collections::HashMap; 10 | use zbus::{ 11 | proxy::CacheProperties, 12 | zvariant::{Dict, ObjectPath, OwnedObjectPath, Value}, 13 | }; 14 | 15 | // Collection struct. 16 | // Should always be created from the SecretService entry point, 17 | // whether through a new collection or a collection search 18 | pub struct Collection<'a> { 19 | conn: zbus::blocking::Connection, 20 | session: &'a Session, 21 | pub collection_path: OwnedObjectPath, 22 | collection_proxy: CollectionProxyBlocking<'a>, 23 | service_proxy: &'a ServiceProxyBlocking<'a>, 24 | } 25 | 26 | impl<'a> Collection<'a> { 27 | pub(crate) fn new( 28 | conn: zbus::blocking::Connection, 29 | session: &'a Session, 30 | service_proxy: &'a ServiceProxyBlocking, 31 | collection_path: OwnedObjectPath, 32 | ) -> Result { 33 | let collection_proxy = CollectionProxyBlocking::builder(&conn) 34 | .destination(SS_DBUS_NAME)? 35 | .path(collection_path.clone())? 36 | .cache_properties(CacheProperties::No) 37 | .build()?; 38 | Ok(Collection { 39 | conn, 40 | session, 41 | collection_path, 42 | collection_proxy, 43 | service_proxy, 44 | }) 45 | } 46 | 47 | pub fn is_locked(&self) -> Result { 48 | Ok(self.collection_proxy.locked()?) 49 | } 50 | 51 | pub fn ensure_unlocked(&self) -> Result<(), Error> { 52 | if self.is_locked()? { 53 | Err(Error::Locked) 54 | } else { 55 | Ok(()) 56 | } 57 | } 58 | 59 | pub fn unlock(&self) -> Result<(), Error> { 60 | lock_or_unlock_blocking( 61 | self.conn.clone(), 62 | self.service_proxy, 63 | &self.collection_path, 64 | LockAction::Unlock, 65 | ) 66 | } 67 | 68 | pub fn lock(&self) -> Result<(), Error> { 69 | lock_or_unlock_blocking( 70 | self.conn.clone(), 71 | self.service_proxy, 72 | &self.collection_path, 73 | LockAction::Lock, 74 | ) 75 | } 76 | 77 | /// Deletes dbus object, but struct instance still exists (current implementation) 78 | pub fn delete(&self) -> Result<(), Error> { 79 | // ensure_unlocked handles prompt for unlocking if necessary 80 | self.ensure_unlocked()?; 81 | let prompt_path = self.collection_proxy.delete()?; 82 | 83 | // "/" means no prompt necessary 84 | if prompt_path.as_str() != "/" { 85 | exec_prompt_blocking(self.conn.clone(), &prompt_path)?; 86 | } 87 | 88 | Ok(()) 89 | } 90 | 91 | pub fn get_all_items(&self) -> Result, Error> { 92 | let items = self.collection_proxy.items()?; 93 | 94 | // map array of item paths to Item 95 | let res = items 96 | .into_iter() 97 | .map(|item_path| { 98 | Item::new( 99 | self.conn.clone(), 100 | self.session, 101 | self.service_proxy, 102 | item_path.into(), 103 | ) 104 | }) 105 | .collect::>()?; 106 | 107 | Ok(res) 108 | } 109 | 110 | pub fn search_items(&self, attributes: HashMap<&str, &str>) -> Result, Error> { 111 | let items = self.collection_proxy.search_items(attributes)?; 112 | 113 | // map array of item paths to Item 114 | let res = items 115 | .into_iter() 116 | .map(|item_path| { 117 | Item::new( 118 | self.conn.clone(), 119 | self.session, 120 | self.service_proxy, 121 | item_path, 122 | ) 123 | }) 124 | .collect::>()?; 125 | 126 | Ok(res) 127 | } 128 | 129 | pub fn get_label(&self) -> Result { 130 | Ok(self.collection_proxy.label()?) 131 | } 132 | 133 | pub fn set_label(&self, new_label: &str) -> Result<(), Error> { 134 | Ok(self.collection_proxy.set_label(new_label)?) 135 | } 136 | 137 | pub fn create_item( 138 | &self, 139 | label: &str, 140 | attributes: HashMap<&str, &str>, 141 | secret: &[u8], 142 | replace: bool, 143 | content_type: &str, 144 | ) -> Result { 145 | let secret_struct = format_secret(self.session, secret, content_type)?; 146 | 147 | let mut properties: HashMap<&str, Value> = HashMap::new(); 148 | let attributes: Dict = attributes.into(); 149 | 150 | properties.insert(SS_ITEM_LABEL, label.into()); 151 | properties.insert(SS_ITEM_ATTRIBUTES, attributes.into()); 152 | 153 | let created_item = self 154 | .collection_proxy 155 | .create_item(properties, secret_struct, replace)?; 156 | 157 | // This prompt handling is practically identical to create_collection 158 | let item_path: ObjectPath = { 159 | // Get path of created object 160 | let created_path = created_item.item; 161 | 162 | // Check if that path is "/", if so should execute a prompt 163 | if created_path.as_str() == "/" { 164 | let prompt_path = created_item.prompt; 165 | 166 | // Exec prompt and parse result 167 | let prompt_res = exec_prompt_blocking(self.conn.clone(), &prompt_path)?; 168 | prompt_res.try_into()? 169 | } else { 170 | // if not, just return created path 171 | created_path.into() 172 | } 173 | }; 174 | 175 | Item::new( 176 | self.conn.clone(), 177 | self.session, 178 | self.service_proxy, 179 | item_path.into(), 180 | ) 181 | } 182 | } 183 | 184 | #[cfg(test)] 185 | mod test { 186 | use crate::blocking::*; 187 | 188 | #[test] 189 | fn should_create_collection_struct() { 190 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 191 | let _ = ss.get_default_collection().unwrap(); 192 | // tested under SecretService struct 193 | } 194 | 195 | #[test] 196 | fn should_check_if_collection_locked() { 197 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 198 | let collection = ss.get_default_collection().unwrap(); 199 | let _ = collection.is_locked().unwrap(); 200 | } 201 | 202 | #[test] 203 | #[ignore] // should unignore this test this manually, otherwise will constantly prompt during tests. 204 | fn should_lock_and_unlock() { 205 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 206 | let collection = ss.get_default_collection().unwrap(); 207 | let locked = collection.is_locked().unwrap(); 208 | if locked { 209 | collection.unlock().unwrap(); 210 | collection.ensure_unlocked().unwrap(); 211 | assert!(!collection.is_locked().unwrap()); 212 | collection.lock().unwrap(); 213 | assert!(collection.is_locked().unwrap()); 214 | } else { 215 | collection.lock().unwrap(); 216 | assert!(collection.is_locked().unwrap()); 217 | collection.unlock().unwrap(); 218 | collection.ensure_unlocked().unwrap(); 219 | assert!(!collection.is_locked().unwrap()); 220 | } 221 | } 222 | 223 | #[test] 224 | #[ignore] 225 | fn should_delete_collection() { 226 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 227 | let collections = ss.get_all_collections().unwrap(); 228 | let count_before = collections.len(); 229 | for collection in collections { 230 | let collection_path = &*collection.collection_path; 231 | if collection_path.contains("Test") { 232 | collection.unlock().unwrap(); 233 | collection.delete().unwrap(); 234 | } 235 | } 236 | //double check after 237 | let collections = ss.get_all_collections().unwrap(); 238 | assert!( 239 | collections.len() < count_before, 240 | "collections before delete {count_before}", 241 | ) 242 | } 243 | 244 | #[test] 245 | fn should_get_all_items() { 246 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 247 | let collection = ss.get_default_collection().unwrap(); 248 | collection.get_all_items().unwrap(); 249 | } 250 | 251 | #[test] 252 | fn should_search_items() { 253 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 254 | let collection = ss.get_default_collection().unwrap(); 255 | 256 | // Create an item 257 | let item = collection 258 | .create_item( 259 | "test", 260 | HashMap::from([("test_attributes_in_collection", "test")]), 261 | b"test_secret", 262 | false, 263 | "text/plain", 264 | ) 265 | .unwrap(); 266 | 267 | // handle empty vec search 268 | collection.search_items(HashMap::new()).unwrap(); 269 | 270 | // handle no result 271 | let bad_search = collection 272 | .search_items(HashMap::from([("test_bad", "test")])) 273 | .unwrap(); 274 | assert_eq!(bad_search.len(), 0); 275 | 276 | // handle correct search for item and compare 277 | let search_item = collection 278 | .search_items(HashMap::from([("test_attributes_in_collection", "test")])) 279 | .unwrap(); 280 | 281 | assert_eq!(item.item_path, search_item[0].item_path); 282 | item.delete().unwrap(); 283 | } 284 | 285 | #[test] 286 | #[ignore] 287 | fn should_get_and_set_collection_label() { 288 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 289 | let collection = ss.get_default_collection().unwrap(); 290 | let label = collection.get_label().unwrap(); 291 | assert_eq!(label, "Login"); 292 | 293 | // Set label to test and check 294 | collection.unlock().unwrap(); 295 | collection.set_label("Test").unwrap(); 296 | let label = collection.get_label().unwrap(); 297 | assert_eq!(label, "Test"); 298 | 299 | // Reset label to original and test 300 | collection.unlock().unwrap(); 301 | collection.set_label("Login").unwrap(); 302 | let label = collection.get_label().unwrap(); 303 | assert_eq!(label, "Login"); 304 | 305 | collection.lock().unwrap(); 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /src/blocking/item.rs: -------------------------------------------------------------------------------- 1 | use crate::error::Error; 2 | use crate::proxy::item::ItemProxyBlocking; 3 | use crate::proxy::service::ServiceProxyBlocking; 4 | use crate::session::decrypt; 5 | use crate::session::Session; 6 | use crate::ss::SS_DBUS_NAME; 7 | use crate::util::{exec_prompt_blocking, format_secret, lock_or_unlock_blocking, LockAction}; 8 | 9 | use std::collections::HashMap; 10 | use zbus::{proxy::CacheProperties, zvariant::OwnedObjectPath}; 11 | 12 | pub struct Item<'a> { 13 | conn: zbus::blocking::Connection, 14 | session: &'a Session, 15 | pub item_path: OwnedObjectPath, 16 | item_proxy: ItemProxyBlocking<'a>, 17 | service_proxy: &'a ServiceProxyBlocking<'a>, 18 | } 19 | 20 | impl<'a> Item<'a> { 21 | pub(crate) fn new( 22 | conn: zbus::blocking::Connection, 23 | session: &'a Session, 24 | service_proxy: &'a ServiceProxyBlocking<'a>, 25 | item_path: OwnedObjectPath, 26 | ) -> Result { 27 | let item_proxy = ItemProxyBlocking::builder(&conn) 28 | .destination(SS_DBUS_NAME)? 29 | .path(item_path.clone())? 30 | .cache_properties(CacheProperties::No) 31 | .build()?; 32 | Ok(Item { 33 | conn, 34 | session, 35 | item_path, 36 | item_proxy, 37 | service_proxy, 38 | }) 39 | } 40 | 41 | pub fn is_locked(&self) -> Result { 42 | Ok(self.item_proxy.locked()?) 43 | } 44 | 45 | pub fn ensure_unlocked(&self) -> Result<(), Error> { 46 | if self.is_locked()? { 47 | Err(Error::Locked) 48 | } else { 49 | Ok(()) 50 | } 51 | } 52 | 53 | pub fn unlock(&self) -> Result<(), Error> { 54 | lock_or_unlock_blocking( 55 | self.conn.clone(), 56 | self.service_proxy, 57 | &self.item_path, 58 | LockAction::Unlock, 59 | ) 60 | } 61 | 62 | pub fn lock(&self) -> Result<(), Error> { 63 | lock_or_unlock_blocking( 64 | self.conn.clone(), 65 | self.service_proxy, 66 | &self.item_path, 67 | LockAction::Lock, 68 | ) 69 | } 70 | 71 | pub fn get_attributes(&self) -> Result, Error> { 72 | Ok(self.item_proxy.attributes()?) 73 | } 74 | 75 | pub fn set_attributes(&self, attributes: HashMap<&str, &str>) -> Result<(), Error> { 76 | Ok(self.item_proxy.set_attributes(attributes)?) 77 | } 78 | 79 | pub fn get_label(&self) -> Result { 80 | Ok(self.item_proxy.label()?) 81 | } 82 | 83 | pub fn set_label(&self, new_label: &str) -> Result<(), Error> { 84 | Ok(self.item_proxy.set_label(new_label)?) 85 | } 86 | 87 | /// Deletes dbus object, but struct instance still exists (current implementation) 88 | pub fn delete(&self) -> Result<(), Error> { 89 | // ensure_unlocked handles prompt for unlocking if necessary 90 | self.ensure_unlocked()?; 91 | let prompt_path = self.item_proxy.delete()?; 92 | 93 | // "/" means no prompt necessary 94 | if prompt_path.as_str() != "/" { 95 | exec_prompt_blocking(self.conn.clone(), &prompt_path)?; 96 | } 97 | 98 | Ok(()) 99 | } 100 | 101 | pub fn get_secret(&self) -> Result, Error> { 102 | let secret_struct = self.item_proxy.get_secret(&self.session.object_path)?; 103 | let secret = secret_struct.value; 104 | 105 | if let Some(session_key) = self.session.get_aes_key() { 106 | // get "param" (aes_iv) field out of secret struct 107 | let aes_iv = secret_struct.parameters; 108 | 109 | // decrypt 110 | let decrypted_secret = decrypt(&secret, session_key, &aes_iv)?; 111 | 112 | Ok(decrypted_secret) 113 | } else { 114 | Ok(secret) 115 | } 116 | } 117 | 118 | pub fn get_secret_content_type(&self) -> Result { 119 | let secret_struct = self.item_proxy.get_secret(&self.session.object_path)?; 120 | let content_type = secret_struct.content_type; 121 | 122 | Ok(content_type) 123 | } 124 | 125 | pub fn set_secret(&self, secret: &[u8], content_type: &str) -> Result<(), Error> { 126 | let secret_struct = format_secret(self.session, secret, content_type)?; 127 | Ok(self.item_proxy.set_secret(secret_struct)?) 128 | } 129 | 130 | pub fn get_created(&self) -> Result { 131 | Ok(self.item_proxy.created()?) 132 | } 133 | 134 | pub fn get_modified(&self) -> Result { 135 | Ok(self.item_proxy.modified()?) 136 | } 137 | } 138 | 139 | impl Eq for Item<'_> {} 140 | impl PartialEq for Item<'_> { 141 | fn eq(&self, other: &Item) -> bool { 142 | self.item_path == other.item_path 143 | } 144 | } 145 | 146 | #[cfg(test)] 147 | mod test { 148 | use crate::blocking::*; 149 | 150 | fn create_test_default_item<'a>(collection: &'a Collection<'_>) -> Item<'a> { 151 | collection 152 | .create_item("Test", HashMap::new(), b"test", false, "text/plain") 153 | .unwrap() 154 | } 155 | 156 | #[test] 157 | fn should_create_and_delete_item() { 158 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 159 | let collection = ss.get_default_collection().unwrap(); 160 | let item = create_test_default_item(&collection); 161 | 162 | item.delete().unwrap(); 163 | // Random operation to prove that path no longer exists 164 | if item.get_label().is_ok() { 165 | panic!("item still existed"); 166 | } 167 | } 168 | 169 | #[test] 170 | fn should_check_if_item_locked() { 171 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 172 | let collection = ss.get_default_collection().unwrap(); 173 | let item = create_test_default_item(&collection); 174 | 175 | item.is_locked().unwrap(); 176 | item.delete().unwrap(); 177 | } 178 | 179 | #[test] 180 | #[ignore] 181 | fn should_lock_and_unlock() { 182 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 183 | let collection = ss.get_default_collection().unwrap(); 184 | let item = create_test_default_item(&collection); 185 | 186 | let locked = item.is_locked().unwrap(); 187 | if locked { 188 | item.unlock().unwrap(); 189 | item.ensure_unlocked().unwrap(); 190 | assert!(!item.is_locked().unwrap()); 191 | item.lock().unwrap(); 192 | assert!(item.is_locked().unwrap()); 193 | } else { 194 | item.lock().unwrap(); 195 | assert!(item.is_locked().unwrap()); 196 | item.unlock().unwrap(); 197 | item.ensure_unlocked().unwrap(); 198 | assert!(!item.is_locked().unwrap()); 199 | } 200 | item.delete().unwrap(); 201 | } 202 | 203 | #[test] 204 | fn should_get_and_set_item_label() { 205 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 206 | let collection = ss.get_default_collection().unwrap(); 207 | let item = create_test_default_item(&collection); 208 | 209 | // Set label to test and check 210 | item.set_label("Tester").unwrap(); 211 | let label = item.get_label().unwrap(); 212 | assert_eq!(label, "Tester"); 213 | item.delete().unwrap(); 214 | } 215 | 216 | #[test] 217 | fn should_create_with_item_attributes() { 218 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 219 | let collection = ss.get_default_collection().unwrap(); 220 | let item = collection 221 | .create_item( 222 | "Test", 223 | HashMap::from([("test_attributes_in_item", "test")]), 224 | b"test", 225 | false, 226 | "text/plain", 227 | ) 228 | .unwrap(); 229 | 230 | let attributes = item.get_attributes().unwrap(); 231 | 232 | // We do not compare exact attributes, since the secret service provider could add its own 233 | // at any time. Instead, we only check that the ones we provided are returned back. 234 | assert_eq!( 235 | attributes 236 | .get("test_attributes_in_item") 237 | .map(String::as_str), 238 | Some("test") 239 | ); 240 | 241 | item.delete().unwrap(); 242 | } 243 | 244 | #[test] 245 | fn should_get_and_set_item_attributes() { 246 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 247 | let collection = ss.get_default_collection().unwrap(); 248 | let item = create_test_default_item(&collection); 249 | 250 | // Also test empty array handling 251 | item.set_attributes(HashMap::new()).unwrap(); 252 | item.set_attributes(HashMap::from([("test_attributes_in_item_get", "test")])) 253 | .unwrap(); 254 | 255 | let attributes = item.get_attributes().unwrap(); 256 | 257 | // We do not compare exact attributes, since the secret service provider could add its own 258 | // at any time. Instead, we only check that the ones we provided are returned back. 259 | assert_eq!( 260 | attributes 261 | .get("test_attributes_in_item_get") 262 | .map(String::as_str), 263 | Some("test") 264 | ); 265 | 266 | item.delete().unwrap(); 267 | } 268 | 269 | #[test] 270 | fn should_get_modified_created_props() { 271 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 272 | let collection = ss.get_default_collection().unwrap(); 273 | let item = create_test_default_item(&collection); 274 | 275 | item.set_label("Tester").unwrap(); 276 | let _created = item.get_created().unwrap(); 277 | let _modified = item.get_modified().unwrap(); 278 | item.delete().unwrap(); 279 | } 280 | 281 | #[test] 282 | fn should_create_and_get_secret() { 283 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 284 | let collection = ss.get_default_collection().unwrap(); 285 | let item = create_test_default_item(&collection); 286 | 287 | let secret = item.get_secret().unwrap(); 288 | item.delete().unwrap(); 289 | assert_eq!(secret, b"test"); 290 | } 291 | 292 | #[test] 293 | fn should_create_and_get_secret_encrypted() { 294 | let ss = SecretService::connect(EncryptionType::Dh).unwrap(); 295 | let collection = ss.get_default_collection().unwrap(); 296 | let item = create_test_default_item(&collection); 297 | 298 | let secret = item.get_secret().unwrap(); 299 | item.delete().unwrap(); 300 | assert_eq!(secret, b"test"); 301 | } 302 | 303 | #[test] 304 | fn should_get_secret_content_type() { 305 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 306 | let collection = ss.get_default_collection().unwrap(); 307 | let item = create_test_default_item(&collection); 308 | 309 | let content_type = item.get_secret_content_type().unwrap(); 310 | item.delete().unwrap(); 311 | assert_eq!(content_type, "text/plain".to_owned()); 312 | } 313 | 314 | #[test] 315 | fn should_set_secret() { 316 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 317 | let collection = ss.get_default_collection().unwrap(); 318 | let item = create_test_default_item(&collection); 319 | 320 | item.set_secret(b"new_test", "text/plain").unwrap(); 321 | let secret = item.get_secret().unwrap(); 322 | item.delete().unwrap(); 323 | assert_eq!(secret, b"new_test"); 324 | } 325 | 326 | #[test] 327 | fn should_create_encrypted_item() { 328 | let ss = SecretService::connect(EncryptionType::Dh).unwrap(); 329 | let collection = ss.get_default_collection().unwrap(); 330 | let item = collection 331 | .create_item( 332 | "Test", 333 | HashMap::new(), 334 | b"test_encrypted", 335 | false, 336 | "text/plain", 337 | ) 338 | .expect("Error on item creation"); 339 | let secret = item.get_secret().unwrap(); 340 | item.delete().unwrap(); 341 | assert_eq!(secret, b"test_encrypted"); 342 | } 343 | 344 | #[test] 345 | fn should_create_encrypted_item_from_empty_secret() { 346 | let ss = SecretService::connect(EncryptionType::Dh).unwrap(); 347 | let collection = ss.get_default_collection().unwrap(); 348 | let item = collection 349 | .create_item("Test", HashMap::new(), b"", false, "text/plain") 350 | .expect("Error on item creation"); 351 | let secret = item.get_secret().unwrap(); 352 | item.delete().unwrap(); 353 | assert_eq!(secret, b""); 354 | } 355 | 356 | #[test] 357 | fn should_get_encrypted_secret_across_dbus_connections() { 358 | { 359 | let ss = SecretService::connect(EncryptionType::Dh).unwrap(); 360 | let collection = ss.get_default_collection().unwrap(); 361 | let item = collection 362 | .create_item( 363 | "Test", 364 | HashMap::from([("test_attributes_in_item_encrypt", "test")]), 365 | b"test_encrypted", 366 | false, 367 | "text/plain", 368 | ) 369 | .expect("Error on item creation"); 370 | let secret = item.get_secret().unwrap(); 371 | assert_eq!(secret, b"test_encrypted"); 372 | } 373 | { 374 | let ss = SecretService::connect(EncryptionType::Dh).unwrap(); 375 | let collection = ss.get_default_collection().unwrap(); 376 | let search_item = collection 377 | .search_items(HashMap::from([("test_attributes_in_item_encrypt", "test")])) 378 | .unwrap(); 379 | let item = search_item.first().unwrap(); 380 | assert_eq!(item.get_secret().unwrap(), b"test_encrypted"); 381 | item.delete().unwrap(); 382 | } 383 | } 384 | } 385 | -------------------------------------------------------------------------------- /src/blocking/mod.rs: -------------------------------------------------------------------------------- 1 | //! A blocking secret service API. 2 | //! 3 | //! This `SecretService` will block the current thread when making requests to the 4 | //! secret service server instead of returning futures. 5 | //! 6 | //! It is important to not call this these functions in an async context or otherwise the runtime 7 | //! may stall. See [zbus's blocking documentation] for more details. If you are in an async context, 8 | //! you should use the [async `SecretService`] instead. 9 | //! 10 | //! [zbus's blocking documentation]: https://docs.rs/zbus/latest/zbus/blocking/index.html 11 | //! [async `SecretService`]: crate::SecretService 12 | 13 | use crate::session::Session; 14 | use crate::ss::SS_COLLECTION_LABEL; 15 | use crate::util; 16 | use crate::{proxy::service::ServiceProxyBlocking, util::exec_prompt_blocking}; 17 | use crate::{EncryptionType, Error, SearchItemsResult}; 18 | use std::collections::HashMap; 19 | use zbus::zvariant::{ObjectPath, Value}; 20 | 21 | mod collection; 22 | pub use collection::Collection; 23 | mod item; 24 | pub use item::Item; 25 | 26 | /// Secret Service Struct. 27 | /// 28 | /// This the main entry point for usage of the library. 29 | /// 30 | /// Creating a new [SecretService] will also initialize dbus 31 | /// and negotiate a new cryptographic session 32 | /// ([EncryptionType::Plain] or [EncryptionType::Dh]) 33 | pub struct SecretService<'a> { 34 | conn: zbus::blocking::Connection, 35 | session: Session, 36 | service_proxy: ServiceProxyBlocking<'a>, 37 | } 38 | 39 | impl SecretService<'_> { 40 | /// Create a new `SecretService` instance 41 | pub fn connect(encryption: EncryptionType) -> Result { 42 | let conn = zbus::blocking::Connection::session().map_err(util::handle_conn_error)?; 43 | let service_proxy = ServiceProxyBlocking::new(&conn).map_err(util::handle_conn_error)?; 44 | 45 | let session = Session::new_blocking(&service_proxy, encryption)?; 46 | 47 | Ok(SecretService { 48 | conn, 49 | session, 50 | service_proxy, 51 | }) 52 | } 53 | 54 | /// Get all collections 55 | pub fn get_all_collections(&self) -> Result, Error> { 56 | let collections = self.service_proxy.collections()?; 57 | collections 58 | .into_iter() 59 | .map(|object_path| { 60 | Collection::new( 61 | self.conn.clone(), 62 | &self.session, 63 | &self.service_proxy, 64 | object_path.into(), 65 | ) 66 | }) 67 | .collect() 68 | } 69 | 70 | /// Get collection by alias. 71 | /// 72 | /// Most common would be the `default` alias, but there 73 | /// is also a specific method for getting the collection 74 | /// by default alias. 75 | pub fn get_collection_by_alias(&self, alias: &str) -> Result { 76 | let object_path = self.service_proxy.read_alias(alias)?; 77 | 78 | if object_path.as_str() == "/" { 79 | Err(Error::NoResult) 80 | } else { 81 | Ok(Collection::new( 82 | self.conn.clone(), 83 | &self.session, 84 | &self.service_proxy, 85 | object_path, 86 | )?) 87 | } 88 | } 89 | 90 | /// Get default collection. 91 | /// (The collection whos alias is `default`) 92 | pub fn get_default_collection(&self) -> Result { 93 | self.get_collection_by_alias("default") 94 | } 95 | 96 | /// Get any collection. 97 | /// First tries `default` collection, then `session` 98 | /// collection, then the first collection when it 99 | /// gets all collections. 100 | pub fn get_any_collection(&self) -> Result { 101 | // default first, then session, then first 102 | 103 | self.get_default_collection() 104 | .or_else(|_| self.get_collection_by_alias("session")) 105 | .or_else(|_| { 106 | let mut collections = self.get_all_collections()?; 107 | if collections.is_empty() { 108 | Err(Error::NoResult) 109 | } else { 110 | Ok(collections.swap_remove(0)) 111 | } 112 | }) 113 | } 114 | 115 | /// Creates a new collection with a label and an alias. 116 | pub fn create_collection(&self, label: &str, alias: &str) -> Result { 117 | let mut properties: HashMap<&str, Value> = HashMap::new(); 118 | properties.insert(SS_COLLECTION_LABEL, label.into()); 119 | 120 | let created_collection = self.service_proxy.create_collection(properties, alias)?; 121 | 122 | // This prompt handling is practically identical to create_collection 123 | let collection_path: ObjectPath = { 124 | // Get path of created object 125 | let created_path = created_collection.collection; 126 | 127 | // Check if that path is "/", if so should execute a prompt 128 | if created_path.as_str() == "/" { 129 | let prompt_path = created_collection.prompt; 130 | 131 | // Exec prompt and parse result 132 | let prompt_res = util::exec_prompt_blocking(self.conn.clone(), &prompt_path)?; 133 | prompt_res.try_into()? 134 | } else { 135 | // if not, just return created path 136 | created_path.into() 137 | } 138 | }; 139 | 140 | Collection::new( 141 | self.conn.clone(), 142 | &self.session, 143 | &self.service_proxy, 144 | collection_path.into(), 145 | ) 146 | } 147 | 148 | /// Searches all items by attributes 149 | pub fn search_items( 150 | &self, 151 | attributes: HashMap<&str, &str>, 152 | ) -> Result, Error> { 153 | let items = self.service_proxy.search_items(attributes)?; 154 | 155 | let object_paths_to_items = |items: Vec<_>| { 156 | items 157 | .into_iter() 158 | .map(|item_path| { 159 | Item::new( 160 | self.conn.clone(), 161 | &self.session, 162 | &self.service_proxy, 163 | item_path, 164 | ) 165 | }) 166 | .collect::>() 167 | }; 168 | 169 | Ok(SearchItemsResult { 170 | unlocked: object_paths_to_items(items.unlocked)?, 171 | locked: object_paths_to_items(items.locked)?, 172 | }) 173 | } 174 | 175 | /// Unlock all items in a batch 176 | pub fn unlock_all(&self, items: &[&Item<'_>]) -> Result<(), Error> { 177 | let objects = items.iter().map(|i| &*i.item_path).collect(); 178 | let lock_action_res = self.service_proxy.unlock(objects)?; 179 | 180 | if lock_action_res.object_paths.is_empty() { 181 | exec_prompt_blocking(self.conn.clone(), &lock_action_res.prompt)?; 182 | } 183 | 184 | Ok(()) 185 | } 186 | } 187 | 188 | #[cfg(test)] 189 | mod test { 190 | use super::*; 191 | use std::convert::TryFrom; 192 | use zbus::zvariant::ObjectPath; 193 | 194 | #[test] 195 | fn should_create_secret_service() { 196 | SecretService::connect(EncryptionType::Plain).unwrap(); 197 | } 198 | 199 | #[test] 200 | fn should_get_all_collections() { 201 | // Assumes that there will always be a default 202 | // collection 203 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 204 | let collections = ss.get_all_collections().unwrap(); 205 | assert!(!collections.is_empty(), "no collections found"); 206 | } 207 | 208 | #[test] 209 | fn should_get_collection_by_alias() { 210 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 211 | ss.get_collection_by_alias("session").unwrap(); 212 | } 213 | 214 | #[test] 215 | fn should_return_error_if_collection_doesnt_exist() { 216 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 217 | 218 | match ss.get_collection_by_alias("definitely_defintely_does_not_exist") { 219 | Err(Error::NoResult) => {} 220 | _ => panic!(), 221 | }; 222 | } 223 | 224 | #[test] 225 | fn should_get_default_collection() { 226 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 227 | ss.get_default_collection().unwrap(); 228 | } 229 | 230 | #[test] 231 | fn should_get_any_collection() { 232 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 233 | let _ = ss.get_any_collection().unwrap(); 234 | } 235 | 236 | #[test_with::no_env(GITHUB_ACTIONS)] 237 | #[test] 238 | fn should_create_and_delete_collection() { 239 | let ss = SecretService::connect(EncryptionType::Plain).unwrap(); 240 | let test_collection = ss.create_collection("Test", "").unwrap(); 241 | assert_eq!( 242 | ObjectPath::from(test_collection.collection_path.clone()), 243 | ObjectPath::try_from("/org/freedesktop/secrets/collection/Test").unwrap() 244 | ); 245 | test_collection.delete().unwrap(); 246 | } 247 | 248 | #[test] 249 | fn should_search_items() { 250 | let ss = SecretService::connect(EncryptionType::Dh).unwrap(); 251 | let collection = ss.get_default_collection().unwrap(); 252 | 253 | // Create an item 254 | let item = collection 255 | .create_item( 256 | "test", 257 | HashMap::from([("test_attribute_in_ss", "test_value")]), 258 | b"test_secret", 259 | false, 260 | "text/plain", 261 | ) 262 | .unwrap(); 263 | 264 | // handle empty vec search 265 | ss.search_items(HashMap::new()).unwrap(); 266 | 267 | // handle no result 268 | let bad_search = ss.search_items(HashMap::from([("test", "test")])).unwrap(); 269 | assert_eq!(bad_search.unlocked.len(), 0); 270 | assert_eq!(bad_search.locked.len(), 0); 271 | 272 | // handle correct search for item and compare 273 | let search_item = ss 274 | .search_items(HashMap::from([("test_attribute_in_ss", "test_value")])) 275 | .unwrap(); 276 | 277 | assert_eq!(item.item_path, search_item.unlocked[0].item_path); 278 | assert_eq!(search_item.locked.len(), 0); 279 | item.delete().unwrap(); 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /src/collection.rs: -------------------------------------------------------------------------------- 1 | use crate::proxy::collection::CollectionProxy; 2 | use crate::proxy::service::ServiceProxy; 3 | use crate::session::Session; 4 | use crate::ss::{SS_DBUS_NAME, SS_ITEM_ATTRIBUTES, SS_ITEM_LABEL}; 5 | use crate::util::{exec_prompt, format_secret, lock_or_unlock, LockAction}; 6 | use crate::Error; 7 | use crate::Item; 8 | 9 | use std::collections::HashMap; 10 | use zbus::{ 11 | proxy::CacheProperties, 12 | zvariant::{Dict, ObjectPath, OwnedObjectPath, Value}, 13 | }; 14 | 15 | // Collection struct. 16 | // Should always be created from the SecretService entry point, 17 | // whether through a new collection or a collection search 18 | pub struct Collection<'a> { 19 | conn: zbus::Connection, 20 | session: &'a Session, 21 | pub collection_path: OwnedObjectPath, 22 | collection_proxy: CollectionProxy<'a>, 23 | service_proxy: &'a ServiceProxy<'a>, 24 | } 25 | 26 | impl<'a> Collection<'a> { 27 | pub(crate) async fn new( 28 | conn: zbus::Connection, 29 | session: &'a Session, 30 | service_proxy: &'a ServiceProxy<'_>, 31 | collection_path: OwnedObjectPath, 32 | ) -> Result, Error> { 33 | let collection_proxy = CollectionProxy::builder(&conn) 34 | .destination(SS_DBUS_NAME)? 35 | .path(collection_path.clone())? 36 | .cache_properties(CacheProperties::No) 37 | .build() 38 | .await?; 39 | 40 | Ok(Collection { 41 | conn, 42 | session, 43 | collection_path, 44 | collection_proxy, 45 | service_proxy, 46 | }) 47 | } 48 | 49 | pub async fn is_locked(&self) -> Result { 50 | Ok(self.collection_proxy.locked().await?) 51 | } 52 | 53 | pub async fn ensure_unlocked(&self) -> Result<(), Error> { 54 | if self.is_locked().await? { 55 | Err(Error::Locked) 56 | } else { 57 | Ok(()) 58 | } 59 | } 60 | 61 | pub async fn unlock(&self) -> Result<(), Error> { 62 | lock_or_unlock( 63 | self.conn.clone(), 64 | self.service_proxy, 65 | &self.collection_path, 66 | LockAction::Unlock, 67 | ) 68 | .await 69 | } 70 | 71 | pub async fn lock(&self) -> Result<(), Error> { 72 | lock_or_unlock( 73 | self.conn.clone(), 74 | self.service_proxy, 75 | &self.collection_path, 76 | LockAction::Lock, 77 | ) 78 | .await 79 | } 80 | 81 | /// Deletes dbus object, but struct instance still exists (current implementation) 82 | pub async fn delete(&self) -> Result<(), Error> { 83 | // ensure_unlocked handles prompt for unlocking if necessary 84 | self.ensure_unlocked().await?; 85 | let prompt_path = self.collection_proxy.delete().await?; 86 | 87 | // "/" means no prompt necessary 88 | if prompt_path.as_str() != "/" { 89 | exec_prompt(self.conn.clone(), &prompt_path).await?; 90 | } 91 | 92 | Ok(()) 93 | } 94 | 95 | pub async fn get_all_items(&self) -> Result>, Error> { 96 | let items = self.collection_proxy.items().await?; 97 | 98 | // map array of item paths to Item 99 | futures_util::future::join_all(items.into_iter().map(|item_path| { 100 | Item::new( 101 | self.conn.clone(), 102 | self.session, 103 | self.service_proxy, 104 | item_path.into(), 105 | ) 106 | })) 107 | .await 108 | .into_iter() 109 | .collect::>() 110 | } 111 | 112 | pub async fn search_items( 113 | &self, 114 | attributes: HashMap<&str, &str>, 115 | ) -> Result>, Error> { 116 | let items = self.collection_proxy.search_items(attributes).await?; 117 | 118 | // map array of item paths to Item 119 | futures_util::future::join_all(items.into_iter().map(|item_path| { 120 | Item::new( 121 | self.conn.clone(), 122 | self.session, 123 | self.service_proxy, 124 | item_path, 125 | ) 126 | })) 127 | .await 128 | .into_iter() 129 | .collect::>() 130 | } 131 | 132 | pub async fn get_label(&self) -> Result { 133 | Ok(self.collection_proxy.label().await?) 134 | } 135 | 136 | pub async fn set_label(&self, new_label: &str) -> Result<(), Error> { 137 | Ok(self.collection_proxy.set_label(new_label).await?) 138 | } 139 | 140 | pub async fn create_item( 141 | &self, 142 | label: &str, 143 | attributes: HashMap<&str, &str>, 144 | secret: &[u8], 145 | replace: bool, 146 | content_type: &str, 147 | ) -> Result, Error> { 148 | let secret_struct = format_secret(self.session, secret, content_type)?; 149 | 150 | let mut properties: HashMap<&str, Value> = HashMap::new(); 151 | let attributes: Dict = attributes.into(); 152 | 153 | properties.insert(SS_ITEM_LABEL, label.into()); 154 | properties.insert(SS_ITEM_ATTRIBUTES, attributes.into()); 155 | 156 | let created_item = self 157 | .collection_proxy 158 | .create_item(properties, secret_struct, replace) 159 | .await?; 160 | 161 | // This prompt handling is practically identical to create_collection 162 | let item_path: ObjectPath = { 163 | // Get path of created object 164 | let created_path = created_item.item; 165 | 166 | // Check if that path is "/", if so should execute a prompt 167 | if created_path.as_str() == "/" { 168 | let prompt_path = created_item.prompt; 169 | 170 | // Exec prompt and parse result 171 | let prompt_res = exec_prompt(self.conn.clone(), &prompt_path).await?; 172 | prompt_res.try_into()? 173 | } else { 174 | // if not, just return created path 175 | created_path.into() 176 | } 177 | }; 178 | 179 | Item::new( 180 | self.conn.clone(), 181 | self.session, 182 | self.service_proxy, 183 | item_path.into(), 184 | ) 185 | .await 186 | } 187 | } 188 | 189 | #[cfg(test)] 190 | mod test { 191 | use crate::*; 192 | 193 | #[tokio::test] 194 | async fn should_create_collection_struct() { 195 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 196 | let _ = ss.get_default_collection().await.unwrap(); 197 | // tested under SecretService struct 198 | } 199 | 200 | #[tokio::test] 201 | async fn should_check_if_collection_locked() { 202 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 203 | let collection = ss.get_default_collection().await.unwrap(); 204 | let _ = collection.is_locked().await.unwrap(); 205 | } 206 | 207 | #[tokio::test] 208 | #[ignore] // should unignore this test this manually, otherwise will constantly prompt during tests. 209 | async fn should_lock_and_unlock() { 210 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 211 | let collection = ss.get_default_collection().await.unwrap(); 212 | let locked = collection.is_locked().await.unwrap(); 213 | if locked { 214 | collection.unlock().await.unwrap(); 215 | collection.ensure_unlocked().await.unwrap(); 216 | assert!(!collection.is_locked().await.unwrap()); 217 | collection.lock().await.unwrap(); 218 | assert!(collection.is_locked().await.unwrap()); 219 | } else { 220 | collection.lock().await.unwrap(); 221 | assert!(collection.is_locked().await.unwrap()); 222 | collection.unlock().await.unwrap(); 223 | collection.ensure_unlocked().await.unwrap(); 224 | assert!(!collection.is_locked().await.unwrap()); 225 | } 226 | } 227 | 228 | #[tokio::test] 229 | #[ignore] 230 | async fn should_delete_collection() { 231 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 232 | let collections = ss.get_all_collections().await.unwrap(); 233 | let count_before = collections.len(); 234 | for collection in collections { 235 | let collection_path = &*collection.collection_path; 236 | if collection_path.contains("Test") { 237 | collection.unlock().await.unwrap(); 238 | collection.delete().await.unwrap(); 239 | } 240 | } 241 | //double check after 242 | let collections = ss.get_all_collections().await.unwrap(); 243 | assert!( 244 | collections.len() < count_before, 245 | "collections before delete {count_before}" 246 | ); 247 | } 248 | 249 | #[tokio::test] 250 | async fn should_get_all_items() { 251 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 252 | let collection = ss.get_default_collection().await.unwrap(); 253 | collection.get_all_items().await.unwrap(); 254 | } 255 | 256 | #[tokio::test] 257 | async fn should_search_items() { 258 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 259 | let collection = ss.get_default_collection().await.unwrap(); 260 | 261 | // Create an item 262 | let item = collection 263 | .create_item( 264 | "test", 265 | HashMap::from([("test_attributes_in_collection", "test")]), 266 | b"test_secret", 267 | false, 268 | "text/plain", 269 | ) 270 | .await 271 | .unwrap(); 272 | 273 | // handle empty vec search 274 | collection.search_items(HashMap::new()).await.unwrap(); 275 | 276 | // handle no result 277 | let bad_search = collection 278 | .search_items(HashMap::from([("test_bad", "test")])) 279 | .await 280 | .unwrap(); 281 | assert_eq!(bad_search.len(), 0); 282 | 283 | // handle correct search for item and compare 284 | let search_item = collection 285 | .search_items(HashMap::from([("test_attributes_in_collection", "test")])) 286 | .await 287 | .unwrap(); 288 | 289 | assert_eq!(item.item_path, search_item[0].item_path); 290 | item.delete().await.unwrap(); 291 | } 292 | 293 | #[tokio::test] 294 | #[ignore] 295 | async fn should_get_and_set_collection_label() { 296 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 297 | let collection = ss.get_default_collection().await.unwrap(); 298 | let label = collection.get_label().await.unwrap(); 299 | assert_eq!(label, "Login"); 300 | 301 | // Set label to test and check 302 | collection.unlock().await.unwrap(); 303 | collection.set_label("Test").await.unwrap(); 304 | let label = collection.get_label().await.unwrap(); 305 | assert_eq!(label, "Test"); 306 | 307 | // Reset label to original and test 308 | collection.unlock().await.unwrap(); 309 | collection.set_label("Login").await.unwrap(); 310 | let label = collection.get_label().await.unwrap(); 311 | assert_eq!(label, "Login"); 312 | 313 | collection.lock().await.unwrap(); 314 | } 315 | } 316 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use zbus::zvariant; 2 | 3 | /// An error that could occur interacting with the secret service dbus interface. 4 | #[derive(Debug)] 5 | #[non_exhaustive] 6 | pub enum Error { 7 | /// An error occured decrypting a response message. 8 | Crypto(&'static str), 9 | /// A call into the secret service provider failed. 10 | Zbus(zbus::Error), 11 | /// A call into a standard dbus interface failed. 12 | ZbusFdo(zbus::fdo::Error), 13 | /// Serializing or deserializing a dbus message failed. 14 | Zvariant(zvariant::Error), 15 | /// A secret service interface was locked and can't return any 16 | /// information about its contents. 17 | Locked, 18 | /// No object was found in the object for the request. 19 | NoResult, 20 | /// An authorization prompt was dismissed, but is required to continue. 21 | Prompt, 22 | /// A secret service provider, or a session to connect to one, was found 23 | /// on the system. 24 | Unavailable, 25 | } 26 | 27 | impl std::fmt::Display for Error { 28 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 29 | match self { 30 | Error::Crypto(err) => write!(f, "Crypto error: {err}"), 31 | Error::Zbus(err) => write!(f, "zbus error: {err}"), 32 | Error::ZbusFdo(err) => write!(f, "zbus fdo error: {err}"), 33 | Error::Zvariant(err) => write!(f, "zbus serde error: {err}"), 34 | Error::Locked => f.write_str("SS Error: object locked"), 35 | Error::NoResult => f.write_str("SS error: result not returned from SS API"), 36 | Error::Prompt => f.write_str("SS error: prompt dismissed"), 37 | Error::Unavailable => f.write_str("no secret service provider or dbus session found"), 38 | } 39 | } 40 | } 41 | 42 | impl std::error::Error for Error { 43 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { 44 | match *self { 45 | Error::Zbus(ref err) => Some(err), 46 | Error::ZbusFdo(ref err) => Some(err), 47 | Error::Zvariant(ref err) => Some(err), 48 | _ => None, 49 | } 50 | } 51 | } 52 | 53 | impl From for Error { 54 | fn from(err: zbus::Error) -> Error { 55 | Error::Zbus(err) 56 | } 57 | } 58 | 59 | impl From for Error { 60 | fn from(err: zbus::fdo::Error) -> Error { 61 | Error::ZbusFdo(err) 62 | } 63 | } 64 | 65 | impl From for Error { 66 | fn from(err: zvariant::Error) -> Error { 67 | Error::Zvariant(err) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/item.rs: -------------------------------------------------------------------------------- 1 | use crate::error::Error; 2 | use crate::proxy::item::ItemProxy; 3 | use crate::proxy::service::ServiceProxy; 4 | use crate::session::decrypt; 5 | use crate::session::Session; 6 | use crate::ss::SS_DBUS_NAME; 7 | use crate::util::{exec_prompt, format_secret, lock_or_unlock, LockAction}; 8 | 9 | use std::collections::HashMap; 10 | use zbus::{proxy::CacheProperties, zvariant::OwnedObjectPath}; 11 | 12 | pub struct Item<'a> { 13 | conn: zbus::Connection, 14 | session: &'a Session, 15 | pub item_path: OwnedObjectPath, 16 | item_proxy: ItemProxy<'a>, 17 | service_proxy: &'a ServiceProxy<'a>, 18 | } 19 | 20 | impl<'a> Item<'a> { 21 | pub(crate) async fn new( 22 | conn: zbus::Connection, 23 | session: &'a Session, 24 | service_proxy: &'a ServiceProxy<'a>, 25 | item_path: OwnedObjectPath, 26 | ) -> Result, Error> { 27 | let item_proxy = ItemProxy::builder(&conn) 28 | .destination(SS_DBUS_NAME)? 29 | .path(item_path.clone())? 30 | .cache_properties(CacheProperties::No) 31 | .build() 32 | .await?; 33 | 34 | Ok(Item { 35 | conn, 36 | session, 37 | item_path, 38 | item_proxy, 39 | service_proxy, 40 | }) 41 | } 42 | 43 | pub async fn is_locked(&self) -> Result { 44 | Ok(self.item_proxy.locked().await?) 45 | } 46 | 47 | pub async fn ensure_unlocked(&self) -> Result<(), Error> { 48 | if self.is_locked().await? { 49 | Err(Error::Locked) 50 | } else { 51 | Ok(()) 52 | } 53 | } 54 | 55 | pub async fn unlock(&self) -> Result<(), Error> { 56 | lock_or_unlock( 57 | self.conn.clone(), 58 | self.service_proxy, 59 | &self.item_path, 60 | LockAction::Unlock, 61 | ) 62 | .await 63 | } 64 | 65 | pub async fn lock(&self) -> Result<(), Error> { 66 | lock_or_unlock( 67 | self.conn.clone(), 68 | self.service_proxy, 69 | &self.item_path, 70 | LockAction::Lock, 71 | ) 72 | .await 73 | } 74 | 75 | pub async fn get_attributes(&self) -> Result, Error> { 76 | Ok(self.item_proxy.attributes().await?) 77 | } 78 | 79 | pub async fn set_attributes(&self, attributes: HashMap<&str, &str>) -> Result<(), Error> { 80 | Ok(self.item_proxy.set_attributes(attributes).await?) 81 | } 82 | 83 | pub async fn get_label(&self) -> Result { 84 | Ok(self.item_proxy.label().await?) 85 | } 86 | 87 | pub async fn set_label(&self, new_label: &str) -> Result<(), Error> { 88 | Ok(self.item_proxy.set_label(new_label).await?) 89 | } 90 | 91 | /// Deletes dbus object, but struct instance still exists (current implementation) 92 | pub async fn delete(&self) -> Result<(), Error> { 93 | // ensure_unlocked handles prompt for unlocking if necessary 94 | self.ensure_unlocked().await?; 95 | let prompt_path = self.item_proxy.delete().await?; 96 | 97 | // "/" means no prompt necessary 98 | if prompt_path.as_str() != "/" { 99 | exec_prompt(self.conn.clone(), &prompt_path).await?; 100 | } 101 | 102 | Ok(()) 103 | } 104 | 105 | pub async fn get_secret(&self) -> Result, Error> { 106 | let secret_struct = self 107 | .item_proxy 108 | .get_secret(&self.session.object_path) 109 | .await?; 110 | let secret = secret_struct.value; 111 | 112 | if let Some(session_key) = self.session.get_aes_key() { 113 | // get "param" (aes_iv) field out of secret struct 114 | let aes_iv = secret_struct.parameters; 115 | 116 | // decrypt 117 | let decrypted_secret = decrypt(&secret, session_key, &aes_iv)?; 118 | 119 | Ok(decrypted_secret) 120 | } else { 121 | Ok(secret) 122 | } 123 | } 124 | 125 | pub async fn get_secret_content_type(&self) -> Result { 126 | let secret_struct = self 127 | .item_proxy 128 | .get_secret(&self.session.object_path) 129 | .await?; 130 | let content_type = secret_struct.content_type; 131 | 132 | Ok(content_type) 133 | } 134 | 135 | pub async fn set_secret(&self, secret: &[u8], content_type: &str) -> Result<(), Error> { 136 | let secret_struct = format_secret(self.session, secret, content_type)?; 137 | Ok(self.item_proxy.set_secret(secret_struct).await?) 138 | } 139 | 140 | pub async fn get_created(&self) -> Result { 141 | Ok(self.item_proxy.created().await?) 142 | } 143 | 144 | pub async fn get_modified(&self) -> Result { 145 | Ok(self.item_proxy.modified().await?) 146 | } 147 | } 148 | 149 | impl Eq for Item<'_> {} 150 | impl PartialEq for Item<'_> { 151 | fn eq(&self, other: &Item) -> bool { 152 | self.item_path == other.item_path 153 | } 154 | } 155 | 156 | #[cfg(test)] 157 | mod test { 158 | use crate::*; 159 | 160 | async fn create_test_default_item<'a>(collection: &'a Collection<'_>) -> Item<'a> { 161 | collection 162 | .create_item("Test", HashMap::new(), b"test", false, "text/plain") 163 | .await 164 | .unwrap() 165 | } 166 | 167 | #[tokio::test] 168 | async fn should_create_and_delete_item() { 169 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 170 | let collection = ss.get_default_collection().await.unwrap(); 171 | let item = create_test_default_item(&collection).await; 172 | 173 | item.delete().await.unwrap(); 174 | // Random operation to prove that path no longer exists 175 | if item.get_label().await.is_ok() { 176 | panic!("item still existed"); 177 | } 178 | } 179 | 180 | #[tokio::test] 181 | async fn should_check_if_item_locked() { 182 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 183 | let collection = ss.get_default_collection().await.unwrap(); 184 | let item = create_test_default_item(&collection).await; 185 | 186 | item.is_locked().await.unwrap(); 187 | item.delete().await.unwrap(); 188 | } 189 | 190 | #[tokio::test] 191 | #[ignore] 192 | async fn should_lock_and_unlock() { 193 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 194 | let collection = ss.get_default_collection().await.unwrap(); 195 | let item = create_test_default_item(&collection).await; 196 | 197 | let locked = item.is_locked().await.unwrap(); 198 | if locked { 199 | item.unlock().await.unwrap(); 200 | item.ensure_unlocked().await.unwrap(); 201 | assert!(!item.is_locked().await.unwrap()); 202 | item.lock().await.unwrap(); 203 | assert!(item.is_locked().await.unwrap()); 204 | } else { 205 | item.lock().await.unwrap(); 206 | assert!(item.is_locked().await.unwrap()); 207 | item.unlock().await.unwrap(); 208 | item.ensure_unlocked().await.unwrap(); 209 | assert!(!item.is_locked().await.unwrap()); 210 | } 211 | item.delete().await.unwrap(); 212 | } 213 | 214 | #[tokio::test] 215 | async fn should_get_and_set_item_label() { 216 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 217 | let collection = ss.get_default_collection().await.unwrap(); 218 | let item = create_test_default_item(&collection).await; 219 | 220 | // Set label to test and check 221 | item.set_label("Tester").await.unwrap(); 222 | let label = item.get_label().await.unwrap(); 223 | assert_eq!(label, "Tester"); 224 | item.delete().await.unwrap(); 225 | } 226 | 227 | #[tokio::test] 228 | async fn should_create_with_item_attributes() { 229 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 230 | let collection = ss.get_default_collection().await.unwrap(); 231 | let item = collection 232 | .create_item( 233 | "Test", 234 | HashMap::from([("test_attributes_in_item", "test")]), 235 | b"test", 236 | false, 237 | "text/plain", 238 | ) 239 | .await 240 | .unwrap(); 241 | 242 | let attributes = item.get_attributes().await.unwrap(); 243 | 244 | // We do not compare exact attributes, since the secret service provider could add its own 245 | // at any time. Instead, we only check that the ones we provided are returned back. 246 | assert_eq!( 247 | attributes 248 | .get("test_attributes_in_item") 249 | .map(String::as_str), 250 | Some("test") 251 | ); 252 | 253 | item.delete().await.unwrap(); 254 | } 255 | 256 | #[tokio::test] 257 | async fn should_get_and_set_item_attributes() { 258 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 259 | let collection = ss.get_default_collection().await.unwrap(); 260 | let item = create_test_default_item(&collection).await; 261 | 262 | // Also test empty array handling 263 | item.set_attributes(HashMap::new()).await.unwrap(); 264 | item.set_attributes(HashMap::from([("test_attributes_in_item_get", "test")])) 265 | .await 266 | .unwrap(); 267 | 268 | let attributes = item.get_attributes().await.unwrap(); 269 | 270 | // We do not compare exact attributes, since the secret service provider could add its own 271 | // at any time. Instead, we only check that the ones we provided are returned back. 272 | assert_eq!( 273 | attributes 274 | .get("test_attributes_in_item_get") 275 | .map(String::as_str), 276 | Some("test") 277 | ); 278 | 279 | item.delete().await.unwrap(); 280 | } 281 | 282 | #[tokio::test] 283 | async fn should_get_modified_created_props() { 284 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 285 | let collection = ss.get_default_collection().await.unwrap(); 286 | let item = create_test_default_item(&collection).await; 287 | 288 | item.set_label("Tester").await.unwrap(); 289 | let _created = item.get_created().await.unwrap(); 290 | let _modified = item.get_modified().await.unwrap(); 291 | item.delete().await.unwrap(); 292 | } 293 | 294 | #[tokio::test] 295 | async fn should_create_and_get_secret() { 296 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 297 | let collection = ss.get_default_collection().await.unwrap(); 298 | let item = create_test_default_item(&collection).await; 299 | 300 | let secret = item.get_secret().await.unwrap(); 301 | item.delete().await.unwrap(); 302 | assert_eq!(secret, b"test"); 303 | } 304 | 305 | #[tokio::test] 306 | async fn should_create_and_get_secret_encrypted() { 307 | let ss = SecretService::connect(EncryptionType::Dh).await.unwrap(); 308 | let collection = ss.get_default_collection().await.unwrap(); 309 | let item = create_test_default_item(&collection).await; 310 | 311 | let secret = item.get_secret().await.unwrap(); 312 | item.delete().await.unwrap(); 313 | assert_eq!(secret, b"test"); 314 | } 315 | 316 | #[tokio::test] 317 | async fn should_get_secret_content_type() { 318 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 319 | let collection = ss.get_default_collection().await.unwrap(); 320 | let item = create_test_default_item(&collection).await; 321 | 322 | let content_type = item.get_secret_content_type().await.unwrap(); 323 | item.delete().await.unwrap(); 324 | assert_eq!(content_type, "text/plain".to_owned()); 325 | } 326 | 327 | #[tokio::test] 328 | async fn should_set_secret() { 329 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 330 | let collection = ss.get_default_collection().await.unwrap(); 331 | let item = create_test_default_item(&collection).await; 332 | 333 | item.set_secret(b"new_test", "text/plain").await.unwrap(); 334 | let secret = item.get_secret().await.unwrap(); 335 | item.delete().await.unwrap(); 336 | assert_eq!(secret, b"new_test"); 337 | } 338 | 339 | #[tokio::test] 340 | async fn should_create_encrypted_item() { 341 | let ss = SecretService::connect(EncryptionType::Dh).await.unwrap(); 342 | let collection = ss.get_default_collection().await.unwrap(); 343 | let item = collection 344 | .create_item( 345 | "Test", 346 | HashMap::new(), 347 | b"test_encrypted", 348 | false, 349 | "text/plain", 350 | ) 351 | .await 352 | .expect("Error on item creation"); 353 | let secret = item.get_secret().await.unwrap(); 354 | item.delete().await.unwrap(); 355 | assert_eq!(secret, b"test_encrypted"); 356 | } 357 | 358 | #[tokio::test] 359 | async fn should_create_encrypted_item_from_empty_secret() { 360 | //empty string 361 | let ss = SecretService::connect(EncryptionType::Dh).await.unwrap(); 362 | let collection = ss.get_default_collection().await.unwrap(); 363 | let item = collection 364 | .create_item("Test", HashMap::new(), b"", false, "text/plain") 365 | .await 366 | .expect("Error on item creation"); 367 | let secret = item.get_secret().await.unwrap(); 368 | item.delete().await.unwrap(); 369 | assert_eq!(secret, b""); 370 | } 371 | 372 | #[tokio::test] 373 | async fn should_get_encrypted_secret_across_dbus_connections() { 374 | { 375 | let ss = SecretService::connect(EncryptionType::Dh).await.unwrap(); 376 | let collection = ss.get_default_collection().await.unwrap(); 377 | let item = collection 378 | .create_item( 379 | "Test", 380 | HashMap::from([("test_attributes_in_item_encrypt", "test")]), 381 | b"test_encrypted", 382 | false, 383 | "text/plain", 384 | ) 385 | .await 386 | .expect("Error on item creation"); 387 | let secret = item.get_secret().await.unwrap(); 388 | assert_eq!(secret, b"test_encrypted"); 389 | } 390 | { 391 | let ss = SecretService::connect(EncryptionType::Dh).await.unwrap(); 392 | let collection = ss.get_default_collection().await.unwrap(); 393 | let search_item = collection 394 | .search_items(HashMap::from([("test_attributes_in_item_encrypt", "test")])) 395 | .await 396 | .unwrap(); 397 | let item = search_item.first().unwrap(); 398 | assert_eq!(item.get_secret().await.unwrap(), b"test_encrypted"); 399 | item.delete().await.unwrap(); 400 | } 401 | } 402 | } 403 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # Secret Service libary 2 | //! 3 | //! This library implements a rust interface to the Secret Service API which is implemented 4 | //! in Linux. 5 | //! 6 | //! ## About Secret Service API 7 | //! 8 | //! 9 | //! Secret Service provides a secure place to store secrets. 10 | //! Gnome keyring and KWallet implement the Secret Service API. 11 | //! 12 | //! ## Basic Usage 13 | //! ``` 14 | //! use secret_service::SecretService; 15 | //! use secret_service::EncryptionType; 16 | //! use std::collections::HashMap; 17 | //! 18 | //! #[tokio::main(flavor = "current_thread")] 19 | //! async fn main() { 20 | //! // initialize secret service (dbus connection and encryption session) 21 | //! let ss = SecretService::connect(EncryptionType::Dh).await.unwrap(); 22 | //! 23 | //! // get default collection 24 | //! let collection = ss.get_default_collection().await.unwrap(); 25 | //! 26 | //! let mut properties = HashMap::new(); 27 | //! properties.insert("test", "test_value"); 28 | //! 29 | //! //create new item 30 | //! collection.create_item( 31 | //! "test_label", // label 32 | //! properties, 33 | //! b"test_secret", //secret 34 | //! false, // replace item with same attributes 35 | //! "text/plain" // secret content type 36 | //! ).await.unwrap(); 37 | //! 38 | //! // search items by properties 39 | //! let search_items = ss.search_items( 40 | //! HashMap::from([("test", "test_value")]) 41 | //! ).await.unwrap(); 42 | //! 43 | //! // retrieve one item, first by checking the unlocked items 44 | //! let item = match search_items.unlocked.first() { 45 | //! Some(item) => item, 46 | //! None => { 47 | //! // if there aren't any, check the locked items and unlock the first one 48 | //! let locked_item = search_items 49 | //! .locked 50 | //! .first() 51 | //! .expect("Search didn't return any items!"); 52 | //! locked_item.unlock().await.unwrap(); 53 | //! locked_item 54 | //! } 55 | //! }; 56 | //! 57 | //! // retrieve secret from item 58 | //! let secret = item.get_secret().await.unwrap(); 59 | //! assert_eq!(secret, b"test_secret"); 60 | //! 61 | //! // delete item (deletes the dbus object, not the struct instance) 62 | //! item.delete().await.unwrap() 63 | //! } 64 | //! ``` 65 | //! 66 | //! ## Overview of this library: 67 | //! ### Entry point 68 | //! The entry point for this library is the `SecretService` struct. A new instance of 69 | //! `SecretService` will initialize the dbus connection and negotiate an encryption session. 70 | //! 71 | //! ``` 72 | //! # use secret_service::SecretService; 73 | //! # use secret_service::EncryptionType; 74 | //! # async fn call() { 75 | //! SecretService::connect(EncryptionType::Plain).await.unwrap(); 76 | //! # } 77 | //! ``` 78 | //! 79 | //! or 80 | //! 81 | //! ``` 82 | //! # use secret_service::SecretService; 83 | //! # use secret_service::EncryptionType; 84 | //! # async fn call() { 85 | //! SecretService::connect(EncryptionType::Dh).await.unwrap(); 86 | //! # } 87 | //! ``` 88 | //! 89 | //! Once the SecretService struct is initialized, it can be used to navigate to a collection. 90 | //! Items can also be directly searched for without getting a collection first. 91 | //! 92 | //! ### Collections and Items 93 | //! The Secret Service API organizes secrets into collections, and holds each secret 94 | //! in an item. 95 | //! 96 | //! Items consist of a label, attributes, and the secret. The most common way to find 97 | //! an item is a search by attributes. 98 | //! 99 | //! While it's possible to create new collections, most users will simply create items 100 | //! within the default collection. 101 | //! 102 | //! ### Actions overview 103 | //! The most common supported actions are `create`, `get`, `search`, and `delete` for 104 | //! `Collections` and `Items`. For more specifics and exact method names, please see 105 | //! each struct's documentation. 106 | //! 107 | //! In addition, `set` and `get` actions are available for secrets contained in an `Item`. 108 | //! 109 | //! ### Crypto 110 | //! Specifics in SecretService API Draft Proposal: 111 | //! 112 | //! 113 | //! ### Async 114 | //! 115 | //! This crate, following `zbus`, is async by default. If you want a synchronous interface 116 | //! that blocks, see the [blocking] module instead. 117 | // 118 | // Util currently has interfaces (dbus method namespace) to make it easier to call methods. 119 | // Util contains function to execute prompts (used in many collection and item methods, like 120 | // delete) 121 | 122 | pub mod blocking; 123 | mod error; 124 | mod proxy; 125 | mod session; 126 | mod ss; 127 | mod util; 128 | 129 | mod collection; 130 | pub use collection::Collection; 131 | 132 | pub use error::Error; 133 | 134 | mod item; 135 | pub use item::Item; 136 | 137 | pub use session::EncryptionType; 138 | 139 | use crate::proxy::service::ServiceProxy; 140 | use crate::session::Session; 141 | use crate::ss::SS_COLLECTION_LABEL; 142 | use crate::util::exec_prompt; 143 | use futures_util::TryFutureExt; 144 | use std::collections::HashMap; 145 | use zbus::zvariant::{ObjectPath, Value}; 146 | 147 | /// Secret Service Struct. 148 | /// 149 | /// This the main entry point for usage of the library. 150 | /// 151 | /// Creating a new [SecretService] will also initialize dbus 152 | /// and negotiate a new cryptographic session 153 | /// ([EncryptionType::Plain] or [EncryptionType::Dh]) 154 | pub struct SecretService<'a> { 155 | conn: zbus::Connection, 156 | session: Session, 157 | service_proxy: ServiceProxy<'a>, 158 | } 159 | 160 | /// Used to indicate locked and unlocked items in the 161 | /// return value of [SecretService::search_items] 162 | /// and [blocking::SecretService::search_items]. 163 | pub struct SearchItemsResult { 164 | pub unlocked: Vec, 165 | pub locked: Vec, 166 | } 167 | 168 | impl<'a> SecretService<'a> { 169 | /// Create a new `SecretService` instance. 170 | pub async fn connect(encryption: EncryptionType) -> Result, Error> { 171 | let conn = zbus::Connection::session() 172 | .await 173 | .map_err(util::handle_conn_error)?; 174 | 175 | let service_proxy = ServiceProxy::new(&conn) 176 | .await 177 | .map_err(util::handle_conn_error)?; 178 | 179 | let session = Session::new(&service_proxy, encryption).await?; 180 | 181 | Ok(SecretService { 182 | conn, 183 | session, 184 | service_proxy, 185 | }) 186 | } 187 | 188 | /// Get all collections 189 | pub async fn get_all_collections(&self) -> Result>, Error> { 190 | let collections = self.service_proxy.collections().await?; 191 | 192 | futures_util::future::join_all(collections.into_iter().map(|object_path| { 193 | Collection::new( 194 | self.conn.clone(), 195 | &self.session, 196 | &self.service_proxy, 197 | object_path.into(), 198 | ) 199 | })) 200 | .await 201 | .into_iter() 202 | .collect::>() 203 | } 204 | 205 | /// Get collection by alias. 206 | /// 207 | /// Most common would be the `default` alias, but there 208 | /// is also a specific method for getting the collection 209 | /// by default alias. 210 | pub async fn get_collection_by_alias(&self, alias: &str) -> Result, Error> { 211 | let object_path = self.service_proxy.read_alias(alias).await?; 212 | 213 | if object_path.as_str() == "/" { 214 | Err(Error::NoResult) 215 | } else { 216 | Collection::new( 217 | self.conn.clone(), 218 | &self.session, 219 | &self.service_proxy, 220 | object_path, 221 | ) 222 | .await 223 | } 224 | } 225 | 226 | /// Get default collection. 227 | /// (The collection whos alias is `default`) 228 | pub async fn get_default_collection(&self) -> Result, Error> { 229 | self.get_collection_by_alias("default").await 230 | } 231 | 232 | /// Get any collection. 233 | /// First tries `default` collection, then `session` 234 | /// collection, then the first collection when it 235 | /// gets all collections. 236 | pub async fn get_any_collection(&self) -> Result, Error> { 237 | // default first, then session, then first 238 | 239 | self.get_default_collection() 240 | .or_else(|_| self.get_collection_by_alias("session")) 241 | .or_else(|_| async { 242 | let mut collections = self.get_all_collections().await?; 243 | if collections.is_empty() { 244 | Err(Error::NoResult) 245 | } else { 246 | Ok(collections.swap_remove(0)) 247 | } 248 | }) 249 | .await 250 | } 251 | 252 | /// Creates a new collection with a label and an alias. 253 | pub async fn create_collection( 254 | &self, 255 | label: &str, 256 | alias: &str, 257 | ) -> Result, Error> { 258 | let mut properties: HashMap<&str, Value> = HashMap::new(); 259 | properties.insert(SS_COLLECTION_LABEL, label.into()); 260 | 261 | let created_collection = self 262 | .service_proxy 263 | .create_collection(properties, alias) 264 | .await?; 265 | 266 | // This prompt handling is practically identical to create_collection 267 | let collection_path: ObjectPath = { 268 | // Get path of created object 269 | let created_path = created_collection.collection; 270 | 271 | // Check if that path is "/", if so should execute a prompt 272 | if created_path.as_str() == "/" { 273 | let prompt_path = created_collection.prompt; 274 | 275 | // Exec prompt and parse result 276 | let prompt_res = exec_prompt(self.conn.clone(), &prompt_path).await?; 277 | prompt_res.try_into()? 278 | } else { 279 | // if not, just return created path 280 | created_path.into() 281 | } 282 | }; 283 | 284 | Collection::new( 285 | self.conn.clone(), 286 | &self.session, 287 | &self.service_proxy, 288 | collection_path.into(), 289 | ) 290 | .await 291 | } 292 | 293 | /// Searches all items by attributes 294 | pub async fn search_items( 295 | &self, 296 | attributes: HashMap<&str, &str>, 297 | ) -> Result>, Error> { 298 | let items = self.service_proxy.search_items(attributes).await?; 299 | 300 | let object_paths_to_items = |items: Vec<_>| { 301 | futures_util::future::join_all(items.into_iter().map(|item_path| { 302 | Item::new( 303 | self.conn.clone(), 304 | &self.session, 305 | &self.service_proxy, 306 | item_path, 307 | ) 308 | })) 309 | }; 310 | 311 | Ok(SearchItemsResult { 312 | unlocked: object_paths_to_items(items.unlocked) 313 | .await 314 | .into_iter() 315 | .collect::>()?, 316 | locked: object_paths_to_items(items.locked) 317 | .await 318 | .into_iter() 319 | .collect::>()?, 320 | }) 321 | } 322 | 323 | /// Unlock all items in a batch 324 | pub async fn unlock_all(&self, items: &[&Item<'_>]) -> Result<(), Error> { 325 | let objects = items.iter().map(|i| &*i.item_path).collect(); 326 | let lock_action_res = self.service_proxy.unlock(objects).await?; 327 | 328 | if lock_action_res.object_paths.is_empty() { 329 | exec_prompt(self.conn.clone(), &lock_action_res.prompt).await?; 330 | } 331 | 332 | Ok(()) 333 | } 334 | } 335 | 336 | #[cfg(test)] 337 | mod test { 338 | use super::*; 339 | use std::convert::TryFrom; 340 | use zbus::zvariant::ObjectPath; 341 | 342 | #[tokio::test] 343 | async fn should_create_secret_service() { 344 | SecretService::connect(EncryptionType::Plain).await.unwrap(); 345 | } 346 | 347 | #[tokio::test] 348 | async fn should_get_all_collections() { 349 | // Assumes that there will always be a default collection 350 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 351 | let collections = ss.get_all_collections().await.unwrap(); 352 | assert!(!collections.is_empty(), "no collections found"); 353 | } 354 | 355 | #[tokio::test] 356 | async fn should_get_collection_by_alias() { 357 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 358 | ss.get_collection_by_alias("session").await.unwrap(); 359 | } 360 | 361 | #[tokio::test] 362 | async fn should_return_error_if_collection_doesnt_exist() { 363 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 364 | 365 | match ss 366 | .get_collection_by_alias("definitely_defintely_does_not_exist") 367 | .await 368 | { 369 | Err(Error::NoResult) => {} 370 | _ => panic!(), 371 | }; 372 | } 373 | 374 | #[tokio::test] 375 | async fn should_get_default_collection() { 376 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 377 | ss.get_default_collection().await.unwrap(); 378 | } 379 | 380 | #[tokio::test] 381 | async fn should_get_any_collection() { 382 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 383 | let _ = ss.get_any_collection().await.unwrap(); 384 | } 385 | 386 | #[test_with::no_env(GITHUB_ACTIONS)] 387 | #[tokio::test] 388 | async fn should_create_and_delete_collection() { 389 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 390 | let test_collection = ss.create_collection("Test", "").await.unwrap(); 391 | assert_eq!( 392 | ObjectPath::from(test_collection.collection_path.clone()), 393 | ObjectPath::try_from("/org/freedesktop/secrets/collection/Test").unwrap() 394 | ); 395 | test_collection.delete().await.unwrap(); 396 | } 397 | 398 | #[tokio::test] 399 | async fn should_search_items() { 400 | let ss = SecretService::connect(EncryptionType::Plain).await.unwrap(); 401 | let collection = ss.get_default_collection().await.unwrap(); 402 | 403 | // Create an item 404 | let item = collection 405 | .create_item( 406 | "test", 407 | HashMap::from([("test_attribute_in_ss", "test_value")]), 408 | b"test_secret", 409 | false, 410 | "text/plain", 411 | ) 412 | .await 413 | .unwrap(); 414 | 415 | // handle empty vec search 416 | ss.search_items(HashMap::new()).await.unwrap(); 417 | 418 | // handle no result 419 | let bad_search = ss 420 | .search_items(HashMap::from([("test", "test")])) 421 | .await 422 | .unwrap(); 423 | assert_eq!(bad_search.unlocked.len(), 0); 424 | assert_eq!(bad_search.locked.len(), 0); 425 | 426 | // handle correct search for item and compare 427 | let search_item = ss 428 | .search_items(HashMap::from([("test_attribute_in_ss", "test_value")])) 429 | .await 430 | .unwrap(); 431 | 432 | assert_eq!(item.item_path, search_item.unlocked[0].item_path); 433 | assert_eq!(search_item.locked.len(), 0); 434 | item.delete().await.unwrap(); 435 | } 436 | } 437 | -------------------------------------------------------------------------------- /src/proxy/collection.rs: -------------------------------------------------------------------------------- 1 | //! A dbus proxy for speaking with secret service's `Collection` Interface. 2 | 3 | use serde::{Deserialize, Serialize}; 4 | use std::collections::HashMap; 5 | use zbus::zvariant::{ObjectPath, OwnedObjectPath, Type, Value}; 6 | 7 | use super::SecretStruct; 8 | 9 | /// A dbus proxy for speaking with secret service's `Collection` Interface. 10 | /// 11 | /// This will derive CollectionProxy 12 | /// 13 | /// Note that `Value` in the method signatures corresponds to `VARIANT` dbus type. 14 | #[zbus::proxy( 15 | interface = "org.freedesktop.Secret.Collection", 16 | default_service = "org.freedesktop.Secret.Collection" 17 | )] 18 | pub trait Collection { 19 | /// Returns prompt: ObjectPath 20 | fn delete(&self) -> zbus::Result; 21 | 22 | fn search_items(&self, attributes: HashMap<&str, &str>) -> zbus::Result>; 23 | 24 | fn create_item( 25 | &self, 26 | properties: HashMap<&str, Value<'_>>, 27 | secret: SecretStruct, 28 | replace: bool, 29 | ) -> zbus::Result; 30 | 31 | #[zbus(property)] 32 | fn items(&self) -> zbus::fdo::Result>>; 33 | 34 | #[zbus(property)] 35 | fn label(&self) -> zbus::fdo::Result; 36 | 37 | #[zbus(property)] 38 | fn set_label(&self, new_label: &str) -> zbus::fdo::Result<()>; 39 | 40 | #[zbus(property)] 41 | fn locked(&self) -> zbus::fdo::Result; 42 | 43 | #[zbus(property)] 44 | fn created(&self) -> zbus::fdo::Result; 45 | 46 | #[zbus(property)] 47 | fn modified(&self) -> zbus::fdo::Result; 48 | } 49 | 50 | #[derive(Debug, Serialize, Deserialize, Type)] 51 | pub struct CreateItemResult { 52 | pub(crate) item: OwnedObjectPath, 53 | pub(crate) prompt: OwnedObjectPath, 54 | } 55 | -------------------------------------------------------------------------------- /src/proxy/item.rs: -------------------------------------------------------------------------------- 1 | //! A dbus proxy for speaking with secret service's `Item` Interface. 2 | 3 | use std::collections::HashMap; 4 | use zbus::zvariant::{ObjectPath, OwnedObjectPath}; 5 | 6 | use super::SecretStruct; 7 | 8 | /// A dbus proxy for speaking with secret service's `Item` Interface. 9 | /// 10 | /// This will derive ItemProxy 11 | #[zbus::proxy( 12 | interface = "org.freedesktop.Secret.Item", 13 | default_service = "org.freedesktop.Secret.Item" 14 | )] 15 | pub trait Item { 16 | fn delete(&self) -> zbus::Result; 17 | 18 | /// returns `Secret` 19 | fn get_secret(&self, session: &ObjectPath<'_>) -> zbus::Result; 20 | 21 | fn set_secret(&self, secret: SecretStruct) -> zbus::Result<()>; 22 | 23 | #[zbus(property)] 24 | fn locked(&self) -> zbus::fdo::Result; 25 | 26 | #[zbus(property)] 27 | fn attributes(&self) -> zbus::fdo::Result>; 28 | 29 | #[zbus(property)] 30 | fn set_attributes(&self, attributes: HashMap<&str, &str>) -> zbus::fdo::Result<()>; 31 | 32 | #[zbus(property)] 33 | fn label(&self) -> zbus::fdo::Result; 34 | 35 | #[zbus(property)] 36 | fn set_label(&self, new_label: &str) -> zbus::fdo::Result<()>; 37 | 38 | #[zbus(property)] 39 | fn created(&self) -> zbus::fdo::Result; 40 | 41 | #[zbus(property)] 42 | fn modified(&self) -> zbus::fdo::Result; 43 | } 44 | -------------------------------------------------------------------------------- /src/proxy/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod collection; 2 | pub mod item; 3 | pub mod prompt; 4 | pub mod service; 5 | 6 | use serde::{Deserialize, Serialize}; 7 | use zbus::zvariant::{OwnedObjectPath, Type}; 8 | 9 | #[derive(Debug, Serialize, Deserialize, Type)] 10 | pub struct SecretStruct { 11 | pub(crate) session: OwnedObjectPath, 12 | pub(crate) parameters: Vec, 13 | pub(crate) value: Vec, 14 | pub(crate) content_type: String, 15 | } 16 | -------------------------------------------------------------------------------- /src/proxy/prompt.rs: -------------------------------------------------------------------------------- 1 | //! A dbus proxy for speaking with secret service's `Prompt` Interface. 2 | 3 | use zbus::zvariant::Value; 4 | 5 | /// A dbus proxy for speaking with secret service's `Prompt` Interface. 6 | /// 7 | /// This will derive PromptProxy 8 | /// 9 | /// Note that `Value` in the method signatures corresponds to `VARIANT` dbus type. 10 | #[zbus::proxy( 11 | interface = "org.freedesktop.Secret.Prompt", 12 | default_service = "org.freedesktop.Secret.Prompt" 13 | )] 14 | pub trait Prompt { 15 | fn prompt(&self, window_id: &str) -> zbus::Result<()>; 16 | 17 | fn dismiss(&self) -> zbus::Result<()>; 18 | 19 | #[zbus(signal)] 20 | fn completed(&self, dismissed: bool, result: Value<'_>) -> zbus::Result<()>; 21 | } 22 | -------------------------------------------------------------------------------- /src/proxy/service.rs: -------------------------------------------------------------------------------- 1 | //! A dbus proxy for speaking with secret service's `Service` Interface. 2 | 3 | use super::SecretStruct; 4 | use serde::{Deserialize, Serialize}; 5 | use std::collections::HashMap; 6 | use zbus::zvariant::{ObjectPath, OwnedObjectPath, OwnedValue, Type, Value}; 7 | 8 | /// A dbus proxy for speaking with secret service's `Service` Interface. 9 | /// 10 | /// This will derive ServiceProxy 11 | /// 12 | /// Note that `Value` in the method signatures corresponds to `VARIANT` dbus type. 13 | #[zbus::proxy( 14 | interface = "org.freedesktop.Secret.Service", 15 | default_service = "org.freedesktop.secrets", 16 | default_path = "/org/freedesktop/secrets" 17 | )] 18 | pub trait Service { 19 | fn open_session(&self, algorithm: &str, input: Value<'_>) -> zbus::Result; 20 | 21 | fn create_collection( 22 | &self, 23 | properties: HashMap<&str, Value<'_>>, 24 | alias: &str, 25 | ) -> zbus::Result; 26 | 27 | fn search_items(&self, attributes: HashMap<&str, &str>) -> zbus::Result; 28 | 29 | fn unlock(&self, objects: Vec<&ObjectPath<'_>>) -> zbus::Result; 30 | 31 | fn lock(&self, objects: Vec<&ObjectPath<'_>>) -> zbus::Result; 32 | 33 | fn get_secrets( 34 | &self, 35 | objects: Vec>, 36 | ) -> zbus::Result>; 37 | 38 | fn read_alias(&self, name: &str) -> zbus::Result; 39 | 40 | fn set_alias(&self, name: &str, collection: ObjectPath<'_>) -> zbus::Result<()>; 41 | 42 | #[zbus(property)] 43 | fn collections(&self) -> zbus::fdo::Result>>; 44 | } 45 | 46 | #[derive(Debug, Serialize, Deserialize, Type)] 47 | pub struct OpenSessionResult { 48 | pub(crate) output: OwnedValue, 49 | pub(crate) result: OwnedObjectPath, 50 | } 51 | 52 | #[derive(Debug, Serialize, Deserialize, Type)] 53 | pub struct CreateCollectionResult { 54 | pub(crate) collection: OwnedObjectPath, 55 | pub(crate) prompt: OwnedObjectPath, 56 | } 57 | 58 | #[derive(Debug, Serialize, Deserialize, Type)] 59 | pub struct SearchItemsResult { 60 | pub(crate) unlocked: Vec, 61 | pub(crate) locked: Vec, 62 | } 63 | 64 | #[derive(Debug, Serialize, Deserialize, Type)] 65 | pub struct LockActionResult { 66 | pub(crate) object_paths: Vec, 67 | pub(crate) prompt: OwnedObjectPath, 68 | } 69 | -------------------------------------------------------------------------------- /src/session.rs: -------------------------------------------------------------------------------- 1 | // key exchange and crypto for session: 2 | // 1. Before session negotiation (openSession), set private key and public key using DH method. 3 | // 2. In session negotiation, send public key. 4 | // 3. As result of session negotiation, get object path for session, which (I think 5 | // it means that it uses the same server public key to create an aes key which is used 6 | // to decode the encoded secret using the aes seed that's sent with the secret). 7 | // 4. As result of session negotition, get server public key. 8 | // 5. Use server public key, my private key, to set an aes key using HKDF. 9 | // 6. Format Secret: aes iv is random seed, in secret struct it's the parameter (Array(Byte)) 10 | // 7. Format Secret: encode the secret value for the value field in secret struct. 11 | // This encoding uses the aes_key from the associated Session. 12 | 13 | use crate::proxy::service::{OpenSessionResult, ServiceProxy, ServiceProxyBlocking}; 14 | use crate::ss::{ALGORITHM_DH, ALGORITHM_PLAIN}; 15 | use crate::Error; 16 | 17 | use generic_array::{typenum::U16, GenericArray}; 18 | use num::{ 19 | bigint::BigUint, 20 | integer::Integer, 21 | traits::{One, Zero}, 22 | FromPrimitive, 23 | }; 24 | use once_cell::sync::Lazy; 25 | use zbus::zvariant::OwnedObjectPath; 26 | 27 | use std::ops::{Mul, Rem, Shr}; 28 | 29 | // for key exchange 30 | static DH_GENERATOR: Lazy = Lazy::new(|| BigUint::from_u64(0x2).unwrap()); 31 | static DH_PRIME: Lazy = Lazy::new(|| { 32 | BigUint::from_bytes_be(&[ 33 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 34 | 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 35 | 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 36 | 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 37 | 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 38 | 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 39 | 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 40 | 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81, 41 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 42 | ]) 43 | }); 44 | 45 | #[allow(unused_macros)] 46 | macro_rules! feature_needed { 47 | () => { 48 | compile_error!("Please enable a feature to pick a runtime (such as rt-async-io-crypto-rust or rt-tokio-crypto-rust) for the secret-service crate") 49 | } 50 | } 51 | 52 | type AesKey = GenericArray; 53 | 54 | #[derive(Debug, Eq, PartialEq)] 55 | pub enum EncryptionType { 56 | Plain, 57 | Dh, 58 | } 59 | 60 | struct Keypair { 61 | private: BigUint, 62 | public: BigUint, 63 | } 64 | 65 | impl Keypair { 66 | fn generate() -> Self { 67 | let mut private_key_bytes = [0; 128]; 68 | getrandom::getrandom(&mut private_key_bytes).expect("platform RNG failed"); 69 | 70 | let private_key = BigUint::from_bytes_be(&private_key_bytes); 71 | let public_key = powm(&DH_GENERATOR, &private_key, &DH_PRIME); 72 | 73 | Self { 74 | private: private_key, 75 | public: public_key, 76 | } 77 | } 78 | 79 | fn derive_shared(&self, server_public_key: &BigUint) -> AesKey { 80 | // Derive the shared secret the server and us. 81 | let common_secret = powm(server_public_key, &self.private, &DH_PRIME); 82 | 83 | let mut common_secret_bytes = common_secret.to_bytes_be(); 84 | let mut common_secret_padded = vec![0; 128 - common_secret_bytes.len()]; 85 | common_secret_padded.append(&mut common_secret_bytes); 86 | 87 | // hkdf 88 | 89 | // input keying material 90 | let ikm = common_secret_padded; 91 | let salt = None; 92 | 93 | // output keying material 94 | let mut okm = [0; 16]; 95 | hkdf(ikm, salt, &mut okm); 96 | 97 | GenericArray::clone_from_slice(&okm) 98 | } 99 | } 100 | 101 | #[cfg(feature = "crypto-openssl")] 102 | fn hkdf(ikm: Vec, salt: Option<&[u8]>, okm: &mut [u8]) { 103 | let mut ctx = openssl::pkey_ctx::PkeyCtx::new_id(openssl::pkey::Id::HKDF) 104 | .expect("hkdf context should not fail"); 105 | ctx.derive_init().expect("hkdf derive init should not fail"); 106 | ctx.set_hkdf_md(openssl::md::Md::sha256()) 107 | .expect("hkdf set md should not fail"); 108 | 109 | ctx.set_hkdf_key(&ikm) 110 | .expect("hkdf set key should not fail"); 111 | if let Some(salt) = salt { 112 | ctx.set_hkdf_salt(salt) 113 | .expect("hkdf set salt should not fail"); 114 | } 115 | 116 | ctx.add_hkdf_info(&[]).unwrap(); 117 | ctx.derive(Some(okm)) 118 | .expect("hkdf expand should never fail"); 119 | } 120 | 121 | #[cfg(feature = "crypto-rust")] 122 | fn hkdf(ikm: Vec, salt: Option<&[u8]>, okm: &mut [u8]) { 123 | use hkdf::Hkdf; 124 | use sha2::Sha256; 125 | 126 | let info = []; 127 | let (_, hk) = Hkdf::::extract(salt, &ikm); 128 | hk.expand(&info, okm) 129 | .expect("hkdf expand should never fail"); 130 | } 131 | 132 | #[cfg(all(not(feature = "crypto-rust"), not(feature = "crypto-openssl")))] 133 | fn hkdf(ikm: Vec, salt: Option<&[u8]>, okm: &mut [u8]) { 134 | feature_needed!() 135 | } 136 | 137 | pub struct Session { 138 | pub object_path: OwnedObjectPath, 139 | aes_key: Option, 140 | } 141 | 142 | impl Session { 143 | fn encrypted_session(keypair: &Keypair, session: OpenSessionResult) -> Result { 144 | let server_public_key = session 145 | .output 146 | .try_into() 147 | .map(|key: Vec| BigUint::from_bytes_be(&key))?; 148 | 149 | let aes_key = keypair.derive_shared(&server_public_key); 150 | 151 | Ok(Session { 152 | object_path: session.result, 153 | aes_key: Some(aes_key), 154 | }) 155 | } 156 | 157 | pub fn new_blocking( 158 | service_proxy: &ServiceProxyBlocking, 159 | encryption: EncryptionType, 160 | ) -> Result { 161 | match encryption { 162 | EncryptionType::Plain => { 163 | let session = service_proxy.open_session(ALGORITHM_PLAIN, "".into())?; 164 | let session_path = session.result; 165 | 166 | Ok(Session { 167 | object_path: session_path, 168 | aes_key: None, 169 | }) 170 | } 171 | EncryptionType::Dh => { 172 | let keypair = Keypair::generate(); 173 | 174 | let session = service_proxy 175 | .open_session(ALGORITHM_DH, keypair.public.to_bytes_be().into())?; 176 | 177 | Self::encrypted_session(&keypair, session) 178 | } 179 | } 180 | } 181 | 182 | pub async fn new( 183 | service_proxy: &ServiceProxy<'_>, 184 | encryption: EncryptionType, 185 | ) -> Result { 186 | match encryption { 187 | EncryptionType::Plain => { 188 | let session = service_proxy 189 | .open_session(ALGORITHM_PLAIN, "".into()) 190 | .await?; 191 | let session_path = session.result; 192 | 193 | Ok(Session { 194 | object_path: session_path, 195 | aes_key: None, 196 | }) 197 | } 198 | EncryptionType::Dh => { 199 | let keypair = Keypair::generate(); 200 | 201 | let session = service_proxy 202 | .open_session(ALGORITHM_DH, keypair.public.to_bytes_be().into()) 203 | .await?; 204 | 205 | Self::encrypted_session(&keypair, session) 206 | } 207 | } 208 | } 209 | 210 | pub fn get_aes_key(&self) -> Option<&AesKey> { 211 | self.aes_key.as_ref() 212 | } 213 | } 214 | 215 | /// from https://github.com/plietar/librespot/blob/master/core/src/util/mod.rs#L53 216 | fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint { 217 | let mut base = base.clone(); 218 | let mut exp = exp.clone(); 219 | let mut result: BigUint = One::one(); 220 | 221 | while !exp.is_zero() { 222 | if exp.is_odd() { 223 | result = result.mul(&base).rem(modulus); 224 | } 225 | exp = exp.shr(1); 226 | base = (&base).mul(&base).rem(modulus); 227 | } 228 | 229 | result 230 | } 231 | 232 | #[cfg(feature = "crypto-rust")] 233 | pub fn encrypt(data: &[u8], key: &AesKey, iv: &[u8]) -> Vec { 234 | use aes::cipher::block_padding::Pkcs7; 235 | use aes::cipher::{BlockEncryptMut, KeyIvInit}; 236 | 237 | type Aes128CbcEnc = cbc::Encryptor; 238 | 239 | let iv = GenericArray::from_slice(iv); 240 | 241 | Aes128CbcEnc::new(key, iv).encrypt_padded_vec_mut::(data) 242 | } 243 | 244 | #[cfg(feature = "crypto-rust")] 245 | pub fn decrypt(encrypted_data: &[u8], key: &AesKey, iv: &[u8]) -> Result, Error> { 246 | use aes::cipher::block_padding::Pkcs7; 247 | use aes::cipher::{BlockDecryptMut, KeyIvInit}; 248 | 249 | type Aes128CbcDec = cbc::Decryptor; 250 | 251 | let iv = GenericArray::from_slice(iv); 252 | Aes128CbcDec::new(key, iv) 253 | .decrypt_padded_vec_mut::(encrypted_data) 254 | .map_err(|_| Error::Crypto("message decryption failed")) 255 | } 256 | 257 | #[cfg(feature = "crypto-openssl")] 258 | pub fn encrypt(data: &[u8], key: &AesKey, iv: &[u8]) -> Vec { 259 | use openssl::cipher::Cipher; 260 | use openssl::cipher_ctx::CipherCtx; 261 | 262 | let mut ctx = CipherCtx::new().expect("cipher creation should not fail"); 263 | ctx.encrypt_init(Some(Cipher::aes_128_cbc()), Some(key), Some(iv)) 264 | .expect("cipher init should not fail"); 265 | 266 | let mut output = vec![]; 267 | ctx.cipher_update_vec(data, &mut output) 268 | .expect("cipher update should not fail"); 269 | ctx.cipher_final_vec(&mut output) 270 | .expect("cipher final should not fail"); 271 | output 272 | } 273 | 274 | #[cfg(feature = "crypto-openssl")] 275 | pub fn decrypt(encrypted_data: &[u8], key: &AesKey, iv: &[u8]) -> Result, Error> { 276 | use openssl::cipher::Cipher; 277 | use openssl::cipher_ctx::CipherCtx; 278 | 279 | let mut ctx = CipherCtx::new().expect("cipher creation should not fail"); 280 | ctx.decrypt_init(Some(Cipher::aes_128_cbc()), Some(key), Some(iv)) 281 | .expect("cipher init should not fail"); 282 | 283 | let mut output = vec![]; 284 | ctx.cipher_update_vec(encrypted_data, &mut output) 285 | .map_err(|_| Error::Crypto("message decryption failed"))?; 286 | ctx.cipher_final_vec(&mut output) 287 | .map_err(|_| Error::Crypto("message decryption failed"))?; 288 | Ok(output) 289 | } 290 | 291 | #[cfg(all(not(feature = "crypto-rust"), not(feature = "crypto-openssl")))] 292 | pub fn encrypt(data: &[u8], key: &AesKey, iv: &[u8]) -> Vec { 293 | feature_needed!() 294 | } 295 | 296 | #[cfg(all(not(feature = "crypto-rust"), not(feature = "crypto-openssl")))] 297 | pub fn decrypt(encrypted_data: &[u8], key: &AesKey, iv: &[u8]) -> Result, Error> { 298 | feature_needed!() 299 | } 300 | 301 | #[cfg(test)] 302 | mod test { 303 | use super::*; 304 | 305 | // There is no async test because this tests that an encryption session can be made, nothing more. 306 | 307 | #[test] 308 | fn should_create_plain_session() { 309 | let conn = zbus::blocking::Connection::session().unwrap(); 310 | let service_proxy = ServiceProxyBlocking::new(&conn).unwrap(); 311 | let session = Session::new_blocking(&service_proxy, EncryptionType::Plain).unwrap(); 312 | assert!(session.get_aes_key().is_none()); 313 | } 314 | 315 | #[test] 316 | fn should_create_encrypted_session() { 317 | let conn = zbus::blocking::Connection::session().unwrap(); 318 | let service_proxy = ServiceProxyBlocking::new(&conn).unwrap(); 319 | let session = Session::new_blocking(&service_proxy, EncryptionType::Dh).unwrap(); 320 | assert!(session.get_aes_key().is_some()); 321 | } 322 | } 323 | -------------------------------------------------------------------------------- /src/ss.rs: -------------------------------------------------------------------------------- 1 | //! Definitions for secret service interactions 2 | 3 | // DBus Name 4 | pub const SS_DBUS_NAME: &str = "org.freedesktop.secrets"; 5 | 6 | // Item Properties 7 | pub const SS_ITEM_LABEL: &str = "org.freedesktop.Secret.Item.Label"; 8 | pub const SS_ITEM_ATTRIBUTES: &str = "org.freedesktop.Secret.Item.Attributes"; 9 | 10 | // Algorithm Names 11 | pub const ALGORITHM_PLAIN: &str = "plain"; 12 | pub const ALGORITHM_DH: &str = "dh-ietf1024-sha256-aes128-cbc-pkcs7"; 13 | 14 | // Collection properties 15 | pub const SS_COLLECTION_LABEL: &str = "org.freedesktop.Secret.Collection.Label"; 16 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | //! Contains helpers for: 2 | //! locking/unlocking 3 | //! exec_prompt 4 | //! formatting secrets 5 | 6 | use crate::error::Error; 7 | use crate::proxy::prompt::{Completed, PromptProxy, PromptProxyBlocking}; 8 | use crate::proxy::service::{ServiceProxy, ServiceProxyBlocking}; 9 | use crate::proxy::SecretStruct; 10 | use crate::session::encrypt; 11 | use crate::session::Session; 12 | use crate::ss::SS_DBUS_NAME; 13 | 14 | use futures_util::StreamExt; 15 | use zbus::{ 16 | proxy::CacheProperties, 17 | zvariant::{self, ObjectPath}, 18 | }; 19 | 20 | // Helper enum for locking 21 | pub(crate) enum LockAction { 22 | Lock, 23 | Unlock, 24 | } 25 | 26 | pub(crate) async fn lock_or_unlock( 27 | conn: zbus::Connection, 28 | service_proxy: &ServiceProxy<'_>, 29 | object_path: &ObjectPath<'_>, 30 | lock_action: LockAction, 31 | ) -> Result<(), Error> { 32 | let objects = vec![object_path]; 33 | 34 | let lock_action_res = match lock_action { 35 | LockAction::Lock => service_proxy.lock(objects).await?, 36 | LockAction::Unlock => service_proxy.unlock(objects).await?, 37 | }; 38 | 39 | if lock_action_res.object_paths.is_empty() { 40 | exec_prompt(conn, &lock_action_res.prompt).await?; 41 | } 42 | Ok(()) 43 | } 44 | 45 | pub(crate) fn lock_or_unlock_blocking( 46 | conn: zbus::blocking::Connection, 47 | service_proxy: &ServiceProxyBlocking, 48 | object_path: &ObjectPath, 49 | lock_action: LockAction, 50 | ) -> Result<(), Error> { 51 | let objects = vec![object_path]; 52 | 53 | let lock_action_res = match lock_action { 54 | LockAction::Lock => service_proxy.lock(objects)?, 55 | LockAction::Unlock => service_proxy.unlock(objects)?, 56 | }; 57 | 58 | if lock_action_res.object_paths.is_empty() { 59 | exec_prompt_blocking(conn, &lock_action_res.prompt)?; 60 | } 61 | Ok(()) 62 | } 63 | 64 | pub(crate) fn format_secret( 65 | session: &Session, 66 | secret: &[u8], 67 | content_type: &str, 68 | ) -> Result { 69 | let content_type = content_type.to_owned(); 70 | 71 | if let Some(session_key) = session.get_aes_key() { 72 | let mut aes_iv = [0; 16]; 73 | getrandom::getrandom(&mut aes_iv).expect("platform RNG failed"); 74 | 75 | let encrypted_secret = encrypt(secret, session_key, &aes_iv); 76 | 77 | // Construct secret struct 78 | let parameters = aes_iv.to_vec(); 79 | let value = encrypted_secret; 80 | 81 | Ok(SecretStruct { 82 | session: session.object_path.clone(), 83 | parameters, 84 | value, 85 | content_type, 86 | }) 87 | } else { 88 | // just Plain for now 89 | let parameters = Vec::new(); 90 | let value = secret.to_vec(); 91 | 92 | Ok(SecretStruct { 93 | session: session.object_path.clone(), 94 | parameters, 95 | value, 96 | content_type, 97 | }) 98 | } 99 | } 100 | 101 | // TODO: Users could pass their own window ID in. 102 | const NO_WINDOW_ID: &str = ""; 103 | 104 | pub(crate) async fn exec_prompt( 105 | conn: zbus::Connection, 106 | prompt: &ObjectPath<'_>, 107 | ) -> Result { 108 | let prompt_proxy = PromptProxy::builder(&conn) 109 | .destination(SS_DBUS_NAME)? 110 | .path(prompt)? 111 | .cache_properties(CacheProperties::No) 112 | .build() 113 | .await?; 114 | 115 | let mut receive_completed_iter = prompt_proxy.receive_completed().await?; 116 | prompt_proxy.prompt(NO_WINDOW_ID).await?; 117 | 118 | handle_signal(receive_completed_iter.next().await.unwrap()) 119 | } 120 | 121 | pub(crate) fn exec_prompt_blocking( 122 | conn: zbus::blocking::Connection, 123 | prompt: &ObjectPath, 124 | ) -> Result { 125 | let prompt_proxy = PromptProxyBlocking::builder(&conn) 126 | .destination(SS_DBUS_NAME)? 127 | .path(prompt)? 128 | .cache_properties(CacheProperties::No) 129 | .build()?; 130 | 131 | let mut receive_completed_iter = prompt_proxy.receive_completed()?; 132 | prompt_proxy.prompt(NO_WINDOW_ID)?; 133 | 134 | handle_signal(receive_completed_iter.next().unwrap()) 135 | } 136 | 137 | fn handle_signal(signal: Completed) -> Result { 138 | let args = signal.args()?; 139 | if args.dismissed { 140 | Err(Error::Prompt) 141 | } else { 142 | zvariant::OwnedValue::try_from(args.result).map_err(From::from) 143 | } 144 | } 145 | 146 | pub(crate) fn handle_conn_error(e: zbus::Error) -> Error { 147 | match e { 148 | zbus::Error::InterfaceNotFound | zbus::Error::Address(_) => Error::Unavailable, 149 | zbus::Error::InputOutput(e) if e.kind() == std::io::ErrorKind::NotFound => { 150 | Error::Unavailable 151 | } 152 | e => e.into(), 153 | } 154 | } 155 | --------------------------------------------------------------------------------