parsec-interface-0.29.1/.cargo/audit.toml 0000644 0000000 0000000 00000002020 10461020230 0016276 0 ustar 0000000 0000000 [advisories]
ignore = []
informational_warnings = ["unmaintained"] # warn for categories of informational advisories
severity_threshold = "low" # CVSS severity ("none", "low", "medium", "high", "critical")
# Advisory Database Configuration
[database]
path = "/tmp/advisory-db" # Path where advisory git repo will be cloned
url = "https://github.com/RustSec/advisory-db.git" # URL to git repo
fetch = true # Perform a `git fetch` before auditing
stale = false # Allow stale advisory DB (i.e. no commits for 90 days)
# Output Configuration
[output]
deny = ["unmaintained"] # exit on error if unmaintained dependencies are found
format = "terminal" # "terminal" (human readable report) or "json"
quiet = false # Only print information on error
show_tree = true # Show inverse dependency trees along with advisories
# Target Configuration
[target]
os = "linux" # Ignore advisories for operating systems other than this one
[yanked]
enabled = true # Warn for yanked crates in Cargo.lock
update_index = true # Auto-update the crates.io index
parsec-interface-0.29.1/.cargo_vcs_info.json 0000644 00000000136 00000000001 0014340 0 ustar {
"git": {
"sha1": "ce9ab8b003ced37d07aa473fb52ccb1245368234"
},
"path_in_vcs": ""
} parsec-interface-0.29.1/.github/workflows/ci.yml 0000644 0000000 0000000 00000001045 10461020230 0017643 0 ustar 0000000 0000000 name: Continuous Integration
on: [push, pull_request, workflow_dispatch]
jobs:
build:
name: Build and check formatting
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Execute all tests
run: ./tests/ci.sh
links:
name: Check links
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Link Checker
uses: peter-evans/link-checker@v1
with:
args: -v -r *.md
- name: Fail if there were link errors
run: exit ${{ steps.lc.outputs.exit_code }}
parsec-interface-0.29.1/.github/workflows/nightly.yml 0000644 0000000 0000000 00000002737 10461020230 0020737 0 ustar 0000000 0000000 name: Nightly Checks
on:
schedule:
# Every night at midnight
- cron: '0 0 * * *'
workflow_dispatch:
inputs:
rev:
description: "Revision hash to run against"
required: false
default: ""
jobs:
dependencies:
name: Check for unused dependencies
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: "${{ github.event.inputs.rev }}"
- name: Install latest Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
- name: Fetch submodules
run: git submodule update --init
- name: Install cargo udeps
run: cargo install cargo-udeps --locked
- name: Execute cargo udeps
run: cargo +nightly udeps
build:
name: Build and check formatting with updated dependencies
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: "${{ github.event.inputs.rev }}"
- name: Execute all tests
run: |
rm Cargo.lock
./tests/ci.sh
audit:
name: Check for crates with security vulnerabilities
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: "${{ github.event.inputs.rev }}"
- name: Install latest Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
- name: Install cargo audit
run: cargo install cargo-audit
- name: Execute cargo audit
run: cargo audit
parsec-interface-0.29.1/.gitignore 0000644 0000000 0000000 00000000024 10461020230 0015114 0 ustar 0000000 0000000 /target
tags
*patch
parsec-interface-0.29.1/.gitmodules 0000644 0000000 0000000 00000000171 10461020230 0015304 0 ustar 0000000 0000000 [submodule "parsec-operations"]
path = parsec-operations
url = https://github.com/parallaxsecond/parsec-operations.git
parsec-interface-0.29.1/.travis.yml.disabled 0000644 0000000 0000000 00000000160 10461020230 0017004 0 ustar 0000000 0000000 # Executing our tests on Arm64 with Travis CI
arch: arm64
dist: bionic
language: rust
script:
- ./tests/ci.sh
parsec-interface-0.29.1/CHANGELOG.md 0000644 0000000 0000000 00000066075 10461020230 0014757 0 ustar 0000000 0000000 # Changelog
## [0.29.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.29.1) (2023-10-16)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.29.0...0.29.1)
**Merged pull requests:**
- Bump psa-crypto to 0.12.0 [\#146](https://github.com/parallaxsecond/parsec-interface-rs/pull/146) ([tgonzalezorlandoarm](https://github.com/tgonzalezorlandoarm))
## [0.29.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.29.0) (2023-10-06)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.28.0...0.29.0)
**Merged pull requests:**
- Bump psa-crypto to 0.11.0 [\#144](https://github.com/parallaxsecond/parsec-interface-rs/pull/144) ([tgonzalezorlandoarm](https://github.com/tgonzalezorlandoarm))
- Bump num-derive to 0.4.0 [\#143](https://github.com/parallaxsecond/parsec-interface-rs/pull/143) ([tgonzalezorlandoarm](https://github.com/tgonzalezorlandoarm))
- Cargo.toml: Bump prost and prost-build to 0.9.0 [\#142](https://github.com/parallaxsecond/parsec-interface-rs/pull/142) ([tgonzalezorlandoarm](https://github.com/tgonzalezorlandoarm))
- Tg/msrv 1.66.0 [\#141](https://github.com/parallaxsecond/parsec-interface-rs/pull/141) ([tgonzalezorlandoarm](https://github.com/tgonzalezorlandoarm))
- Fix nightly issues [\#140](https://github.com/parallaxsecond/parsec-interface-rs/pull/140) ([gowthamsk-arm](https://github.com/gowthamsk-arm))
- Bump secrecy crate [\#139](https://github.com/parallaxsecond/parsec-interface-rs/pull/139) ([gowthamsk-arm](https://github.com/gowthamsk-arm))
## [0.28.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.28.0) (2023-03-13)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.27.0...0.28.0)
**Merged pull requests:**
- Fix CI issues [\#136](https://github.com/parallaxsecond/parsec-interface-rs/pull/136) ([gowthamsk-arm](https://github.com/gowthamsk-arm))
- Do not derive Arbitrary for types not implementing it [\#135](https://github.com/parallaxsecond/parsec-interface-rs/pull/135) ([ema](https://github.com/ema))
- Update to remove const\_err [\#134](https://github.com/parallaxsecond/parsec-interface-rs/pull/134) ([marcsvll](https://github.com/marcsvll))
## [0.27.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.27.0) (2022-09-09)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.26.0...0.27.0)
**Implemented enhancements:**
- Strongify wire header serialization [\#115](https://github.com/parallaxsecond/parsec-interface-rs/issues/115)
- Validate hash length for psa\_sign\_hash [\#107](https://github.com/parallaxsecond/parsec-interface-rs/issues/107)
- Find a way to represent deprecated primitives [\#33](https://github.com/parallaxsecond/parsec-interface-rs/issues/33)
**Merged pull requests:**
- Release prep 0.27.0 [\#132](https://github.com/parallaxsecond/parsec-interface-rs/pull/132) ([mohamedasaker-arm](https://github.com/mohamedasaker-arm))
- Use psa-crypto with updated zeroize [\#131](https://github.com/parallaxsecond/parsec-interface-rs/pull/131) ([gowthamsk-arm](https://github.com/gowthamsk-arm))
- Fix clippy warnings and ignore those under generated ops [\#130](https://github.com/parallaxsecond/parsec-interface-rs/pull/130) ([mohamedasaker-arm](https://github.com/mohamedasaker-arm))
- Feature/33 represent check deprecated primitives [\#129](https://github.com/parallaxsecond/parsec-interface-rs/pull/129) ([mohamedasaker-arm](https://github.com/mohamedasaker-arm))
- Configure bincode used in wire header serialization/deserialization [\#128](https://github.com/parallaxsecond/parsec-interface-rs/pull/128) ([mohamedasaker-arm](https://github.com/mohamedasaker-arm))
## [0.26.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.26.0) (2022-02-15)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.25.0...0.26.0)
**Implemented enhancements:**
- Add key attestation operations [\#124](https://github.com/parallaxsecond/parsec-interface-rs/pull/124) ([ionut-arm](https://github.com/ionut-arm))
**Merged pull requests:**
- Prepare for 0.26.0 release [\#126](https://github.com/parallaxsecond/parsec-interface-rs/pull/126) ([ionut-arm](https://github.com/ionut-arm))
- Merge can-do-crypto branch into main [\#125](https://github.com/parallaxsecond/parsec-interface-rs/pull/125) ([anta5010](https://github.com/anta5010))
- Merge origin/main into can-do-crypto [\#123](https://github.com/parallaxsecond/parsec-interface-rs/pull/123) ([anta5010](https://github.com/anta5010))
- Add PsaCipherEncrypt and PsaCipherDecrypt operations [\#122](https://github.com/parallaxsecond/parsec-interface-rs/pull/122) ([akazimierskigl](https://github.com/akazimierskigl))
- Upgrade prost to 0.8.0 [\#121](https://github.com/parallaxsecond/parsec-interface-rs/pull/121) ([hug-dev](https://github.com/hug-dev))
- Added the changes required for the CanDoCrypto operation. [\#120](https://github.com/parallaxsecond/parsec-interface-rs/pull/120) ([Kakemone](https://github.com/Kakemone))
- Update CHANGELOG [\#119](https://github.com/parallaxsecond/parsec-interface-rs/pull/119) ([hug-dev](https://github.com/hug-dev))
## [0.25.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.25.0) (2021-08-03)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.24.0...0.25.0)
**Implemented enhancements:**
- Investigate pre-generating Rust protobuf code [\#98](https://github.com/parallaxsecond/parsec-interface-rs/issues/98)
- Implement Deref on RequestBody and ResponseBody [\#61](https://github.com/parallaxsecond/parsec-interface-rs/issues/61)
**Fixed bugs:**
- Check that reserved fields are zero [\#109](https://github.com/parallaxsecond/parsec-interface-rs/pull/109) ([hug-dev](https://github.com/hug-dev))
**Security fixes:**
- Bump prost crate versions [\#112](https://github.com/parallaxsecond/parsec-interface-rs/pull/112) ([ionut-arm](https://github.com/ionut-arm))
**Merged pull requests:**
- Prepare for next release [\#118](https://github.com/parallaxsecond/parsec-interface-rs/pull/118) ([hug-dev](https://github.com/hug-dev))
- Commit the generated Rust protobuf files in tree [\#117](https://github.com/parallaxsecond/parsec-interface-rs/pull/117) ([hug-dev](https://github.com/hug-dev))
- Implement Deref\(Mut\) on bodies [\#116](https://github.com/parallaxsecond/parsec-interface-rs/pull/116) ([hug-dev](https://github.com/hug-dev))
- Add a cargo audit config [\#114](https://github.com/parallaxsecond/parsec-interface-rs/pull/114) ([hug-dev](https://github.com/hug-dev))
- Revert "Bump prost crate versions" [\#113](https://github.com/parallaxsecond/parsec-interface-rs/pull/113) ([ionut-arm](https://github.com/ionut-arm))
- Update psa-crypto [\#110](https://github.com/parallaxsecond/parsec-interface-rs/pull/110) ([hug-dev](https://github.com/hug-dev))
- Add more precision to error messages [\#108](https://github.com/parallaxsecond/parsec-interface-rs/pull/108) ([hug-dev](https://github.com/hug-dev))
- Fix latest clippy lints [\#106](https://github.com/parallaxsecond/parsec-interface-rs/pull/106) ([hug-dev](https://github.com/hug-dev))
- Add PsaSignMessage and PsaVerifyMessage operations [\#105](https://github.com/parallaxsecond/parsec-interface-rs/pull/105) ([akazimierskigl](https://github.com/akazimierskigl))
- Add updated changelog [\#104](https://github.com/parallaxsecond/parsec-interface-rs/pull/104) ([hug-dev](https://github.com/hug-dev))
## [0.24.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.24.0) (2021-03-18)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.23.0...0.24.0)
**Implemented enhancements:**
- Rename ProviderID [\#36](https://github.com/parallaxsecond/parsec-interface-rs/issues/36)
- Investigate possible use of zerocopy [\#10](https://github.com/parallaxsecond/parsec-interface-rs/issues/10)
**Merged pull requests:**
- Add version 0.24.0 [\#103](https://github.com/parallaxsecond/parsec-interface-rs/pull/103) ([hug-dev](https://github.com/hug-dev))
- Update psa-crypto dependence [\#102](https://github.com/parallaxsecond/parsec-interface-rs/pull/102) ([hug-dev](https://github.com/hug-dev))
- Implement Display on ProviderID and AuthType [\#101](https://github.com/parallaxsecond/parsec-interface-rs/pull/101) ([hug-dev](https://github.com/hug-dev))
- Add log message to help debugging [\#100](https://github.com/parallaxsecond/parsec-interface-rs/pull/100) ([hug-dev](https://github.com/hug-dev))
- Use newest PSA Crypto crate version [\#99](https://github.com/parallaxsecond/parsec-interface-rs/pull/99) ([ionut-arm](https://github.com/ionut-arm))
- Add Changelog file [\#97](https://github.com/parallaxsecond/parsec-interface-rs/pull/97) ([ionut-arm](https://github.com/ionut-arm))
## [0.23.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.23.0) (2021-01-19)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.22.0...0.23.0)
**Security fixes:**
- Add a new ResponseStatus for admin operations [\#93](https://github.com/parallaxsecond/parsec-interface-rs/issues/93)
**Closed issues:**
- Add ListClients and DeleteClient structures [\#94](https://github.com/parallaxsecond/parsec-interface-rs/issues/94)
**Merged pull requests:**
- Bump PSA Crypto version [\#96](https://github.com/parallaxsecond/parsec-interface-rs/pull/96) ([ionut-arm](https://github.com/ionut-arm))
- Add ListClients and DeleteClient operations [\#95](https://github.com/parallaxsecond/parsec-interface-rs/pull/95) ([hug-dev](https://github.com/hug-dev))
- Fix lints and remove Travis build [\#92](https://github.com/parallaxsecond/parsec-interface-rs/pull/92) ([ionut-arm](https://github.com/ionut-arm))
## [0.22.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.22.0) (2020-12-18)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.21.0...0.22.0)
**Merged pull requests:**
- Consume psa-crypto at version 0.6.1 and bump interface to 0.22.0 [\#91](https://github.com/parallaxsecond/parsec-interface-rs/pull/91) ([paulhowardarm](https://github.com/paulhowardarm))
- Add CryptoAuthLib to Provider enumeration. [\#90](https://github.com/parallaxsecond/parsec-interface-rs/pull/90) ([RobertDrazkowskiGL](https://github.com/RobertDrazkowskiGL))
- Update psa-crypto version [\#89](https://github.com/parallaxsecond/parsec-interface-rs/pull/89) ([hug-dev](https://github.com/hug-dev))
## [0.21.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.21.0) (2020-10-20)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.20.2...0.21.0)
**Implemented enhancements:**
- Write opcode numbers in hexadecimal format [\#82](https://github.com/parallaxsecond/parsec-interface-rs/issues/82)
- Create conversion method from TryFromIntError for ResponseStatus [\#53](https://github.com/parallaxsecond/parsec-interface-rs/issues/53)
- Add Trusted Services crypto provider ID [\#87](https://github.com/parallaxsecond/parsec-interface-rs/pull/87) ([ionut-arm](https://github.com/ionut-arm))
- Add a JWT SVID authentication type [\#84](https://github.com/parallaxsecond/parsec-interface-rs/pull/84) ([hug-dev](https://github.com/hug-dev))
**Fixed bugs:**
- Fix nightly CI [\#78](https://github.com/parallaxsecond/parsec-interface-rs/pull/78) ([hug-dev](https://github.com/hug-dev))
**Closed issues:**
- Add support for another authenticator [\#70](https://github.com/parallaxsecond/parsec-interface-rs/issues/70)
**Merged pull requests:**
- Add methods to check opcode nature [\#88](https://github.com/parallaxsecond/parsec-interface-rs/pull/88) ([hug-dev](https://github.com/hug-dev))
- Use hexadecimal format for opcode values [\#86](https://github.com/parallaxsecond/parsec-interface-rs/pull/86) ([hug-dev](https://github.com/hug-dev))
- Add a uuid::Error conversion [\#85](https://github.com/parallaxsecond/parsec-interface-rs/pull/85) ([hug-dev](https://github.com/hug-dev))
- Add ListKeys operation [\#83](https://github.com/parallaxsecond/parsec-interface-rs/pull/83) ([joechrisellis](https://github.com/joechrisellis))
## [0.20.2](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.20.2) (2020-09-04)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.20.1...0.20.2)
**Implemented enhancements:**
- Re-export `uuid` crate [\#51](https://github.com/parallaxsecond/parsec-interface-rs/issues/51)
- Upgrade dependencies [\#77](https://github.com/parallaxsecond/parsec-interface-rs/pull/77) ([hug-dev](https://github.com/hug-dev))
**Security fixes:**
- Audit response status code for information disclosure [\#59](https://github.com/parallaxsecond/parsec-interface-rs/issues/59)
## [0.20.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.20.1) (2020-08-20)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.20.0...0.20.1)
## [0.20.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.20.0) (2020-08-14)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.19.0...0.20.0)
**Fixed bugs:**
- Fix clippy warnings [\#67](https://github.com/parallaxsecond/parsec-interface-rs/pull/67) ([ionut-arm](https://github.com/ionut-arm))
**Merged pull requests:**
- Added raw key agreement interface [\#75](https://github.com/parallaxsecond/parsec-interface-rs/pull/75) ([sbailey-arm](https://github.com/sbailey-arm))
- Added hash compute and compare interfaces [\#74](https://github.com/parallaxsecond/parsec-interface-rs/pull/74) ([sbailey-arm](https://github.com/sbailey-arm))
- Added aead encrypt and decrypt [\#73](https://github.com/parallaxsecond/parsec-interface-rs/pull/73) ([sbailey-arm](https://github.com/sbailey-arm))
- Add support for ListAuthenticators operation [\#72](https://github.com/parallaxsecond/parsec-interface-rs/pull/72) ([joechrisellis](https://github.com/joechrisellis))
- Add new AuthType variants [\#71](https://github.com/parallaxsecond/parsec-interface-rs/pull/71) ([joechrisellis](https://github.com/joechrisellis))
- Add support for `psa_generate_random` [\#68](https://github.com/parallaxsecond/parsec-interface-rs/pull/68) ([joechrisellis](https://github.com/joechrisellis))
## [0.19.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.19.0) (2020-07-15)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.18.0...0.19.0)
**Implemented enhancements:**
- Bump version of psa-crypto to 0.3.0 [\#66](https://github.com/parallaxsecond/parsec-interface-rs/pull/66) ([hug-dev](https://github.com/hug-dev))
- Added export key [\#65](https://github.com/parallaxsecond/parsec-interface-rs/pull/65) ([sbailey-arm](https://github.com/sbailey-arm))
**Merged pull requests:**
- Added the from impls for going from an operations and result to NativeOperation and NativeResult for asym encrypt and decrypt [\#64](https://github.com/parallaxsecond/parsec-interface-rs/pull/64) ([sbailey-arm](https://github.com/sbailey-arm))
## [0.18.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.18.0) (2020-07-07)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.17.1...0.18.0)
**Merged pull requests:**
- Added asymmetric encrypt and decrypt [\#63](https://github.com/parallaxsecond/parsec-interface-rs/pull/63) ([sbailey-arm](https://github.com/sbailey-arm))
## [0.17.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.17.1) (2020-07-01)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.17.0...0.17.1)
**Fixed bugs:**
- Fix compilation on testing feature [\#62](https://github.com/parallaxsecond/parsec-interface-rs/pull/62) ([hug-dev](https://github.com/hug-dev))
## [0.17.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.17.0) (2020-06-26)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.16.0...0.17.0)
**Implemented enhancements:**
- Implement DataBuffer and replace byte vectors [\#60](https://github.com/parallaxsecond/parsec-interface-rs/pull/60) ([ionut-arm](https://github.com/ionut-arm))
## [0.16.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.16.0) (2020-06-18)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.15.0...0.16.0)
**Implemented enhancements:**
- Import the newer version of psa-crypto [\#58](https://github.com/parallaxsecond/parsec-interface-rs/pull/58) ([hug-dev](https://github.com/hug-dev))
## [0.15.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.15.0) (2020-06-03)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.14.1...0.15.0)
**Implemented enhancements:**
- Use crates.io for psa-crypto [\#57](https://github.com/parallaxsecond/parsec-interface-rs/pull/57) ([hug-dev](https://github.com/hug-dev))
- Derive PartialEq, Hash and Eq on ProviderInfo [\#54](https://github.com/parallaxsecond/parsec-interface-rs/pull/54) ([ionut-arm](https://github.com/ionut-arm))
**Merged pull requests:**
- Replace algorithms and attributes with psa-crypto [\#55](https://github.com/parallaxsecond/parsec-interface-rs/pull/55) ([ionut-arm](https://github.com/ionut-arm))
## [0.14.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.14.1) (2020-05-11)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.14.0...0.14.1)
**Implemented enhancements:**
- Add validation to sign and verify operations [\#52](https://github.com/parallaxsecond/parsec-interface-rs/pull/52) ([ionut-arm](https://github.com/ionut-arm))
**Fixed bugs:**
- Modify Opcode enumeration size [\#49](https://github.com/parallaxsecond/parsec-interface-rs/issues/49)
- Modify Opcode size [\#50](https://github.com/parallaxsecond/parsec-interface-rs/pull/50) ([hug-dev](https://github.com/hug-dev))
## [0.14.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.14.0) (2020-04-23)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.13.0...0.14.0)
**Implemented enhancements:**
- Breaking change to wire protocol 1.0 to support additional fields and transports [\#48](https://github.com/parallaxsecond/parsec-interface-rs/pull/48) ([paulhowardarm](https://github.com/paulhowardarm))
- Update copyrights on all files [\#46](https://github.com/parallaxsecond/parsec-interface-rs/pull/46) ([hug-dev](https://github.com/hug-dev))
**Fixed bugs:**
- Make wire protocol version a property of request and response headers [\#41](https://github.com/parallaxsecond/parsec-interface-rs/issues/41)
- Make sure there is a clear separation between PSA and Core structures [\#30](https://github.com/parallaxsecond/parsec-interface-rs/issues/30)
## [0.13.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.13.0) (2020-04-15)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.12.0...0.13.0)
**Implemented enhancements:**
- Add body type getter in Convert trait [\#40](https://github.com/parallaxsecond/parsec-interface-rs/issues/40)
- Add provider ID to list\_opcodes [\#44](https://github.com/parallaxsecond/parsec-interface-rs/pull/44) ([ionut-arm](https://github.com/ionut-arm))
- Add body\_type fn to Convert [\#42](https://github.com/parallaxsecond/parsec-interface-rs/pull/42) ([ionut-arm](https://github.com/ionut-arm))
**Merged pull requests:**
- Bump version number [\#45](https://github.com/parallaxsecond/parsec-interface-rs/pull/45) ([ionut-arm](https://github.com/ionut-arm))
## [0.12.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.12.0) (2020-04-07)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.11.0...0.12.0)
**Implemented enhancements:**
- Add faillible methods [\#39](https://github.com/parallaxsecond/parsec-interface-rs/pull/39) ([hug-dev](https://github.com/hug-dev))
- Add a new method for permisison and compatibility [\#38](https://github.com/parallaxsecond/parsec-interface-rs/pull/38) ([hug-dev](https://github.com/hug-dev))
## [0.11.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.11.0) (2020-04-03)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.10.0...0.11.0)
**Implemented enhancements:**
- Add permits method to check for policy [\#37](https://github.com/parallaxsecond/parsec-interface-rs/pull/37) ([hug-dev](https://github.com/hug-dev))
## [0.10.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.10.0) (2020-03-18)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.8.3...0.10.0)
**Implemented enhancements:**
- Update to PSA Crypto API 1.0.0 [\#4](https://github.com/parallaxsecond/parsec-interface-rs/issues/4)
- Update to PSA Crypto API 1.0.0 [\#28](https://github.com/parallaxsecond/parsec-interface-rs/pull/28) ([hug-dev](https://github.com/hug-dev))
**Closed issues:**
- Update documentation after upgrading to PSA Crypto 1.0.0 [\#29](https://github.com/parallaxsecond/parsec-interface-rs/issues/29)
**Merged pull requests:**
- Add missing\_doc as an error [\#31](https://github.com/parallaxsecond/parsec-interface-rs/pull/31) ([hug-dev](https://github.com/hug-dev))
## [0.8.3](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.8.3) (2020-02-28)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.8.2...0.8.3)
**Implemented enhancements:**
- Add code documentation [\#26](https://github.com/parallaxsecond/parsec-interface-rs/pull/26) ([hug-dev](https://github.com/hug-dev))
## [0.8.2](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.8.2) (2020-02-25)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.8.1...0.8.2)
## [0.8.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.8.1) (2020-02-24)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.8.0...0.8.1)
**Fixed bugs:**
- Fix supported wire protocol version [\#24](https://github.com/parallaxsecond/parsec-interface-rs/pull/24) ([hug-dev](https://github.com/hug-dev))
## [0.8.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.8.0) (2020-02-21)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.7.1...0.8.0)
## [0.7.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.7.1) (2020-02-06)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.7.0...0.7.1)
**Implemented enhancements:**
- Add a submodule for the operations [\#21](https://github.com/parallaxsecond/parsec-interface-rs/pull/21) ([hug-dev](https://github.com/hug-dev))
**Fixed bugs:**
- Deploy on crates.io [\#14](https://github.com/parallaxsecond/parsec-interface-rs/issues/14)
## [0.7.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.7.0) (2020-02-05)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.6.1...0.7.0)
**Implemented enhancements:**
- Add Travis CI tests for Aarch64 [\#12](https://github.com/parallaxsecond/parsec-interface-rs/issues/12)
**Fixed bugs:**
- Build fails with confusing message if wget is not available [\#17](https://github.com/parallaxsecond/parsec-interface-rs/issues/17)
- Replace direct `Command` by crates in the build script [\#7](https://github.com/parallaxsecond/parsec-interface-rs/issues/7)
## [0.6.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.6.1) (2020-02-04)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.6.0...0.6.1)
**Implemented enhancements:**
- Various lint fixes [\#18](https://github.com/parallaxsecond/parsec-interface-rs/pull/18) ([hug-dev](https://github.com/hug-dev))
**Fixed bugs:**
- Replace cross tests for native tests [\#19](https://github.com/parallaxsecond/parsec-interface-rs/pull/19) ([hug-dev](https://github.com/hug-dev))
## [0.6.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.6.0) (2020-01-30)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.5.1...0.6.0)
**Fixed bugs:**
- Add body length limit to reading requests and responses [\#16](https://github.com/parallaxsecond/parsec-interface-rs/pull/16) ([ionut-arm](https://github.com/ionut-arm))
## [0.5.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.5.1) (2020-01-28)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.5.0...0.5.1)
**Implemented enhancements:**
- Derive Arbitrary for fuzz testing [\#15](https://github.com/parallaxsecond/parsec-interface-rs/pull/15) ([ionut-arm](https://github.com/ionut-arm))
## [0.5.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.5.0) (2020-01-27)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.4.1...0.5.0)
**Implemented enhancements:**
- Remove most panicking behaviour [\#13](https://github.com/parallaxsecond/parsec-interface-rs/pull/13) ([hug-dev](https://github.com/hug-dev))
## [0.4.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.4.1) (2020-01-09)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.4.0...0.4.1)
**Implemented enhancements:**
- Deny compilation for some rustc lints [\#11](https://github.com/parallaxsecond/parsec-interface-rs/pull/11) ([hug-dev](https://github.com/hug-dev))
## [0.4.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.4.0) (2019-12-05)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.3.0...0.4.0)
**Implemented enhancements:**
- Add TPM Provider [\#9](https://github.com/parallaxsecond/parsec-interface-rs/pull/9) ([hug-dev](https://github.com/hug-dev))
## [0.3.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.3.0) (2019-11-18)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.2.1...0.3.0)
**Implemented enhancements:**
- Add PKCS 11 ProviderID enumeration variant [\#8](https://github.com/parallaxsecond/parsec-interface-rs/pull/8) ([hug-dev](https://github.com/hug-dev))
## [0.2.1](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.2.1) (2019-11-01)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.2.0...0.2.1)
**Implemented enhancements:**
- Add cross-compilation and testing to Arm64 on CI [\#6](https://github.com/parallaxsecond/parsec-interface-rs/pull/6) ([hug-dev](https://github.com/hug-dev))
## [0.2.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.2.0) (2019-10-23)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/0.1.0...0.2.0)
**Merged pull requests:**
- Remove references to key lifetime [\#5](https://github.com/parallaxsecond/parsec-interface-rs/pull/5) ([hug-dev](https://github.com/hug-dev))
- Remove ci folder and modify CI workflow [\#3](https://github.com/parallaxsecond/parsec-interface-rs/pull/3) ([hug-dev](https://github.com/hug-dev))
## [0.1.0](https://github.com/parallaxsecond/parsec-interface-rs/tree/0.1.0) (2019-10-09)
[Full Changelog](https://github.com/parallaxsecond/parsec-interface-rs/compare/c89c06232024d57d96826b41ea4d409a021fd530...0.1.0)
**Merged pull requests:**
- Add a specific tag when getting operations [\#2](https://github.com/parallaxsecond/parsec-interface-rs/pull/2) ([hug-dev](https://github.com/hug-dev))
- Split Rust interface into its own repository [\#1](https://github.com/parallaxsecond/parsec-interface-rs/pull/1) ([hug-dev](https://github.com/hug-dev))
\* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)*
parsec-interface-0.29.1/Cargo.toml 0000644 00000003301 00000000001 0012333 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
rust-version = "1.66.0"
name = "parsec-interface"
version = "0.29.1"
authors = ["Parsec Project Contributors"]
description = "Parsec interface library to communicate using the wire protocol"
readme = "README.md"
keywords = [
"parsec",
"interface",
"serialization",
]
categories = ["encoding"]
license = "Apache-2.0"
repository = "https://github.com/parallaxsecond/parsec-interface-rs"
[dependencies.arbitrary]
version = "0.4.6"
features = ["derive"]
optional = true
[dependencies.bincode]
version = "1.3.1"
[dependencies.derivative]
version = "2.1.1"
[dependencies.log]
version = "0.4.11"
[dependencies.num]
version = "0.4.0"
[dependencies.num-derive]
version = "0.4.0"
[dependencies.num-traits]
version = "0.2.12"
[dependencies.prost]
version = "0.9.0"
[dependencies.psa-crypto]
version = "0.12.0"
default-features = false
[dependencies.secrecy]
version = "0.8.0"
features = ["serde"]
[dependencies.serde]
version = "1.0.115"
features = ["derive"]
[dependencies.uuid]
version = "0.8.1"
[dependencies.zeroize]
version = "1.1.0"
features = ["zeroize_derive"]
[build-dependencies.prost-build]
version = "0.9.0"
optional = true
[features]
fuzz = ["arbitrary"]
regenerate-protobuf = ["prost-build"]
testing = []
parsec-interface-0.29.1/Cargo.toml.orig 0000644 0000000 0000000 00000002012 10461020230 0016012 0 ustar 0000000 0000000 [package]
name = "parsec-interface"
version = "0.29.1"
authors = ["Parsec Project Contributors"]
description = "Parsec interface library to communicate using the wire protocol"
license = "Apache-2.0"
repository = "https://github.com/parallaxsecond/parsec-interface-rs"
readme = "README.md"
keywords = ["parsec", "interface", "serialization"]
categories = ["encoding"]
edition = "2018"
rust-version = "1.66.0"
[build-dependencies]
prost-build = { version = "0.9.0", optional = true }
[dependencies]
serde = { version = "1.0.115", features = ["derive"] }
bincode = "1.3.1"
num-traits = "0.2.12"
num-derive = "0.4.0"
num = "0.4.0"
prost = "0.9.0"
arbitrary = { version = "0.4.6", features = ["derive"], optional = true }
uuid = "0.8.1"
log = "0.4.11"
psa-crypto = { version = "0.12.0", default-features = false }
zeroize = { version = "1.1.0", features = ["zeroize_derive"] }
secrecy = { version = "0.8.0", features = ["serde"] }
derivative = "2.1.1"
[features]
testing = []
fuzz = ["arbitrary"]
regenerate-protobuf = ["prost-build"]
parsec-interface-0.29.1/LICENSE 0000644 0000000 0000000 00000026136 10461020230 0014145 0 ustar 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
parsec-interface-0.29.1/MAINTAINERS.toml 0000644 0000000 0000000 00000002417 10461020230 0015603 0 ustar 0000000 0000000 # parsec-interface-rs maintainers file
#
# This file lists the maintainers of the parallaxsecond/parsec-interface-rs
# project.
#
# Its structure is inspired from the maintainers files in the Docker Github
# repositories. Please see the MAINTAINERS file in docker/opensource for more
# information.
[maintainers]
# Core maintainers of the project.
[maintainers.core]
people = [
"adamparco",
"heavypackets",
"hug-dev",
"ionut-arm",
"justincormack",
"paulhowardarm",
]
[people]
# A reference list of all people associated with the project.
[people.adamparco]
Name = "Adam Parco"
Email = "adam.parco@docker.com"
GitHub = "adamparco"
[people.heavypackets]
Name = "Sabree Blackmon"
Email = "sabree.blackmon@docker.com"
GitHub = "heavypackets"
[people.hug-dev]
Name = "Hugues de Valon"
Email = "hugues.devalon@arm.com"
GitHub = "hug-dev"
[people.ionut-arm]
Name = "Ionut Mihalcea"
Email = "ionut.mihalcea@docker.com"
GitHub = "ionut-arm"
[people.justincormack]
Name = "Justin Cormack"
Email = "justin.cormack@docker.com"
GitHub = "justincormack"
[people.paulhowardarm]
Name = "Paul Howard"
Email = "paul.howard@arm.com"
GitHub = "paulhowardarm"
parsec-interface-0.29.1/README.md 0000644 0000000 0000000 00000002563 10461020230 0014415 0 ustar 0000000 0000000 # Parsec Rust Interface
This repository contains an interface library to be used both by the Parsec service and a Rust Client library.
The library contains methods to communicate using the [wire protocol](https://parallaxsecond.github.io/parsec-book/parsec_client/wire_protocol.html).
## Build
The Parsec operations repository is included as a submodule. Make sure to update it first before
trying to compile otherwise it will not work ("`No such file or directory`").
```bash
$ git submodule update --init
```
By default, the crate will use the pre-generated Rust Protobuf files in
`src/operations_protobuf/generated_ops`. To re-generate them from the `parsec-operations`
submodule, compile this
crate with the feature `regenerate-protobuf`.
## License
The software is provided under Apache-2.0. Contributions to this project are accepted under the same license.
## Contributing
Please check the [**Contribution Guidelines**](https://parallaxsecond.github.io/parsec-book/contributing/index.html)
to know more about the contribution process.
*Copyright 2021 Contributors to the Parsec project.*
parsec-interface-0.29.1/build.rs 0000644 0000000 0000000 00000003675 10461020230 0014610 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
// This one is hard to avoid.
#![allow(clippy::multiple_crate_versions)]
use std::io::Result;
// Replace the committed protobuf files with the generated one.
#[cfg(feature = "regenerate-protobuf")]
fn generate_proto_sources() -> Result<()> {
use std::fs::read_dir;
use std::io::{Error, ErrorKind};
use std::path::Path;
use std::process::Command;
let path = String::from("parsec-operations/protobuf");
let dir_entries = read_dir(Path::new(&path))?;
let files: Result> = dir_entries
.map(|protos_file| {
protos_file?
.path()
.into_os_string()
.into_string()
.map_err(|_| {
Error::new(
ErrorKind::InvalidData,
"conversion from OsString to String failed",
)
})
})
// Fail the entire operation if there was an error.
.collect();
let proto_files: Vec = files?
.into_iter()
.filter(|string| string.ends_with(".proto"))
.collect();
let files_slices: Vec<&str> = proto_files.iter().map(|file| &file[..]).collect();
prost_build::compile_protos(&files_slices, &[&path])?;
// Copy all files generated in src/operations_protobuf/generated_ops
let status = Command::new("bash")
.arg("-c")
.arg(format!(
"cp {}/*.rs src/operations_protobuf/generated_ops",
std::env::var("OUT_DIR").expect("OUT_DIR env var is empty")
))
.status()?;
if !status.success() {
Err(Error::new(
ErrorKind::InvalidData,
"failed copying generated protobuf files",
))
} else {
Ok(())
}
}
fn main() -> Result<()> {
#[cfg(feature = "regenerate-protobuf")]
generate_proto_sources()?;
Ok(())
}
parsec-interface-0.29.1/parsec-operations/.github/workflows/ci.yml 0000644 0000000 0000000 00000001572 10461020230 0023306 0 ustar 0000000 0000000 name: Continuous Integration
on: [push, pull_request]
jobs:
format:
name: Check formatting
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install clang-format
run: |
sudo apt update
# This is needed because of a bug, see microsoft/azure-pipelines-image-generation#672
sudo apt-get remove -y clang-6.0 libclang-common-6.0-dev libclang1-6.0 libllvm6.0
sudo apt-get autoremove
sudo apt install clang-format
- name: Check formatting using clang-format
run: ./ci/check_format.sh
build:
name: Build tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install protoc
run: |
sudo apt update
sudo apt install protobuf-compiler
- name: Check that the protobuf files compile using protoc
run: ./ci/check_build.sh
parsec-interface-0.29.1/parsec-operations/.gitignore 0000644 0000000 0000000 00000000010 10461020230 0020545 0 ustar 0000000 0000000 *.patch
parsec-interface-0.29.1/parsec-operations/LICENSE 0000644 0000000 0000000 00000026136 10461020230 0017603 0 ustar 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
parsec-interface-0.29.1/parsec-operations/MAINTAINERS.toml 0000644 0000000 0000000 00000002612 10461020230 0021236 0 ustar 0000000 0000000 # parsec-operations maintainers file
#
# This file lists the maintainers of the parallaxsecond/parsec-operations
# project.
#
# Its structure is inspired from the maintainers files in the Docker Github
# repositories. Please see the MAINTAINERS file in docker/opensource for more
# information.
[maintainers]
# Core maintainers of the project.
[maintainers.core]
people = [
"adamparco",
"anta5010",
"heavypackets",
"hug-dev",
"ionut-arm",
"justincormack",
"paulhowardarm",
]
[people]
# A reference list of all people associated with the project.
[people.adamparco]
Name = "Adam Parco"
Email = "adam.parco@docker.com"
GitHub = "adamparco"
[people.anta5010]
Name = "Anton Antonov"
Email = "anton.antonov@arm.com"
GitHub = "anta5010"
[people.heavypackets]
Name = "Sabree Blackmon"
Email = "sabree.blackmon@docker.com"
GitHub = "heavypackets"
[people.hug-dev]
Name = "Hugues de Valon"
Email = "hugues.devalon@arm.com"
GitHub = "hug-dev"
[people.ionut-arm]
Name = "Ionut Mihalcea"
Email = "ionut.mihalcea@docker.com"
GitHub = "ionut-arm"
[people.justincormack]
Name = "Justin Cormack"
Email = "justin.cormack@docker.com"
GitHub = "justincormack"
[people.paulhowardarm]
Name = "Paul Howard"
Email = "paul.howard@arm.com"
GitHub = "paulhowardarm"
parsec-interface-0.29.1/parsec-operations/README.md 0000644 0000000 0000000 00000002245 10461020230 0020050 0 ustar 0000000 0000000
# Parsec Language Neutral Operations

This repository provides a centralised access for all Parsec operations.
Client libraries can download and compile the operations of this repository to the programming language that they use.
Please check the [operations document](https://parallaxsecond.github.io/parsec-book/parsec_client/operations/index.html)
for more information on operations.
# License
The software is provided under Apache-2.0. Contributions to this project are accepted under the same license.
# User Guide
In order to make a Parsec client library, you will need to add in the build script of your library the needed operations
to clone this git repository and then compile the operations into functions to convert between your language native
memory structures and the operations format.
# Contributing
Please check the [**Contribution Guidelines**](https://parallaxsecond.github.io/parsec-book/contributing.html)
to know more about the contribution process.
parsec-interface-0.29.1/parsec-operations/ci/check_build.sh 0000755 0000000 0000000 00000000573 10461020230 0021761 0 ustar 0000000 0000000 #!/usr/bin/env bash
# Copyright 2020 Contributors to the Parsec project.
# SPDX-License-Identifier: Apache-2.0
set -e
OUT_DIR="/tmp/parsec-operations-ci"
mkdir -p $OUT_DIR
# Check that protoc can build the protobuf files.
mkdir -p $OUT_DIR/protobuf
PROTOBUF_FILES=protobuf/*.proto
for f in $PROTOBUF_FILES
do
protoc --proto_path=protobuf --cpp_out=$OUT_DIR/protobuf $f
done
parsec-interface-0.29.1/parsec-operations/ci/check_format.sh 0000755 0000000 0000000 00000000673 10461020230 0022153 0 ustar 0000000 0000000 #!/usr/bin/env bash
# Copyright 2020 Contributors to the Parsec project.
# SPDX-License-Identifier: Apache-2.0
set -e
# Check the git diff between the clang-formatted file and the actual file to
# make sure they match.
OUT_DIR="/tmp/parsec-operations-ci"
mkdir -p $OUT_DIR
# protobuf tests
mkdir -p $OUT_DIR/protobuf
PROTOBUF_FILES=protobuf/*.proto
for f in $PROTOBUF_FILES
do
clang-format $f > $OUT_DIR/$f
git diff $f $OUT_DIR/$f
done
parsec-interface-0.29.1/parsec-operations/protobuf/delete_client.proto 0000644 0000000 0000000 00000000314 10461020230 0024311 0 ustar 0000000 0000000 /*
* Copyright 2021 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package delete_client;
message Operation { string client = 1; }
message Result {}
parsec-interface-0.29.1/parsec-operations/protobuf/list_authenticators.proto 0000644 0000000 0000000 00000000606 10461020230 0025605 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package list_authenticators;
message AuthenticatorInfo {
string description = 1;
uint32 version_maj = 2;
uint32 version_min = 3;
uint32 version_rev = 4;
uint32 id = 5;
}
message Operation {}
message Result { repeated AuthenticatorInfo authenticators = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/list_clients.proto 0000644 0000000 0000000 00000000325 10461020230 0024207 0 ustar 0000000 0000000 /*
* Copyright 2021 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package list_clients;
message Operation {}
message Result { repeated string clients = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/list_keys.proto 0000644 0000000 0000000 00000000551 10461020230 0023522 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package list_keys;
import "psa_key_attributes.proto";
message KeyInfo {
uint32 provider_id = 1;
string name = 2;
psa_key_attributes.KeyAttributes attributes = 3;
}
message Operation {}
message Result { repeated KeyInfo keys = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/list_opcodes.proto 0000644 0000000 0000000 00000000405 10461020230 0024201 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package list_opcodes;
message Operation { uint32 provider_id = 1; } // Cast down to 8 bits
message Result { repeated uint32 opcodes = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/list_providers.proto 0000644 0000000 0000000 00000000632 10461020230 0024564 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package list_providers;
message ProviderInfo {
string uuid = 1;
string description = 2;
string vendor = 3;
uint32 version_maj = 4;
uint32 version_min = 5;
uint32 version_rev = 6;
uint32 id = 7;
}
message Operation {}
message Result { repeated ProviderInfo providers = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/ping.proto 0000644 0000000 0000000 00000000456 10461020230 0022455 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package ping;
message Operation {}
message Result {
uint32 wire_protocol_version_maj = 1; // Cast down to 8 bits
uint32 wire_protocol_version_min = 2; // Cast down to 8 bits
}
parsec-interface-0.29.1/parsec-operations/protobuf/psa_aead_decrypt.proto 0000644 0000000 0000000 00000000567 10461020230 0025012 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_aead_decrypt;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.Aead alg = 2;
bytes nonce = 3;
bytes additional_data = 4;
bytes ciphertext = 5;
}
message Result { bytes plaintext = 1; } parsec-interface-0.29.1/parsec-operations/protobuf/psa_aead_encrypt.proto 0000644 0000000 0000000 00000000567 10461020230 0025024 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_aead_encrypt;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.Aead alg = 2;
bytes nonce = 3;
bytes additional_data = 4;
bytes plaintext = 5;
}
message Result { bytes ciphertext = 1; } parsec-interface-0.29.1/parsec-operations/protobuf/psa_algorithm.proto 0000644 0000000 0000000 00000006742 10461020230 0024355 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_algorithm;
message Algorithm {
message None {}
enum Hash {
HASH_NONE = 0; // This default variant should not be used.
MD2 = 1 [ deprecated = true ];
MD4 = 2 [ deprecated = true ];
MD5 = 3 [ deprecated = true ];
RIPEMD160 = 4;
SHA_1 = 5 [ deprecated = true ];
SHA_224 = 6;
SHA_256 = 7;
SHA_384 = 8;
SHA_512 = 9;
SHA_512_224 = 10;
SHA_512_256 = 11;
SHA3_224 = 12;
SHA3_256 = 13;
SHA3_384 = 14;
SHA3_512 = 15;
}
message Mac {
message FullLength {
message Hmac { Hash hash_alg = 1; }
message CbcMac {}
message Cmac {}
oneof variant {
Hmac hmac = 1;
CbcMac cbc_mac = 2;
Cmac cmac = 3;
}
}
message Truncated {
FullLength mac_alg = 1;
uint32 mac_length = 2;
}
oneof variant {
FullLength full_length = 1;
Truncated truncated = 2;
}
}
enum Cipher {
CIPHER_NONE = 0; // This default variant should not be used.
STREAM_CIPHER = 1;
CTR = 2;
CFB = 3;
OFB = 4;
XTS = 5;
ECB_NO_PADDING = 6;
CBC_NO_PADDING = 7;
CBC_PKCS7 = 8;
}
message Aead {
enum AeadWithDefaultLengthTag {
AEAD_WITH_DEFAULT_LENGTH_TAG_NONE =
0; // This default variant should not be used.
CCM = 1;
GCM = 2;
CHACHA20_POLY1305 = 3;
}
message AeadWithShortenedTag {
AeadWithDefaultLengthTag aead_alg = 1;
uint32 tag_length = 2;
}
oneof variant {
AeadWithDefaultLengthTag aead_with_default_length_tag = 1;
AeadWithShortenedTag aead_with_shortened_tag = 2;
}
}
message AsymmetricSignature {
message SignHash {
message Any {}
oneof variant {
Any any = 1;
Hash specific = 2;
}
}
message RsaPkcs1v15Sign { SignHash hash_alg = 1; }
message RsaPkcs1v15SignRaw {}
message RsaPss { SignHash hash_alg = 1; }
message Ecdsa { SignHash hash_alg = 1; }
message EcdsaAny {}
message DeterministicEcdsa { SignHash hash_alg = 1; }
oneof variant {
RsaPkcs1v15Sign rsa_pkcs1v15_sign = 1;
RsaPkcs1v15SignRaw rsa_pkcs1v15_sign_raw = 2;
RsaPss rsa_pss = 3;
Ecdsa ecdsa = 4;
EcdsaAny ecdsa_any = 5;
DeterministicEcdsa deterministic_ecdsa = 6;
}
}
message AsymmetricEncryption {
message RsaPkcs1v15Crypt {}
message RsaOaep { Hash hash_alg = 1; }
oneof variant {
RsaPkcs1v15Crypt rsa_pkcs1v15_crypt = 1;
RsaOaep rsa_oaep = 2;
}
}
message KeyAgreement {
enum Raw {
RAW_NONE = 0; // This default variant should not be used.
FFDH = 1;
ECDH = 2;
}
message WithKeyDerivation {
Raw ka_alg = 1;
KeyDerivation kdf_alg = 2;
}
oneof variant {
Raw raw = 1;
WithKeyDerivation with_key_derivation = 2;
}
}
message KeyDerivation {
message Hkdf { Hash hash_alg = 1; }
message Tls12Prf { Hash hash_alg = 1; }
message Tls12PskToMs { Hash hash_alg = 1; }
oneof variant {
Hkdf hkdf = 1;
Tls12Prf tls12_prf = 2;
Tls12PskToMs tls12_psk_to_ms = 3;
}
}
oneof variant {
None none = 1;
Hash hash = 2;
Mac mac = 3;
Cipher cipher = 4;
Aead aead = 5;
AsymmetricSignature asymmetric_signature = 6;
AsymmetricEncryption asymmetric_encryption = 7;
KeyAgreement key_agreement = 8;
KeyDerivation key_derivation = 9;
}
}
parsec-interface-0.29.1/parsec-operations/protobuf/psa_asymmetric_decrypt.proto 0000644 0000000 0000000 00000000557 10461020230 0026274 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_asymmetric_decrypt;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.AsymmetricEncryption alg = 2;
bytes ciphertext = 3;
bytes salt = 4;
}
message Result { bytes plaintext = 1; } parsec-interface-0.29.1/parsec-operations/protobuf/psa_asymmetric_encrypt.proto 0000644 0000000 0000000 00000000557 10461020230 0026306 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_asymmetric_encrypt;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.AsymmetricEncryption alg = 2;
bytes plaintext = 3;
bytes salt = 4;
}
message Result { bytes ciphertext = 1; } parsec-interface-0.29.1/parsec-operations/protobuf/psa_cipher_decrypt.proto 0000644 0000000 0000000 00000000513 10461020230 0025361 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_cipher_decrypt;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.Cipher alg = 2;
bytes ciphertext = 3;
}
message Result { bytes plaintext = 1; } parsec-interface-0.29.1/parsec-operations/protobuf/psa_cipher_encrypt.proto 0000644 0000000 0000000 00000000513 10461020230 0025373 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_cipher_encrypt;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.Cipher alg = 2;
bytes plaintext = 3;
}
message Result { bytes ciphertext = 1; } parsec-interface-0.29.1/parsec-operations/protobuf/psa_destroy_key.proto 0000644 0000000 0000000 00000000320 10461020230 0024712 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_destroy_key;
message Operation { string key_name = 1; }
message Result {}
parsec-interface-0.29.1/parsec-operations/protobuf/psa_export_key.proto 0000644 0000000 0000000 00000000340 10461020230 0024544 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_export_key;
message Operation { string key_name = 1; }
message Result { bytes data = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/psa_export_public_key.proto 0000644 0000000 0000000 00000000347 10461020230 0026111 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_export_public_key;
message Operation { string key_name = 1; }
message Result { bytes data = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/psa_generate_key.proto 0000644 0000000 0000000 00000000452 10461020230 0025021 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_generate_key;
import "psa_key_attributes.proto";
message Operation {
string key_name = 1;
psa_key_attributes.KeyAttributes attributes = 2;
}
message Result {}
parsec-interface-0.29.1/parsec-operations/protobuf/psa_generate_random.proto 0000644 0000000 0000000 00000000351 10461020230 0025507 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_generate_random;
message Operation { uint64 size = 1; }
message Result { bytes random_bytes = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/psa_hash_compare.proto 0000644 0000000 0000000 00000000450 10461020230 0025006 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_hash_compare;
import "psa_algorithm.proto";
message Operation {
psa_algorithm.Algorithm.Hash alg = 1;
bytes input = 2;
bytes hash = 3;
}
message Result {}
parsec-interface-0.29.1/parsec-operations/protobuf/psa_hash_compute.proto 0000644 0000000 0000000 00000000447 10461020230 0025042 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_hash_compute;
import "psa_algorithm.proto";
message Operation {
psa_algorithm.Algorithm.Hash alg = 1;
bytes input = 2;
}
message Result { bytes hash = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/psa_import_key.proto 0000644 0000000 0000000 00000000472 10461020230 0024543 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_import_key;
import "psa_key_attributes.proto";
message Operation {
string key_name = 1;
psa_key_attributes.KeyAttributes attributes = 2;
bytes data = 3;
}
message Result {}
parsec-interface-0.29.1/parsec-operations/protobuf/psa_key_attributes.proto 0000644 0000000 0000000 00000004003 10461020230 0025411 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_key_attributes;
import "psa_algorithm.proto";
message KeyAttributes {
KeyType key_type = 1;
uint32 key_bits = 2;
KeyPolicy key_policy = 3;
}
message KeyType {
message RawData {}
message Hmac {}
message Derive {}
message Aes {}
message Des {}
message Camellia {}
message Arc4 {}
message Chacha20 {}
message RsaPublicKey {}
message RsaKeyPair {}
message EccKeyPair { EccFamily curve_family = 1; }
message EccPublicKey { EccFamily curve_family = 1; }
message DhKeyPair { DhFamily group_family = 1; }
message DhPublicKey { DhFamily group_family = 1; }
enum EccFamily {
ECC_FAMILY_NONE = 0; // This default variant should not be used.
SECP_K1 = 1;
SECP_R1 = 2;
SECP_R2 = 3 [ deprecated = true ];
SECT_K1 = 4; // DEPRECATED for sect163k1 curve
SECT_R1 = 5; // DEPRECATED for sect163r1 curve
SECT_R2 = 6 [ deprecated = true ];
BRAINPOOL_P_R1 = 7; // DEPRECATED for brainpoolP160r1 curve
FRP = 8;
MONTGOMERY = 9;
}
enum DhFamily { RFC7919 = 0; }
oneof variant {
RawData raw_data = 1;
// Symmetric keys
Hmac hmac = 2;
Derive derive = 3;
Aes aes = 4;
Des des = 5 [ deprecated = true ];
Camellia camellia = 6;
Arc4 arc4 = 7 [ deprecated = true ];
Chacha20 chacha20 = 8;
// RSA keys
RsaPublicKey rsa_public_key = 9;
RsaKeyPair rsa_key_pair = 10;
// Elliptic Curve keys
EccKeyPair ecc_key_pair = 11;
EccPublicKey ecc_public_key = 12;
// Finite Field Diffie Hellman keys
DhKeyPair dh_key_pair = 13;
DhPublicKey dh_public_key = 14;
}
}
message KeyPolicy {
UsageFlags key_usage_flags = 1;
psa_algorithm.Algorithm key_algorithm = 2;
}
message UsageFlags {
bool export = 1;
bool copy = 2;
bool cache = 3;
bool encrypt = 4;
bool decrypt = 5;
bool sign_message = 6;
bool verify_message = 7;
bool sign_hash = 8;
bool verify_hash = 9;
bool derive = 10;
}
parsec-interface-0.29.1/parsec-operations/protobuf/psa_mac_compute.proto 0000644 0000000 0000000 00000000473 10461020230 0024656 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_mac_compute;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.Mac alg = 2;
bytes input = 3;
}
message Result { bytes mac = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/psa_mac_verify.proto 0000644 0000000 0000000 00000000473 10461020230 0024506 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_mac_verify;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.Mac alg = 2;
bytes input = 3;
bytes mac = 4;
}
message Result {}
parsec-interface-0.29.1/parsec-operations/protobuf/psa_raw_key_agreement.proto 0000644 0000000 0000000 00000000543 10461020230 0026050 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_raw_key_agreement;
import "psa_algorithm.proto";
message Operation {
psa_algorithm.Algorithm.KeyAgreement.Raw alg = 1;
string private_key_name = 2;
bytes peer_key = 3;
}
message Result { bytes shared_secret = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/psa_sign_hash.proto 0000644 0000000 0000000 00000000516 10461020230 0024323 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_sign_hash;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.AsymmetricSignature alg = 2;
bytes hash = 3;
}
message Result { bytes signature = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/psa_sign_message.proto 0000644 0000000 0000000 00000000524 10461020230 0025023 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_sign_message;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.AsymmetricSignature alg = 2;
bytes message = 3;
}
message Result { bytes signature = 1; }
parsec-interface-0.29.1/parsec-operations/protobuf/psa_verify_hash.proto 0000644 0000000 0000000 00000000521 10461020230 0024663 0 ustar 0000000 0000000 /*
* Copyright 2019 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_verify_hash;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.AsymmetricSignature alg = 2;
bytes hash = 3;
bytes signature = 4;
}
message Result {}
parsec-interface-0.29.1/parsec-operations/protobuf/psa_verify_message.proto 0000644 0000000 0000000 00000000527 10461020230 0025372 0 ustar 0000000 0000000 /*
* Copyright 2020 Contributors to the Parsec project.
* SPDX-License-Identifier: Apache-2.0
*/
syntax = "proto3";
package psa_verify_message;
import "psa_algorithm.proto";
message Operation {
string key_name = 1;
psa_algorithm.Algorithm.AsymmetricSignature alg = 2;
bytes message = 3;
bytes signature = 4;
}
message Result {}
parsec-interface-0.29.1/rustfmt.toml 0000644 0000000 0000000 00000000141 10461020230 0015525 0 ustar 0000000 0000000 # The utils module has to be declared before to make its macros visible.
reorder_modules = false
parsec-interface-0.29.1/src/lib.rs 0000644 0000000 0000000 00000017102 10461020230 0015034 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
#![deny(
nonstandard_style,
dead_code,
improper_ctypes,
non_shorthand_field_patterns,
no_mangle_generic_items,
overflowing_literals,
path_statements,
patterns_in_fns_without_body,
private_in_public,
unconditional_recursion,
unused,
unused_allocation,
unused_comparisons,
unused_parens,
while_true,
missing_debug_implementations,
missing_docs,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results,
missing_copy_implementations
)]
// This one is hard to avoid.
#![allow(clippy::multiple_crate_versions)]
// This crate declares deprecated values for legacy reasons.
#![allow(deprecated)]
//! # Parsec Rust Interface
//!
//! The Parsec Rust Interface provides methods to communicate easily with the Parsec service using
//! the [wire protocol](https://github.com/docker/parsec/blob/master/docs/wire_protocol.md) and the
//! [operation
//! contracts](https://parallaxsecond.github.io/parsec-book/parsec_client/operations/index.html).
//!
//! ## For the Parsec service
//!
//! This library is used by the Parsec service to:
//! * read from a stream a `Request` sent to the service with the `read_from_stream` method
//! * use the `body_to_operation` method of the `Convert` trait on a converter to parse the request
//! body into a `NativeOperation`
//!
//!```
//!# use std::io::Read;
//!#
//!# pub struct MockRead {
//!# pub buffer: Vec,
//!# }
//!#
//!# impl Read for MockRead {
//!# fn read(&mut self, buf: &mut [u8]) -> std::io::Result {
//!# for val in buf.iter_mut() {
//!# *val = self.buffer.remove(0);
//!# }
//!#
//!# Ok(buf.len())
//!# }
//!# }
//!#
//!# let mut stream = MockRead {
//!# buffer: vec![
//!# 0x10, 0xA7, 0xC0, 0x5E, 0x1e, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
//!# 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x1, 0x0, 0x0,
//!# 0x0, 0x0, 0x0, 0x0, 0x0, 0x72, 0x6F, 0x6F, 0x74
//!# ]
//!# };
//!use parsec_interface::operations::{Convert, NativeOperation};
//!use parsec_interface::requests::Request;
//!use parsec_interface::operations_protobuf::ProtobufConverter;
//!
//!let converter = ProtobufConverter {};
//!// stream is a Read object
//!let request = Request::read_from_stream(&mut stream, 2048).unwrap();
//!let operation: NativeOperation = converter
//! .body_to_operation(request.body, request.header.opcode)
//! .unwrap();
//!```
//!
//! The service can now execute the operation to yield a `NativeResult` and:
//! * use the `result_to_body` method to serialize the `NativeResult`
//! * create a `Response` containing the result as its body and write it back to the stream with
//! the `write_to_stream` method.
//!
//!```
//!# use std::io::Write;
//!#
//!# pub struct MockWrite {
//!# pub buffer: Vec,
//!# }
//!#
//!# impl Write for MockWrite {
//!# fn write(&mut self, buf: &[u8]) -> std::io::Result {
//!# for val in buf.iter() {
//!# self.buffer.push(*val);
//!# }
//!# Ok(buf.len())
//!# }
//!#
//!# fn flush(&mut self) -> std::io::Result<()> {
//!# Ok(())
//!# }
//!# }
//!# let mut stream = MockWrite { buffer: Vec::new() };
//!use parsec_interface::operations::{Convert, NativeResult, psa_generate_key::Result};
//!use parsec_interface::requests::{ProviderId, Opcode, BodyType, Response, ResponseStatus};
//!use parsec_interface::requests::response::ResponseHeader;
//!use parsec_interface::operations_protobuf::ProtobufConverter;
//!
//!let converter = ProtobufConverter {};
//!let result = NativeResult::PsaGenerateKey(Result {});
//!let result_body = converter.result_to_body(result).unwrap();
//!let response = Response {
//! header: ResponseHeader {
//! provider: ProviderId::MbedCrypto,
//! session: 0,
//! content_type: BodyType::Protobuf,
//! opcode: Opcode::PsaGenerateKey,
//! status: ResponseStatus::Success,
//! },
//! body: result_body,
//!};
//!// stream is a Write object
//!response.write_to_stream(&mut stream).unwrap();
//!```
//!
//! ## For the Parsec Rust clients
//!
//! This library is used by the Parsec Rust clients to:
//! * use the `operation_to_body` method to serialize the `NativeOperation` to be sent as body of a
//! `Request`
//! * write it to the stream with the `write_to_stream` method.
//!
//!```
//!# use std::io::Write;
//!#
//!# pub struct MockWrite {
//!# pub buffer: Vec,
//!# }
//!#
//!# impl Write for MockWrite {
//!# fn write(&mut self, buf: &[u8]) -> std::io::Result {
//!# for val in buf.iter() {
//!# self.buffer.push(*val);
//!# }
//!# Ok(buf.len())
//!# }
//!# fn flush(&mut self) -> std::io::Result<()> {
//!# Ok(())
//!# }
//!# }
//!#
//!# let mut stream = MockWrite { buffer: Vec::new() };
//!use parsec_interface::operations::{Convert, NativeOperation};
//!use parsec_interface::requests::{Request, ProviderId, BodyType, AuthType, Opcode};
//!use parsec_interface::requests::request::{RequestHeader, RequestAuth};
//!use parsec_interface::operations_protobuf::ProtobufConverter;
//!use parsec_interface::operations::ping::Operation;
//!
//!let converter = ProtobufConverter {};
//!let operation = NativeOperation::Ping(Operation {});
//!let request = Request {
//! header: RequestHeader {
//! provider: ProviderId::Core,
//! session: 0,
//! content_type: BodyType::Protobuf,
//! accept_type: BodyType::Protobuf,
//! auth_type: AuthType::Direct,
//! opcode: Opcode::Ping,
//! },
//! body: converter.operation_to_body(operation).unwrap(),
//! auth: RequestAuth::new(Vec::from("root")),
//!};
//!// stream is a Write object
//!request.write_to_stream(&mut stream).unwrap();
//!```
//!
//! After the operation has been executed by the Parsec service:
//! * read from a stream the `Response` from the service with the `read_from_stream` method
//! * use the `body_to_result` method to parse the result body into a `NativeResult`
//!
//!```
//!# use std::io::Read;
//!#
//!# pub struct MockRead {
//!# pub buffer: Vec,
//!# }
//!#
//!# impl Read for MockRead {
//!# fn read(&mut self, buf: &mut [u8]) -> std::io::Result {
//!# for val in buf.iter_mut() {
//!# *val = self.buffer.remove(0);
//!# }
//!#
//!# Ok(buf.len())
//!# }
//!# }
//!#
//!# let mut stream = MockRead {
//!# buffer: vec![
//!# 0x10, 0xA7, 0xC0, 0x5E, 0x1e, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0,
//!# 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0,
//!# 0x0, 0x0, 0x0, 0x0
//!# ]
//!# };
//!use parsec_interface::operations::{Convert, NativeResult};
//!use parsec_interface::requests::Response;
//!use parsec_interface::operations_protobuf::ProtobufConverter;
//!
//!let converter = ProtobufConverter {};
//!// stream is a Read object
//!let response = Response::read_from_stream(&mut stream, 2048).unwrap();
//!let result: NativeResult = converter
//! .body_to_result(response.body, response.header.opcode)
//! .unwrap();
//!```
//!
//! See the [Parsec Test client](https://github.com/parallaxsecond/parsec-client-test) as an example
//! of a Rust client.
pub mod operations;
pub mod operations_protobuf;
pub mod requests;
/// Module providing access to secret-wrapping functionality.
pub use secrecy;
parsec-interface-0.29.1/src/operations/attest_key.rs 0000644 0000000 0000000 00000002420 10461020230 0020622 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # AttestKey operation
//!
//! Produce an attestation token as proof that the given
//! key was produced and is stored in the hardware backend.
use derivative::Derivative;
use zeroize::Zeroizing;
/// Native operation for key attestation
#[derive(Derivative)]
#[derivative(Debug)]
#[non_exhaustive]
pub enum Operation {
/// Attestation via TPM 2.0 ActivateCredential operation
ActivateCredential {
/// Name of key to be attested
attested_key_name: String,
/// Blob of data representing the encrypted credential
#[derivative(Debug = "ignore")]
credential_blob: Zeroizing>,
/// Blob of data representing the encrypted secret
#[derivative(Debug = "ignore")]
secret: Zeroizing>,
/// Name of key to be used for attesting
attesting_key_name: Option,
},
}
/// Native result of key attestation
#[derive(Derivative)]
#[derivative(Debug)]
#[non_exhaustive]
pub enum Result {
/// Result of attestation via TPM 2.0 ActivateCredential operation
ActivateCredential {
/// Decrypted credential
#[derivative(Debug = "ignore")]
credential: Zeroizing>,
},
}
parsec-interface-0.29.1/src/operations/can_do_crypto.rs 0000644 0000000 0000000 00000002076 10461020230 0021300 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # CanDoCrypto operation
//!
//! Checks if the provider supports the input attributes for the operations of a given type
use super::psa_key_attributes::Attributes;
/// Public enum which stores the options for the types of check
#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
pub enum CheckType {
/// Using a specific algorithm with an existing key.
Use,
/// Generating a key and optionally using it for a specific algorithm.
Generate,
/// Importing a key and optionally using it for a specific algorithm.
Import,
/// Deriving a key and optionally using it for a specific algorithm (to be checked)
Derive,
}
/// Native object for client deleting operation.
#[derive(Clone, Debug, Copy)]
pub struct Operation {
/// The type of check required
pub check_type: CheckType,
/// The attributes that are to be checked
pub attributes: Attributes,
}
/// Native object for client deleting result.
#[derive(Copy, Clone, Debug)]
pub struct Result;
parsec-interface-0.29.1/src/operations/delete_client.rs 0000644 0000000 0000000 00000000650 10461020230 0021251 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # DeleteClient operation
//!
//! Delete all data a client own in Parsec.
/// Native object for client deleting operation.
#[derive(Clone, Debug)]
pub struct Operation {
/// A client application name.
pub client: String,
}
/// Native object for client deleting result.
#[derive(Copy, Clone, Debug)]
pub struct Result;
parsec-interface-0.29.1/src/operations/list_authenticators.rs 0000644 0000000 0000000 00000002312 10461020230 0022536 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # ListAuthenticators operation
//!
//! List the authenticators available in the service.
use crate::requests::AuthType;
use std::cmp::Eq;
/// Structure holding the basic information that defines the authenticators in the service for
/// client discovery.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AuthenticatorInfo {
/// Short description of the authenticator.
pub description: String,
/// Authenticator implementation version major.
pub version_maj: u32,
/// Authenticator implementation version minor.
pub version_min: u32,
/// Authenticator implementation version revision number.
pub version_rev: u32,
/// Authenticator ID to use on the wire protocol to communicate with this authenticator.
pub id: AuthType,
}
/// Native object for authenticator listing operation.
#[derive(Copy, Clone, Debug)]
pub struct Operation;
/// Native object for authenticator listing result.
#[derive(Debug)]
pub struct Result {
/// A list of `AuthenticatorInfo` structures, one for each authenticator available in
/// the service.
pub authenticators: Vec,
}
parsec-interface-0.29.1/src/operations/list_clients.rs 0000644 0000000 0000000 00000000656 10461020230 0021153 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # ListClients operation
//!
//! Lists all clients owning data in Parsec.
/// Native object for client listing operation.
#[derive(Copy, Clone, Debug)]
pub struct Operation;
/// Native object for client listing result.
#[derive(Debug)]
pub struct Result {
/// A list of client application names.
pub clients: Vec,
}
parsec-interface-0.29.1/src/operations/list_keys.rs 0000644 0000000 0000000 00000001510 10461020230 0020453 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # ListKeys operation
//!
//! Lists all keys belonging to the application.
use super::psa_key_attributes::Attributes;
use crate::requests::ProviderId;
/// Structure holding the basic information for a key in the application for client discovery.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyInfo {
/// The ID of the associated provider.
pub provider_id: ProviderId,
/// The name of the key.
pub name: String,
/// The key attributes.
pub attributes: Attributes,
}
/// Native object for key listing operation.
#[derive(Copy, Clone, Debug)]
pub struct Operation;
/// Native object for key listing result.
#[derive(Debug)]
pub struct Result {
/// A list of `KeyInfo` structures.
pub keys: Vec,
}
parsec-interface-0.29.1/src/operations/list_opcodes.rs 0000644 0000000 0000000 00000001236 10461020230 0021141 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # ListOpcodes operation
//!
//! List the opcodes supported by the provider.
use crate::requests::{Opcode, ProviderId};
use std::collections::HashSet;
/// Native object for opcode listing operation.
#[derive(Copy, Clone, Debug)]
pub struct Operation {
/// Provider for which the supported opcodes are requsted.
pub provider_id: ProviderId,
}
/// Native object for opcode listing result.
#[derive(Debug)]
pub struct Result {
/// `opcodes` holds a list of opcodes supported by the provider identified in
/// the request.
pub opcodes: HashSet,
}
parsec-interface-0.29.1/src/operations/list_providers.rs 0000644 0000000 0000000 00000002445 10461020230 0021525 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # ListProviders operation
//!
//! List the providers available in the service, with some information.
use crate::requests::ProviderId;
use std::cmp::Eq;
pub use uuid::Uuid;
/// Structure holding the basic information that defines the providers in
/// the service for client discovery.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ProviderInfo {
/// Unique, permanent, identifier of the provider.
pub uuid: Uuid,
/// Short description of the provider.
pub description: String,
/// Provider vendor.
pub vendor: String,
/// Provider implementation version major.
pub version_maj: u32,
/// Provider implementation version minor.
pub version_min: u32,
/// Provider implementation version revision number.
pub version_rev: u32,
/// Provider ID to use on the wire protocol to communicate with this provider.
pub id: ProviderId,
}
/// Native object for provider listing operation.
#[derive(Copy, Clone, Debug)]
pub struct Operation;
/// Native object for provider listing result.
#[derive(Debug)]
pub struct Result {
/// A list of `ProviderInfo` structures, one for each provider available in
/// the service.
pub providers: Vec,
}
parsec-interface-0.29.1/src/operations/mod.rs 0000644 0000000 0000000 00000052257 10461020230 0017242 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # Rust representation of operations
//!
//! Rust native representation of the language neutral operations described in the
//! [Operations](https://parallaxsecond.github.io/parsec-book/parsec_client/operations/index.html)
//! page in the book.
//! Some of the doc comments have directly been taken from the PSA Crypto API document version
//! 1.0.0. Please check that
//! [document](https://developer.arm.com/architectures/security-architectures/platform-security-architecture/documentation)
//! and the book for more details.
pub mod ping;
pub mod psa_generate_key;
pub mod psa_import_key;
pub mod psa_export_public_key;
pub mod psa_export_key;
pub mod psa_destroy_key;
pub mod psa_sign_hash;
pub mod psa_verify_hash;
pub mod psa_hash_compute;
pub mod psa_hash_compare;
pub mod psa_asymmetric_encrypt;
pub mod psa_asymmetric_decrypt;
pub mod psa_aead_encrypt;
pub mod psa_aead_decrypt;
pub mod psa_cipher_encrypt;
pub mod psa_cipher_decrypt;
pub mod psa_sign_message;
pub mod psa_verify_message;
pub mod list_opcodes;
pub mod list_providers;
pub mod list_authenticators;
pub mod list_keys;
pub mod delete_client;
pub mod list_clients;
pub mod psa_generate_random;
pub mod psa_raw_key_agreement;
pub mod can_do_crypto;
pub mod attest_key;
pub mod prepare_key_attestation;
pub mod utils_deprecated_primitives;
pub use psa_crypto::types::algorithm as psa_algorithm;
pub use psa_crypto::types::key as psa_key_attributes;
use crate::requests::{request::RequestBody, response::ResponseBody, BodyType, Opcode, Result};
/// Container type for operation conversion values, holding a native operation object
/// to be passed in/out of a converter.
#[derive(Debug)]
pub enum NativeOperation {
/// ListProviders operation
ListProviders(list_providers::Operation),
/// ListOpcodes operation
ListOpcodes(list_opcodes::Operation),
/// ListAuthenticators operation
ListAuthenticators(list_authenticators::Operation),
/// ListKeys operation
ListKeys(list_keys::Operation),
/// ListClients operation
ListClients(list_clients::Operation),
/// DeleteClient operation
DeleteClient(delete_client::Operation),
/// Ping operation
Ping(ping::Operation),
/// PsaGenerateKey operation
PsaGenerateKey(psa_generate_key::Operation),
/// PsaImportKey operation
PsaImportKey(psa_import_key::Operation),
/// PsaExportPublicKey operation
PsaExportPublicKey(psa_export_public_key::Operation),
/// PsaExportKey operation
PsaExportKey(psa_export_key::Operation),
/// PsaDestroyKey operation
PsaDestroyKey(psa_destroy_key::Operation),
/// PsaSignHash operation
PsaSignHash(psa_sign_hash::Operation),
/// PsaVerifyHash operation
PsaVerifyHash(psa_verify_hash::Operation),
/// PsaHashCompute operation
PsaHashCompute(psa_hash_compute::Operation),
/// PsaHashCompare operation
PsaHashCompare(psa_hash_compare::Operation),
/// PsaAsymmetricEncrypt operation
PsaAsymmetricEncrypt(psa_asymmetric_encrypt::Operation),
/// PsaAsymmetricDecrypt operation
PsaAsymmetricDecrypt(psa_asymmetric_decrypt::Operation),
/// PsaAeadEncrypt operation
PsaAeadEncrypt(psa_aead_encrypt::Operation),
/// PsaAeadDecrypt operation
PsaAeadDecrypt(psa_aead_decrypt::Operation),
/// PsaCipherEncrypt operation
PsaCipherEncrypt(psa_cipher_encrypt::Operation),
/// PsaCipherDecrypt operation
PsaCipherDecrypt(psa_cipher_decrypt::Operation),
/// PsaGenerateRandom operation
PsaGenerateRandom(psa_generate_random::Operation),
/// PsaRawKeyAgreement operation
PsaRawKeyAgreement(psa_raw_key_agreement::Operation),
/// PsaSignMessage operation
PsaSignMessage(psa_sign_message::Operation),
/// PsaVerifyMessage operation
PsaVerifyMessage(psa_verify_message::Operation),
/// CanDoCrypto operation
CanDoCrypto(can_do_crypto::Operation),
/// AttestKey operation
AttestKey(attest_key::Operation),
/// PrepareKeyAttestation operation
PrepareKeyAttestation(prepare_key_attestation::Operation),
}
impl NativeOperation {
/// Return the opcode of the operation associated.
pub fn opcode(&self) -> Opcode {
match self {
NativeOperation::Ping(_) => Opcode::Ping,
NativeOperation::PsaGenerateKey(_) => Opcode::PsaGenerateKey,
NativeOperation::PsaDestroyKey(_) => Opcode::PsaDestroyKey,
NativeOperation::PsaSignHash(_) => Opcode::PsaSignHash,
NativeOperation::PsaVerifyHash(_) => Opcode::PsaVerifyHash,
NativeOperation::PsaHashCompute(_) => Opcode::PsaHashCompute,
NativeOperation::PsaHashCompare(_) => Opcode::PsaHashCompare,
NativeOperation::PsaImportKey(_) => Opcode::PsaImportKey,
NativeOperation::PsaExportPublicKey(_) => Opcode::PsaExportPublicKey,
NativeOperation::PsaExportKey(_) => Opcode::PsaExportKey,
NativeOperation::ListOpcodes(_) => Opcode::ListOpcodes,
NativeOperation::ListProviders(_) => Opcode::ListProviders,
NativeOperation::ListAuthenticators(_) => Opcode::ListAuthenticators,
NativeOperation::ListKeys(_) => Opcode::ListKeys,
NativeOperation::ListClients(_) => Opcode::ListClients,
NativeOperation::DeleteClient(_) => Opcode::DeleteClient,
NativeOperation::PsaAsymmetricEncrypt(_) => Opcode::PsaAsymmetricEncrypt,
NativeOperation::PsaAsymmetricDecrypt(_) => Opcode::PsaAsymmetricDecrypt,
NativeOperation::PsaAeadEncrypt(_) => Opcode::PsaAeadEncrypt,
NativeOperation::PsaAeadDecrypt(_) => Opcode::PsaAeadDecrypt,
NativeOperation::PsaCipherEncrypt(_) => Opcode::PsaCipherEncrypt,
NativeOperation::PsaCipherDecrypt(_) => Opcode::PsaCipherDecrypt,
NativeOperation::PsaGenerateRandom(_) => Opcode::PsaGenerateRandom,
NativeOperation::PsaRawKeyAgreement(_) => Opcode::PsaRawKeyAgreement,
NativeOperation::PsaSignMessage(_) => Opcode::PsaSignMessage,
NativeOperation::PsaVerifyMessage(_) => Opcode::PsaVerifyMessage,
NativeOperation::CanDoCrypto(_) => Opcode::CanDoCrypto,
NativeOperation::AttestKey(_) => Opcode::AttestKey,
NativeOperation::PrepareKeyAttestation(_) => Opcode::PrepareKeyAttestation,
}
}
}
/// Container type for result conversion values, holding a native result object to be
/// passed in/out of the converter.
#[derive(Debug)]
pub enum NativeResult {
/// ListProviders result
ListProviders(list_providers::Result),
/// ListOpcodes result
ListOpcodes(list_opcodes::Result),
/// ListAuthenticators result
ListAuthenticators(list_authenticators::Result),
/// ListKeys result
ListKeys(list_keys::Result),
/// ListClients result
ListClients(list_clients::Result),
/// DeleteClient result
DeleteClient(delete_client::Result),
/// Ping result
Ping(ping::Result),
/// PsaGenerateKey result
PsaGenerateKey(psa_generate_key::Result),
/// PsaImportKey result
PsaImportKey(psa_import_key::Result),
/// PsaExportPublicKey result
PsaExportPublicKey(psa_export_public_key::Result),
/// PsaExportKey result
PsaExportKey(psa_export_key::Result),
/// PsaDestroyKey result
PsaDestroyKey(psa_destroy_key::Result),
/// PsaSignHash result
PsaSignHash(psa_sign_hash::Result),
/// PsaHashCompute result
PsaHashCompute(psa_hash_compute::Result),
/// PsaHashCompare result
PsaHashCompare(psa_hash_compare::Result),
/// PsaVerifyHash result
PsaVerifyHash(psa_verify_hash::Result),
/// PsaAsymmetricEncrypt result
PsaAsymmetricEncrypt(psa_asymmetric_encrypt::Result),
/// PsaAsymmetricDecrypt result
PsaAsymmetricDecrypt(psa_asymmetric_decrypt::Result),
/// PsaAeadEncrypt result
PsaAeadEncrypt(psa_aead_encrypt::Result),
/// PsaAeadDecrypt result
PsaAeadDecrypt(psa_aead_decrypt::Result),
/// PsaCipherEncrypt result
PsaCipherEncrypt(psa_cipher_encrypt::Result),
/// PsaCipherDecrypt result
PsaCipherDecrypt(psa_cipher_decrypt::Result),
/// PsaGenerateRandom result
PsaGenerateRandom(psa_generate_random::Result),
/// PsaRawKeyAgreement result
PsaRawKeyAgreement(psa_raw_key_agreement::Result),
/// PsaSignMessage result
PsaSignMessage(psa_sign_message::Result),
/// PsaVerifyMessage result
PsaVerifyMessage(psa_verify_message::Result),
/// CanDoCrypto result
CanDoCrypto(can_do_crypto::Result),
/// AttestKey result
AttestKey(attest_key::Result),
/// AttestKey result
PrepareKeyAttestation(prepare_key_attestation::Result),
}
impl NativeResult {
/// Return the opcode of the operation associated.
pub fn opcode(&self) -> Opcode {
match self {
NativeResult::Ping(_) => Opcode::Ping,
NativeResult::PsaGenerateKey(_) => Opcode::PsaGenerateKey,
NativeResult::PsaDestroyKey(_) => Opcode::PsaDestroyKey,
NativeResult::PsaSignHash(_) => Opcode::PsaSignHash,
NativeResult::PsaVerifyHash(_) => Opcode::PsaVerifyHash,
NativeResult::PsaImportKey(_) => Opcode::PsaImportKey,
NativeResult::PsaHashCompute(_) => Opcode::PsaHashCompute,
NativeResult::PsaHashCompare(_) => Opcode::PsaHashCompare,
NativeResult::PsaExportPublicKey(_) => Opcode::PsaExportPublicKey,
NativeResult::PsaExportKey(_) => Opcode::PsaExportKey,
NativeResult::ListOpcodes(_) => Opcode::ListOpcodes,
NativeResult::ListProviders(_) => Opcode::ListProviders,
NativeResult::ListAuthenticators(_) => Opcode::ListAuthenticators,
NativeResult::ListKeys(_) => Opcode::ListKeys,
NativeResult::ListClients(_) => Opcode::ListClients,
NativeResult::DeleteClient(_) => Opcode::DeleteClient,
NativeResult::PsaAsymmetricEncrypt(_) => Opcode::PsaAsymmetricEncrypt,
NativeResult::PsaAsymmetricDecrypt(_) => Opcode::PsaAsymmetricDecrypt,
NativeResult::PsaAeadEncrypt(_) => Opcode::PsaAeadEncrypt,
NativeResult::PsaAeadDecrypt(_) => Opcode::PsaAeadDecrypt,
NativeResult::PsaCipherEncrypt(_) => Opcode::PsaCipherEncrypt,
NativeResult::PsaCipherDecrypt(_) => Opcode::PsaCipherDecrypt,
NativeResult::PsaGenerateRandom(_) => Opcode::PsaGenerateRandom,
NativeResult::PsaRawKeyAgreement(_) => Opcode::PsaRawKeyAgreement,
NativeResult::PsaSignMessage(_) => Opcode::PsaSignMessage,
NativeResult::PsaVerifyMessage(_) => Opcode::PsaVerifyMessage,
NativeResult::CanDoCrypto(_) => Opcode::CanDoCrypto,
NativeResult::AttestKey(_) => Opcode::AttestKey,
NativeResult::PrepareKeyAttestation(_) => Opcode::PrepareKeyAttestation,
}
}
}
/// Definition of the operations converters must implement to allow usage of a specific
/// `BodyType`.
pub trait Convert {
/// Get the `BodyType` associated with this converter.
fn body_type(&self) -> BodyType;
/// Create a native operation object from a request body.
///
/// # Errors
/// - if deserialization fails, `ResponseStatus::DeserializingBodyFailed` is returned
fn body_to_operation(&self, body: RequestBody, opcode: Opcode) -> Result;
/// Create a request body from a native operation object.
///
/// # Errors
/// - if serialization fails, `ResponseStatus::SerializingBodyFailed` is returned
fn operation_to_body(&self, operation: NativeOperation) -> Result;
/// Create a native result object from a response body.
///
/// # Errors
/// - if deserialization fails, `ResponseStatus::DeserializingBodyFailed` is returned
fn body_to_result(&self, body: ResponseBody, opcode: Opcode) -> Result;
/// Create a response body from a native result object.
///
/// # Errors
/// - if serialization fails, `ResponseStatus::SerializingBodyFailed` is returned
fn result_to_body(&self, result: NativeResult) -> Result;
}
impl From for NativeOperation {
fn from(op: list_providers::Operation) -> Self {
NativeOperation::ListProviders(op)
}
}
impl From for NativeOperation {
fn from(op: list_opcodes::Operation) -> Self {
NativeOperation::ListOpcodes(op)
}
}
impl From for NativeOperation {
fn from(op: list_authenticators::Operation) -> Self {
NativeOperation::ListAuthenticators(op)
}
}
impl From for NativeOperation {
fn from(op: list_keys::Operation) -> Self {
NativeOperation::ListKeys(op)
}
}
impl From for NativeOperation {
fn from(op: list_clients::Operation) -> Self {
NativeOperation::ListClients(op)
}
}
impl From for NativeOperation {
fn from(op: delete_client::Operation) -> Self {
NativeOperation::DeleteClient(op)
}
}
impl From for NativeOperation {
fn from(op: ping::Operation) -> Self {
NativeOperation::Ping(op)
}
}
impl From for NativeOperation {
fn from(op: psa_generate_key::Operation) -> Self {
NativeOperation::PsaGenerateKey(op)
}
}
impl From for NativeOperation {
fn from(op: psa_import_key::Operation) -> Self {
NativeOperation::PsaImportKey(op)
}
}
impl From for NativeOperation {
fn from(op: psa_export_public_key::Operation) -> Self {
NativeOperation::PsaExportPublicKey(op)
}
}
impl From for NativeOperation {
fn from(op: psa_export_key::Operation) -> Self {
NativeOperation::PsaExportKey(op)
}
}
impl From for NativeOperation {
fn from(op: psa_destroy_key::Operation) -> Self {
NativeOperation::PsaDestroyKey(op)
}
}
impl From for NativeOperation {
fn from(op: psa_sign_hash::Operation) -> Self {
NativeOperation::PsaSignHash(op)
}
}
impl From for NativeOperation {
fn from(op: psa_verify_hash::Operation) -> Self {
NativeOperation::PsaVerifyHash(op)
}
}
impl From for NativeOperation {
fn from(op: psa_asymmetric_encrypt::Operation) -> Self {
NativeOperation::PsaAsymmetricEncrypt(op)
}
}
impl From for NativeOperation {
fn from(op: psa_asymmetric_decrypt::Operation) -> Self {
NativeOperation::PsaAsymmetricDecrypt(op)
}
}
impl From for NativeOperation {
fn from(op: psa_aead_encrypt::Operation) -> Self {
NativeOperation::PsaAeadEncrypt(op)
}
}
impl From for NativeOperation {
fn from(op: psa_aead_decrypt::Operation) -> Self {
NativeOperation::PsaAeadDecrypt(op)
}
}
impl From for NativeOperation {
fn from(op: psa_cipher_encrypt::Operation) -> Self {
NativeOperation::PsaCipherEncrypt(op)
}
}
impl From for NativeOperation {
fn from(op: psa_cipher_decrypt::Operation) -> Self {
NativeOperation::PsaCipherDecrypt(op)
}
}
impl From for NativeOperation {
fn from(op: psa_generate_random::Operation) -> Self {
NativeOperation::PsaGenerateRandom(op)
}
}
impl From for NativeOperation {
fn from(op: psa_hash_compute::Operation) -> Self {
NativeOperation::PsaHashCompute(op)
}
}
impl From for NativeOperation {
fn from(op: psa_hash_compare::Operation) -> Self {
NativeOperation::PsaHashCompare(op)
}
}
impl From for NativeOperation {
fn from(op: psa_raw_key_agreement::Operation) -> Self {
NativeOperation::PsaRawKeyAgreement(op)
}
}
impl From for NativeOperation {
fn from(op: psa_sign_message::Operation) -> Self {
NativeOperation::PsaSignMessage(op)
}
}
impl From for NativeOperation {
fn from(op: psa_verify_message::Operation) -> Self {
NativeOperation::PsaVerifyMessage(op)
}
}
impl From for NativeOperation {
fn from(op: can_do_crypto::Operation) -> Self {
NativeOperation::CanDoCrypto(op)
}
}
impl From for NativeOperation {
fn from(op: attest_key::Operation) -> Self {
NativeOperation::AttestKey(op)
}
}
impl From for NativeOperation {
fn from(op: prepare_key_attestation::Operation) -> Self {
NativeOperation::PrepareKeyAttestation(op)
}
}
impl From for NativeResult {
fn from(op: list_providers::Result) -> Self {
NativeResult::ListProviders(op)
}
}
impl From for NativeResult {
fn from(op: list_opcodes::Result) -> Self {
NativeResult::ListOpcodes(op)
}
}
impl From for NativeResult {
fn from(op: list_authenticators::Result) -> Self {
NativeResult::ListAuthenticators(op)
}
}
impl From for NativeResult {
fn from(op: list_keys::Result) -> Self {
NativeResult::ListKeys(op)
}
}
impl From for NativeResult {
fn from(op: list_clients::Result) -> Self {
NativeResult::ListClients(op)
}
}
impl From for NativeResult {
fn from(op: delete_client::Result) -> Self {
NativeResult::DeleteClient(op)
}
}
impl From for NativeResult {
fn from(op: ping::Result) -> Self {
NativeResult::Ping(op)
}
}
impl From for NativeResult {
fn from(op: psa_generate_key::Result) -> Self {
NativeResult::PsaGenerateKey(op)
}
}
impl From for NativeResult {
fn from(op: psa_import_key::Result) -> Self {
NativeResult::PsaImportKey(op)
}
}
impl From for NativeResult {
fn from(op: psa_export_public_key::Result) -> Self {
NativeResult::PsaExportPublicKey(op)
}
}
impl From for NativeResult {
fn from(op: psa_export_key::Result) -> Self {
NativeResult::PsaExportKey(op)
}
}
impl From for NativeResult {
fn from(op: psa_destroy_key::Result) -> Self {
NativeResult::PsaDestroyKey(op)
}
}
impl From for NativeResult {
fn from(op: psa_sign_hash::Result) -> Self {
NativeResult::PsaSignHash(op)
}
}
impl From for NativeResult {
fn from(op: psa_verify_hash::Result) -> Self {
NativeResult::PsaVerifyHash(op)
}
}
impl From for NativeResult {
fn from(op: psa_hash_compute::Result) -> Self {
NativeResult::PsaHashCompute(op)
}
}
impl From for NativeResult {
fn from(op: psa_hash_compare::Result) -> Self {
NativeResult::PsaHashCompare(op)
}
}
impl From for NativeResult {
fn from(op: psa_asymmetric_encrypt::Result) -> Self {
NativeResult::PsaAsymmetricEncrypt(op)
}
}
impl From for NativeResult {
fn from(op: psa_asymmetric_decrypt::Result) -> Self {
NativeResult::PsaAsymmetricDecrypt(op)
}
}
impl From for NativeResult {
fn from(op: psa_aead_encrypt::Result) -> Self {
NativeResult::PsaAeadEncrypt(op)
}
}
impl From for NativeResult {
fn from(op: psa_aead_decrypt::Result) -> Self {
NativeResult::PsaAeadDecrypt(op)
}
}
impl From for NativeResult {
fn from(op: psa_cipher_encrypt::Result) -> Self {
NativeResult::PsaCipherEncrypt(op)
}
}
impl From for NativeResult {
fn from(op: psa_cipher_decrypt::Result) -> Self {
NativeResult::PsaCipherDecrypt(op)
}
}
impl From for NativeResult {
fn from(op: psa_generate_random::Result) -> Self {
NativeResult::PsaGenerateRandom(op)
}
}
impl From for NativeResult {
fn from(op: psa_raw_key_agreement::Result) -> Self {
NativeResult::PsaRawKeyAgreement(op)
}
}
impl From for NativeResult {
fn from(op: psa_sign_message::Result) -> Self {
NativeResult::PsaSignMessage(op)
}
}
impl From for NativeResult {
fn from(op: psa_verify_message::Result) -> Self {
NativeResult::PsaVerifyMessage(op)
}
}
impl From for NativeResult {
fn from(op: can_do_crypto::Result) -> Self {
NativeResult::CanDoCrypto(op)
}
}
impl From for NativeResult {
fn from(op: attest_key::Result) -> Self {
NativeResult::AttestKey(op)
}
}
impl From for NativeResult {
fn from(op: prepare_key_attestation::Result) -> Self {
NativeResult::PrepareKeyAttestation(op)
}
}
parsec-interface-0.29.1/src/operations/ping.rs 0000644 0000000 0000000 00000001414 10461020230 0017405 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # Ping operation
//!
//! The Ping operation is used to check if the service is alive and determine the highest wire
//! protocol version a client can use.
/// Native object for Ping operation.
#[derive(Copy, Clone, Debug)]
pub struct Operation;
/// Native object for Ping result.
///
/// The latest wire protocol version supported by the service. The version is represented as `x.y`
/// where `x` is the version major and `y` the version minor.
#[derive(Copy, Clone, Debug)]
pub struct Result {
/// Supported latest wire protocol version major
pub wire_protocol_version_maj: u8,
/// Supported latest wire protocol version minor
pub wire_protocol_version_min: u8,
}
parsec-interface-0.29.1/src/operations/prepare_key_attestation.rs 0000644 0000000 0000000 00000002345 10461020230 0023401 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PrepareKeyAttestation operation
//!
//! Produce any parameters required for the AttestKey operation
use derivative::Derivative;
use zeroize::Zeroizing;
/// Native operation for retrieving key attestation parameters
#[derive(Debug)]
#[non_exhaustive]
pub enum Operation {
/// Get parameters for TPM 2.0 ActivateCredential operation
ActivateCredential {
/// Name of key to be attested
attested_key_name: String,
/// Name of key to be used for attesting
attesting_key_name: Option,
},
}
/// Native result of retrieving key attestation parameters
#[derive(Derivative)]
#[derivative(Debug)]
#[non_exhaustive]
pub enum Result {
/// Parameters for TPM 2.0 ActivateCredential operation
ActivateCredential {
/// TPM name of key to be attested
#[derivative(Debug = "ignore")]
name: Zeroizing>,
/// TPM public key parameters of object to be attested
#[derivative(Debug = "ignore")]
public: Zeroizing>,
/// Public part of attesting key
#[derivative(Debug = "ignore")]
attesting_key_pub: Zeroizing>,
},
}
parsec-interface-0.29.1/src/operations/psa_aead_decrypt.rs 0000644 0000000 0000000 00000012610 10461020230 0021737 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaAeadDecrypt operation
//!
//! Process an authenticated decryption operation.
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::Aead;
use crate::requests::ResponseStatus;
use derivative::Derivative;
/// Native object for AEAD decryption operations.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// Defines which key should be used for the decryption operation.
pub key_name: String,
/// An AEAD encryption algorithm that is compatible with the key type.
pub alg: Aead,
/// Nonce or IV to use.
#[derivative(Debug = "ignore")]
pub nonce: zeroize::Zeroizing>,
/// Additional data that has been authenticated but not encrypted.
#[derivative(Debug = "ignore")]
pub additional_data: zeroize::Zeroizing>,
/// Data that has been authenticated and encrypted. For algorithms where the encrypted data and
/// the authentication tag are defined as separate inputs, the buffer must contain the encrypted
/// data followed by the authentication tag.
#[derivative(Debug = "ignore")]
pub ciphertext: zeroize::Zeroizing>,
}
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows decrypting messages
/// * the key policy allows the encryption algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
/// * the message to decrypt is valid (not length 0)
/// * the nonce is valid (not length 0)
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_decrypt_message()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
if self.ciphertext.is_empty() || self.nonce.is_empty() {
return Err(ResponseStatus::PsaErrorInvalidArgument);
}
Ok(())
}
}
/// Native object for AEAD decrypt result.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// The `plaintext` field contains the authenticated and decrypted data.
#[derivative(Debug = "ignore")]
pub plaintext: zeroize::Zeroizing>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::AeadWithDefaultLengthTag;
use crate::operations::psa_key_attributes::{Lifetime, Policy, Type, UsageFlags};
use psa_crypto::types::algorithm::Aead;
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_decrypt();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::Aes,
bits: 0,
policy: Policy {
usage_flags,
permitted_algorithms: Aead::AeadWithDefaultLengthTag(AeadWithDefaultLengthTag::Ccm)
.into(),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Ccm.into(),
ciphertext: vec![0xff, 32].into(),
nonce: vec![0xaa, 12].into(),
additional_data: vec![0xff, 16].into(),
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_decrypt() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Ccm.into(),
ciphertext: vec![0xff, 32].into(),
nonce: vec![0xaa, 12].into(),
additional_data: vec![0xff, 16].into()
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Gcm.into(),
ciphertext: vec![0xff, 32].into(),
nonce: vec![0xaa, 12].into(),
additional_data: vec![0xff, 16].into()
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn invalid_plaintext() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Ccm.into(),
ciphertext: vec![].into(),
nonce: vec![0xaa, 12].into(),
additional_data: vec![0xff, 16].into()
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
#[test]
fn invalid_nonce() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Ccm.into(),
ciphertext: vec![0xff, 32].into(),
nonce: vec![].into(),
additional_data: vec![0xff, 16].into()
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
}
parsec-interface-0.29.1/src/operations/psa_aead_encrypt.rs 0000644 0000000 0000000 00000012553 10461020230 0021757 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaAeadEncrypt operation
//!
//! Process an authenticated encryption operation.
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::Aead;
use crate::requests::ResponseStatus;
use derivative::Derivative;
/// Native object for AEAD encryption operations.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// Defines which key should be used for the encryption operation.
pub key_name: String,
/// An AEAD encryption algorithm that is compatible with the key type.
pub alg: Aead,
/// Nonce or IV to use.
#[derivative(Debug = "ignore")]
pub nonce: zeroize::Zeroizing>,
/// Additional data that will be authenticated but not encrypted.
#[derivative(Debug = "ignore")]
pub additional_data: zeroize::Zeroizing>,
/// Data that will be authenticated and encrypted.
#[derivative(Debug = "ignore")]
pub plaintext: zeroize::Zeroizing>,
}
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows encrypting messages
/// * the key policy allows the encryption algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
/// * the message to encrypt is valid (not length 0)
/// * the nonce is valid (not length 0)
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_encrypt_message()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
if self.plaintext.is_empty() || self.nonce.is_empty() {
return Err(ResponseStatus::PsaErrorInvalidArgument);
}
Ok(())
}
}
/// Native object for AEAD encrypt result.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// The `ciphertext` field contains the encrypted and authenticated data.For algorithms where
/// the encrypted data and the authentication tag are defined as separate outputs, the authentication
/// tag is appended to the encrypted data.
#[derivative(Debug = "ignore")]
pub ciphertext: zeroize::Zeroizing>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::AeadWithDefaultLengthTag;
use crate::operations::psa_key_attributes::{Lifetime, Policy, Type, UsageFlags};
use psa_crypto::types::algorithm::Aead;
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_encrypt();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::Aes,
bits: 0,
policy: Policy {
usage_flags,
permitted_algorithms: Aead::AeadWithDefaultLengthTag(AeadWithDefaultLengthTag::Ccm)
.into(),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Ccm.into(),
plaintext: vec![0xff, 32].into(),
nonce: vec![0xaa, 12].into(),
additional_data: vec![0xff, 16].into(),
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_encrypt() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Ccm.into(),
plaintext: vec![0xff, 32].into(),
nonce: vec![0xaa, 12].into(),
additional_data: vec![0xff, 16].into()
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Gcm.into(),
plaintext: vec![0xff, 32].into(),
nonce: vec![0xaa, 12].into(),
additional_data: vec![0xff, 16].into()
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn invalid_plaintext() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Ccm.into(),
plaintext: vec![].into(),
nonce: vec![0xaa, 12].into(),
additional_data: vec![0xff, 16].into()
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
#[test]
fn invalid_nonce() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AeadWithDefaultLengthTag::Ccm.into(),
plaintext: vec![0xff, 32].into(),
nonce: vec![].into(),
additional_data: vec![0xff, 16].into()
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
}
parsec-interface-0.29.1/src/operations/psa_asymmetric_decrypt.rs 0000644 0000000 0000000 00000012210 10461020230 0023216 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaAsymmetricDecrypt operation
//!
//! Decrypt a short message with a public key.
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::AsymmetricEncryption;
use crate::requests::ResponseStatus;
use derivative::Derivative;
/// Native object for asymmetric decryption operations.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// Defines which key should be used for the signing operation.
pub key_name: String,
/// An asymmetric encryption algorithm to be used for decryption, that is compatible with the type of key.
pub alg: AsymmetricEncryption,
/// The short encrypted message to be decrypted.
#[derivative(Debug = "ignore")]
pub ciphertext: zeroize::Zeroizing>,
/// Salt to use during decryption, if supported by the algorithm.
#[derivative(Debug = "ignore")]
pub salt: Option>>,
}
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows decrypting messages
/// * the key policy allows the decryption algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
/// * if the algorithm is RsaPkcs1v15Crypt, it has no salt (it is not compatible with salt)
/// * the message to decrypt is valid (not length 0)
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_decrypt_message()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
if (self.alg == AsymmetricEncryption::RsaPkcs1v15Crypt && self.salt.is_some())
|| self.ciphertext.is_empty()
{
return Err(ResponseStatus::PsaErrorInvalidArgument);
}
Ok(())
}
}
/// Native object for asymmetric decrypt result.
// Debug derived as NativeResult enum requires it, even though nothing inside this Result is debuggable
// as `plaintext` is sensitive.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// Decrypted message
#[derivative(Debug = "ignore")]
pub plaintext: zeroize::Zeroizing>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::{AsymmetricEncryption, Hash};
use crate::operations::psa_key_attributes::{Lifetime, Policy, Type, UsageFlags};
use zeroize::Zeroizing;
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_decrypt();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::RsaKeyPair,
bits: 256,
policy: Policy {
usage_flags,
permitted_algorithms: AsymmetricEncryption::RsaPkcs1v15Crypt.into(),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaPkcs1v15Crypt,
ciphertext: Zeroizing::new(vec![0xff, 32]),
salt: None,
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_decrypt() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaPkcs1v15Crypt,
ciphertext: Zeroizing::new(vec![0xff, 32]),
salt: None,
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaOaep {
hash_alg: Hash::Sha256,
},
ciphertext: Zeroizing::new(vec![0xff, 32]),
salt: None,
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn invalid_ciphertext() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaPkcs1v15Crypt,
ciphertext: Zeroizing::new(vec![]),
salt: None,
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
#[test]
fn salt_with_rsapkcs1v15crypt() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaPkcs1v15Crypt,
ciphertext: Zeroizing::new(vec![0xff, 32]),
salt: Some(zeroize::Zeroizing::new(vec![0xff, 32])),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
}
parsec-interface-0.29.1/src/operations/psa_asymmetric_encrypt.rs 0000644 0000000 0000000 00000011665 10461020230 0023245 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaAsymmetricEncrypt operation
//!
//! Encrypt a short message with a public key.
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::AsymmetricEncryption;
use crate::requests::ResponseStatus;
use derivative::Derivative;
/// Native object for asymmetric encryption operations.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// Defines which key should be used for the encryption operation.
pub key_name: String,
/// An asymmetric encryption algorithm that is compatible with the key type
pub alg: AsymmetricEncryption,
/// The short message to be encrypted.
#[derivative(Debug = "ignore")]
pub plaintext: zeroize::Zeroizing>,
/// Salt to use during encryption, if supported by the algorithm.
#[derivative(Debug = "ignore")]
pub salt: Option>>,
}
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows encrypting messages
/// * the key policy allows the encryption algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
/// * if the algorithm is RsaPkcs1v15Crypt, it has no salt (it is not compatible with salt)
/// * the message to encrypt is valid (not length 0)
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_encrypt_message()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
if (self.alg == AsymmetricEncryption::RsaPkcs1v15Crypt && self.salt.is_some())
|| self.plaintext.is_empty()
{
return Err(ResponseStatus::PsaErrorInvalidArgument);
}
Ok(())
}
}
/// Native object for asymmetric encrypt result.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// The `ciphertext` field contains the encrypted short message.
#[derivative(Debug = "ignore")]
pub ciphertext: zeroize::Zeroizing>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::{AsymmetricEncryption, Hash};
use crate::operations::psa_key_attributes::{Lifetime, Policy, Type, UsageFlags};
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_encrypt();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::RsaKeyPair,
bits: 256,
policy: Policy {
usage_flags,
permitted_algorithms: AsymmetricEncryption::RsaPkcs1v15Crypt.into(),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaPkcs1v15Crypt,
plaintext: vec![0xff, 32].into(),
salt: None,
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_encrypt() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaPkcs1v15Crypt,
plaintext: vec![0xff, 32].into(),
salt: None,
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaOaep {
hash_alg: Hash::Sha256,
},
plaintext: vec![0xff, 32].into(),
salt: None,
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn invalid_plaintext() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaPkcs1v15Crypt,
plaintext: vec![].into(),
salt: None,
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
#[test]
fn salt_with_rsapkcs1v15crypt() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricEncryption::RsaPkcs1v15Crypt,
plaintext: vec![0xff, 32].into(),
salt: Some(zeroize::Zeroizing::new(vec![0xff, 32])),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
}
parsec-interface-0.29.1/src/operations/psa_cipher_decrypt.rs 0000644 0000000 0000000 00000007676 10461020230 0022337 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaCipherDecrypt operation
//!
//! Decrypt a short message with a symmetric cipher
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::Cipher;
use crate::requests::ResponseStatus;
use derivative::Derivative;
/// Native object for cipher decryption operations.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// Defines which key should be used for the decryption operation.
pub key_name: String,
/// An cipher encryption algorithm to be used for decryption, that is compatible with the type of key.
pub alg: Cipher,
/// The short encrypted message to be decrypted.
#[derivative(Debug = "ignore")]
pub ciphertext: zeroize::Zeroizing>,
}
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows decrypting messages
/// * the key policy allows the decryption algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
/// * the message to decrypt is valid (not length 0)
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_decrypt_message()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
if self.ciphertext.is_empty() {
return Err(ResponseStatus::PsaErrorInvalidArgument);
}
Ok(())
}
}
/// Native object for cipher decrypt result.
// Debug derived as NativeResult enum requires it, even though nothing inside this Result is debuggable
// as `plaintext` is sensitive.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// Decrypted message
#[derivative(Debug = "ignore")]
pub plaintext: zeroize::Zeroizing>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::Cipher;
use crate::operations::psa_key_attributes::{Lifetime, Policy, Type, UsageFlags};
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_decrypt();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::Arc4,
bits: 256,
policy: Policy {
usage_flags,
permitted_algorithms: Cipher::StreamCipher.into(),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: Cipher::StreamCipher,
ciphertext: vec![0xff, 32].into(),
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_decrypt() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: Cipher::StreamCipher,
ciphertext: vec![0xff, 32].into(),
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: Cipher::Cfb,
ciphertext: vec![0xff, 32].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn invalid_ciphertext() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: Cipher::StreamCipher,
ciphertext: vec![].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
}
parsec-interface-0.29.1/src/operations/psa_cipher_encrypt.rs 0000644 0000000 0000000 00000007462 10461020230 0022342 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaCipherEncrypt operation
//!
//! Encrypt a short message with a symmetric cipher
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::Cipher;
use crate::requests::ResponseStatus;
use derivative::Derivative;
/// Native object for cipher encryption operations.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// Defines which key should be used for the encryption operation.
pub key_name: String,
/// An cipher encryption algorithm that is compatible with the key type
pub alg: Cipher,
/// The short message to be encrypted.
#[derivative(Debug = "ignore")]
pub plaintext: zeroize::Zeroizing>,
}
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows encrypting messages
/// * the key policy allows the encryption algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
/// * the message to encrypt is valid (not length 0)
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_encrypt_message()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
if self.plaintext.is_empty() {
return Err(ResponseStatus::PsaErrorInvalidArgument);
}
Ok(())
}
}
/// Native object for cipher encrypt result.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// The `ciphertext` field contains the encrypted short message.
#[derivative(Debug = "ignore")]
pub ciphertext: zeroize::Zeroizing>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::Cipher;
use crate::operations::psa_key_attributes::{Lifetime, Policy, Type, UsageFlags};
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_encrypt();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::Arc4,
bits: 256,
policy: Policy {
usage_flags,
permitted_algorithms: Cipher::StreamCipher.into(),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: Cipher::StreamCipher,
plaintext: vec![0xff, 32].into(),
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_encrypt() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: Cipher::StreamCipher,
plaintext: vec![0xff, 32].into(),
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: Cipher::Cfb,
plaintext: vec![0xff, 32].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn invalid_plaintext() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: Cipher::StreamCipher,
plaintext: vec![].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
}
parsec-interface-0.29.1/src/operations/psa_destroy_key.rs 0000644 0000000 0000000 00000001002 10461020230 0021645 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaDestroyKey operation
//!
//! Destroy a key.
/// Native object for cryptographic key destruction.
#[derive(Debug, Clone)]
pub struct Operation {
/// `key_name` identifies the key to be destroyed.
pub key_name: String,
}
/// Native object for result of cryptographic key destruction.
///
/// True result of operation is returned in the response `status`.
#[derive(Copy, Clone, Debug)]
pub struct Result;
parsec-interface-0.29.1/src/operations/psa_export_key.rs 0000644 0000000 0000000 00000001427 10461020230 0021510 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaExportKey operation
//!
//! Export a key in binary format. See the book for the format description.
use derivative::Derivative;
/// Native object for key exporting operation.
#[derive(Debug)]
pub struct Operation {
/// `key_name` identifies the key that will be exported.
pub key_name: String,
}
/// Native object for result of key export operation.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// `data` holds the bytes defining the key, formatted as specified
/// by the provider for which the request was made.
#[derivative(Debug = "ignore")] // Don't output at debug - potentially contains private key
pub data: secrecy::Secret>,
}
parsec-interface-0.29.1/src/operations/psa_export_public_key.rs 0000644 0000000 0000000 00000001355 10461020230 0023046 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaExportPublicKey operation
//!
//! Export a key in binary format. See the book for the format description.
/// Native object for public key exporting operation.
#[derive(Debug)]
pub struct Operation {
/// `key_name` identifies the key for which the public
/// part will be exported. The specified key must be an asymmetric keypair.
pub key_name: String,
}
/// Native object for result of public key export operation.
#[derive(Debug)]
pub struct Result {
/// `data` holds the bytes defining the public key, formatted as specified
/// by the provider for which the request was made.
pub data: zeroize::Zeroizing>,
}
parsec-interface-0.29.1/src/operations/psa_generate_key.rs 0000644 0000000 0000000 00000001373 10461020230 0021761 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaGenerateKey operation
//!
//! Generate a key or a key pair.
use super::psa_key_attributes::Attributes;
/// Native object for creating a cryptographic key.
#[derive(Clone, Debug)]
pub struct Operation {
/// `key_name` specifies a name by which the service will identify the key. Key
/// name must be unique per application.
pub key_name: String,
/// `attributes` specifies the parameters to be associated with the key.
pub attributes: Attributes,
}
/// Native object for the result of creating a cryptographic key.
///
/// The true result is returned in the `status` field of the response.
#[derive(Copy, Clone, Debug)]
pub struct Result;
parsec-interface-0.29.1/src/operations/psa_generate_random.rs 0000644 0000000 0000000 00000001117 10461020230 0022445 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaGenerateRandom operation
//!
//! Generate random bytes.
use derivative::Derivative;
/// Native object for creating a cryptographic key.
#[derive(Copy, Clone, Debug)]
pub struct Operation {
/// `size` specifies how many random bytes to fetch.
pub size: usize,
}
/// Native object for random bytes result.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// Random bytes.
#[derivative(Debug = "ignore")]
pub random_bytes: zeroize::Zeroizing>,
}
parsec-interface-0.29.1/src/operations/psa_hash_compare.rs 0000644 0000000 0000000 00000001410 10461020230 0021740 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaHashCompare operation
//!
//! Compute the hash value of a message and compare it with a reference value.
use crate::operations::psa_algorithm::Hash;
use derivative::Derivative;
/// Native object for hash compare operations.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// The hash algorithm to compute.
pub alg: Hash,
/// The input to hash.
#[derivative(Debug = "ignore")]
pub input: zeroize::Zeroizing>,
/// The reference hash value.
#[derivative(Debug = "ignore")]
pub hash: zeroize::Zeroizing>,
}
/// Native object for hash compare result.
#[derive(Debug, Default, Copy, Clone)]
pub struct Result;
parsec-interface-0.29.1/src/operations/psa_hash_compute.rs 0000644 0000000 0000000 00000001402 10461020230 0021767 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaHashCompute operation
//!
//! Compute the hash value of a message.
use crate::operations::psa_algorithm::Hash;
use derivative::Derivative;
/// Native object for hash compute operations.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// The hash algorithm to compute.
pub alg: Hash,
/// The input to hash.
#[derivative(Debug = "ignore")]
pub input: zeroize::Zeroizing>,
}
/// Native object for hash compute result.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// The `hash` field contains the hash of the message.
#[derivative(Debug = "ignore")]
pub hash: zeroize::Zeroizing>,
}
parsec-interface-0.29.1/src/operations/psa_import_key.rs 0000644 0000000 0000000 00000002226 10461020230 0021477 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaImportKey operation
//!
//! Import a key in binary format.
use super::psa_key_attributes::Attributes;
use derivative::Derivative;
/// Native object for cryptographic key importing operation.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// `key_name` specifies a name by which the service will identify the key. Key
/// name must be unique per application.
pub key_name: String,
/// `attributes` specifies the attributes for the new key.
pub attributes: Attributes,
/// `data` contains the bytes for the key,
/// formatted in accordance with the requirements of the provider for the key type
/// specified in `attributes`.
// Debug is not derived for this because it could expose secrets if printed or logged
// somewhere
#[derivative(Debug = "ignore")]
pub data: crate::secrecy::Secret>,
}
/// Native object for the result of a cryptographic key import operation.
///
/// The true result is sent in the `status` field of the response header.
#[derive(Copy, Clone, Debug)]
pub struct Result;
parsec-interface-0.29.1/src/operations/psa_raw_key_agreement.rs 0000644 0000000 0000000 00000007365 10461020230 0023016 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaRawKeyAgreement operation
//!
//! Perform a raw key agreement.
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::{KeyAgreement, RawKeyAgreement};
use derivative::Derivative;
/// Native object for raw key agreement operation.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
/// `alg` specifies the raw key agreement algorithm to use. It must allow the `derive` usage flag.
pub alg: RawKeyAgreement,
/// `private_key_name` specifies a name of the private key to use in the key agreement operation.
pub private_key_name: String,
/// `peer_key` contains the bytes of a peers public key, to be used in the key agreement operation.
/// This must be in the format that `PsaImportKey` accepts.
#[derivative(Debug = "ignore")]
pub peer_key: zeroize::Zeroizing>,
}
/// Native object for result for raw key agreement operation.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
/// `data` holds the bytes defining the key, formatted as specified
/// by the provider for which the request was made.
#[derivative(Debug = "ignore")]
pub shared_secret: crate::secrecy::Secret>,
}
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows derivation
/// * the key policy allows the key agreement algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_derive_from()?;
key_attributes.permits_alg(KeyAgreement::Raw(self.alg).into())?;
key_attributes.compatible_with_alg(KeyAgreement::Raw(self.alg).into())?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::{KeyAgreement, RawKeyAgreement};
use crate::operations::psa_key_attributes::{EccFamily, Lifetime, Policy, Type, UsageFlags};
use crate::requests::ResponseStatus;
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_derive();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::EccKeyPair {
curve_family: EccFamily::SecpR1,
},
bits: 256,
policy: Policy {
usage_flags,
permitted_algorithms: KeyAgreement::Raw(RawKeyAgreement::Ecdh).into(),
},
}
}
#[test]
fn validate_success() {
(Operation {
private_key_name: String::from("some key"),
alg: RawKeyAgreement::Ecdh,
peer_key: vec![0xff, 32].into(),
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_derive() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
private_key_name: String::from("some key"),
alg: RawKeyAgreement::Ecdh,
peer_key: vec![0xff, 32].into(),
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
private_key_name: String::from("some key"),
alg: RawKeyAgreement::Ffdh,
peer_key: vec![0xff, 32].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
}
parsec-interface-0.29.1/src/operations/psa_sign_hash.rs 0000644 0000000 0000000 00000011543 10461020230 0021262 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaSignHash operation
//!
//! Sign an already-calculated hash with a private key.
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::AsymmetricSignature;
use crate::requests::ResponseStatus;
/// Native object for asymmetric sign operations.
#[derive(Debug)]
pub struct Operation {
/// Defines which key should be used for the signing operation.
pub key_name: String,
/// An asymmetric signature algorithm that separates the hash and sign operations, that is
/// compatible with the type of key.
pub alg: AsymmetricSignature,
/// The input whose signature is to be verified. This is usually the hash of a message.
pub hash: zeroize::Zeroizing>,
}
/// Native object for asymmetric sign result.
#[derive(Debug)]
pub struct Result {
/// The `signature` field contains the resulting bytes from the signing operation. The format of
/// the signature is as specified by the provider doing the signing.
pub signature: zeroize::Zeroizing>,
}
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows signing hashes
/// * the key policy allows the signing algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
/// * the length of the given digest is consistent with the specified signing algorithm
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_sign_hash()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
if !self.alg.is_hash_len_permitted(self.hash.len()) {
return Err(ResponseStatus::PsaErrorInvalidArgument);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::{Algorithm, AsymmetricSignature, Hash};
use crate::operations::psa_key_attributes::{EccFamily, Lifetime, Policy, Type, UsageFlags};
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_sign_hash();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::EccKeyPair {
curve_family: EccFamily::SecpR1,
},
bits: 256,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
}),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
hash: vec![0xff; 32].into(),
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_sign() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
hash: vec![0xff; 32].into(),
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha224.into(),
},
hash: vec![0xff; 28].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_scheme() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::RsaPss {
hash_alg: Hash::Sha224.into(),
},
hash: vec![0xff; 28].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn invalid_hash() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
hash: vec![0xff; 16].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
}
parsec-interface-0.29.1/src/operations/psa_sign_message.rs 0000644 0000000 0000000 00000010213 10461020230 0021754 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaSignMessage operation
//!
//! Sign a message with a private key.
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::AsymmetricSignature;
/// Native object for asymmetric sign operations.
#[derive(Debug)]
pub struct Operation {
/// Defines which key should be used for the signing operation.
pub key_name: String,
/// An asymmetric signature algorithm that separates the hash and sign operations, that is
/// compatible with the type of key.
pub alg: AsymmetricSignature,
/// The message to sign.
pub message: zeroize::Zeroizing>,
}
/// Native object for asymmetric sign result.
#[derive(Debug)]
pub struct Result {
/// The `signature` field contains the resulting bytes from the signing operation. The format of
/// the signature is as specified by the provider doing the signing.
pub signature: zeroize::Zeroizing>,
}
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows signing messages
/// * the key policy allows the signing algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_sign_message()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::{Algorithm, AsymmetricSignature, Hash};
use crate::operations::psa_key_attributes::{EccFamily, Lifetime, Policy, Type, UsageFlags};
use crate::requests::ResponseStatus;
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_sign_hash();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::EccKeyPair {
curve_family: EccFamily::SecpR1,
},
bits: 256,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
}),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
message: vec![0xff; 32].into(),
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_sign() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
message: vec![0xff; 32].into(),
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha224.into(),
},
message: vec![0xff; 28].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_scheme() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::RsaPss {
hash_alg: Hash::Sha224.into(),
},
message: vec![0xff; 28].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
}
parsec-interface-0.29.1/src/operations/psa_verify_hash.rs 0000644 0000000 0000000 00000012234 10461020230 0021624 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaVerifyHash operation
//!
//! Verify the signature of a hash or short message using a public key.
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::AsymmetricSignature;
use crate::requests::ResponseStatus;
/// Native object for asymmetric verification of signatures.
#[derive(Debug)]
pub struct Operation {
/// `key_name` specifies the key to be used for verification.
pub key_name: String,
/// An asymmetric signature algorithm that separates the hash and sign operations, that is
/// compatible with the type of key.
pub alg: AsymmetricSignature,
/// The `hash` contains a short message or hash value as described for the
/// asymmetric signing operation.
pub hash: zeroize::Zeroizing>,
/// Buffer containing the signature to verify.
pub signature: zeroize::Zeroizing>,
}
/// Native object for asymmetric verification of signatures.
///
/// The true result of the operation is sent as a `status` code in the response.
#[derive(Copy, Clone, Debug)]
pub struct Result;
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows verifying signatures on hashes
/// * the key policy allows the verification algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
/// * the length of the given digest is consistent with the specified verification algorithm
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_verify_hash()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
if !self.alg.is_hash_len_permitted(self.hash.len()) {
return Err(ResponseStatus::PsaErrorInvalidArgument);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::{Algorithm, AsymmetricSignature, Hash};
use crate::operations::psa_key_attributes::{EccFamily, Lifetime, Policy, Type, UsageFlags};
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_verify_hash();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::EccKeyPair {
curve_family: EccFamily::SecpR1,
},
bits: 256,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
}),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
hash: vec![0xff; 32].into(),
signature: vec![0xa5; 65].into(),
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_sign() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
hash: vec![0xff; 32].into(),
signature: vec![0xa5; 65].into(),
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha224.into(),
},
hash: vec![0xff; 28].into(),
signature: vec![0xa5; 65].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_scheme() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::RsaPss {
hash_alg: Hash::Sha224.into(),
},
hash: vec![0xff; 28].into(),
signature: vec![0xa5; 65].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn invalid_hash() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
hash: vec![0xff; 16].into(),
signature: vec![0xa5; 65].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorInvalidArgument
);
}
}
parsec-interface-0.29.1/src/operations/psa_verify_message.rs 0000644 0000000 0000000 00000010701 10461020230 0022322 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaVerifyMessage operation
//!
//! Verify the signature of a message using a public key.
use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::AsymmetricSignature;
/// Native object for asymmetric verification of signatures.
#[derive(Debug)]
pub struct Operation {
/// `key_name` specifies the key to be used for verification.
pub key_name: String,
/// An asymmetric signature algorithm that separates the hash and sign operations, that is
/// compatible with the type of key.
pub alg: AsymmetricSignature,
/// The `message` whose signature is to be verified for the
/// asymmetric signing operation.
pub message: zeroize::Zeroizing>,
/// Buffer containing the signature to verify.
pub signature: zeroize::Zeroizing>,
}
/// Native object for asymmetric verification of signatures.
///
/// The true result of the operation is sent as a `status` code in the response.
#[derive(Copy, Clone, Debug)]
pub struct Result;
impl Operation {
/// Validate the contents of the operation against the attributes of the key it targets
///
/// This method checks that:
/// * the key policy allows verifying signatures on messages
/// * the key policy allows the verification algorithm requested in the operation
/// * the key type is compatible with the requested algorithm
pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
key_attributes.can_verify_message()?;
key_attributes.permits_alg(self.alg.into())?;
key_attributes.compatible_with_alg(self.alg.into())?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::psa_algorithm::{Algorithm, AsymmetricSignature, Hash};
use crate::operations::psa_key_attributes::{EccFamily, Lifetime, Policy, Type, UsageFlags};
use crate::requests::ResponseStatus;
fn get_attrs() -> Attributes {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags.set_verify_hash();
Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::EccKeyPair {
curve_family: EccFamily::SecpR1,
},
bits: 256,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
}),
},
}
}
#[test]
fn validate_success() {
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
message: vec![0xff; 32].into(),
signature: vec![0xa5; 65].into(),
})
.validate(get_attrs())
.unwrap();
}
#[test]
fn cannot_sign() {
let mut attrs = get_attrs();
attrs.policy.usage_flags = UsageFlags::default();
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha256.into(),
},
message: vec![0xff; 32].into(),
signature: vec![0xa5; 65].into(),
})
.validate(attrs)
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_algorithm() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::Ecdsa {
hash_alg: Hash::Sha224.into(),
},
message: vec![0xff; 28].into(),
signature: vec![0xa5; 65].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
#[test]
fn wrong_scheme() {
assert_eq!(
(Operation {
key_name: String::from("some key"),
alg: AsymmetricSignature::RsaPss {
hash_alg: Hash::Sha224.into(),
},
message: vec![0xff; 28].into(),
signature: vec![0xa5; 65].into(),
})
.validate(get_attrs())
.unwrap_err(),
ResponseStatus::PsaErrorNotPermitted
);
}
}
parsec-interface-0.29.1/src/operations/utils_deprecated_primitives.rs 0000644 0000000 0000000 00000057123 10461020230 0024253 0 ustar 0000000 0000000 // Copyright 2022 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//!
//! # Utilities for checking deprecated primitives
//! # by PSA Crypto API 1.0.0
use crate::requests::{ResponseStatus, Result};
use psa_crypto::types::algorithm::*;
use psa_crypto::types::key;
use psa_crypto::types::key::Type;
fn get_deprecated_hashes() -> Vec {
vec![Hash::Md2, Hash::Md4, Hash::Md5, Hash::Sha1]
}
/// Check if hash is deprecated by PSA Crypto API
pub fn is_hash_deprecated(hash: Hash) -> bool {
get_deprecated_hashes().contains(&hash)
}
/// Check if signhash is deprecated by PSA Crypto API
pub fn is_signhash_deprecated(signhash: SignHash) -> bool {
match signhash {
SignHash::Specific(hash) => is_hash_deprecated(hash),
SignHash::Any => false,
}
}
/// Check if any part of the mac is deprecated by PSA Crypto API
pub fn is_mac_deprecated(mac: Mac) -> bool {
pub fn is_full_length_mac_deprecated(full_length_mac: FullLengthMac) -> bool {
match full_length_mac {
FullLengthMac::Hmac { hash_alg } => is_hash_deprecated(hash_alg),
_ => false,
}
}
match mac {
Mac::FullLength(full_length_mac) => is_full_length_mac_deprecated(full_length_mac),
Mac::Truncated { mac_alg, .. } => is_full_length_mac_deprecated(mac_alg),
}
}
/// Check if any part of the cipher is deprecated by PSA Crypto API
pub fn is_cipher_deprecated(_cipher: Cipher) -> bool {
false
}
/// Check if any part of the aead is deprecated by PSA Crypto API
pub fn is_aead_deprecated(_aead: Aead) -> bool {
false
}
/// Check if any part of the asymmetric signature is deprecated by PSA Crypto API
pub fn is_asymmetric_signature_deprecated(asymm_sig: AsymmetricSignature) -> bool {
match asymm_sig {
AsymmetricSignature::RsaPkcs1v15Sign { hash_alg }
| AsymmetricSignature::RsaPss { hash_alg }
| AsymmetricSignature::Ecdsa { hash_alg }
| AsymmetricSignature::DeterministicEcdsa { hash_alg } => is_signhash_deprecated(hash_alg),
_ => false,
}
}
/// Check if any part of the asymmetric encryption is deprecated by PSA Crypto API
pub fn is_asymmetric_encryption_deprecated(asymm_enc: AsymmetricEncryption) -> bool {
match asymm_enc {
AsymmetricEncryption::RsaOaep { hash_alg } => is_hash_deprecated(hash_alg),
_ => false,
}
}
/// Check if any part of the key agreement is deprecated by PSA Crypto API
pub fn is_key_agreement_deprecated(key_agreement: KeyAgreement) -> bool {
match key_agreement {
KeyAgreement::WithKeyDerivation { kdf_alg, .. } => is_key_derivation_deprecated(kdf_alg),
_ => false,
}
}
/// Check if any part of the key derivation is deprecated by PSA Crypto API
pub fn is_key_derivation_deprecated(keyderv: KeyDerivation) -> bool {
match keyderv {
KeyDerivation::Hkdf { hash_alg }
| KeyDerivation::Tls12Prf { hash_alg }
| KeyDerivation::Tls12PskToMs { hash_alg } => is_hash_deprecated(hash_alg),
}
}
/// Check if any part of the algorithm is deprecated by PSA Crypto API
pub fn is_algorithm_deprecated(alg: Algorithm) -> bool {
match alg {
Algorithm::None => false,
Algorithm::Hash(hash) => is_hash_deprecated(hash),
Algorithm::Mac(mac) => is_mac_deprecated(mac),
Algorithm::Cipher(cipher) => is_cipher_deprecated(cipher),
Algorithm::Aead(aead) => is_aead_deprecated(aead),
Algorithm::AsymmetricSignature(asymm_sig) => is_asymmetric_signature_deprecated(asymm_sig),
Algorithm::AsymmetricEncryption(asymm_enc) => {
is_asymmetric_encryption_deprecated(asymm_enc)
}
Algorithm::KeyAgreement(key_agreement) => is_key_agreement_deprecated(key_agreement),
Algorithm::KeyDerivation(keyderv) => is_key_derivation_deprecated(keyderv),
}
}
/// Return a list of deprecated keys (type, size) if size is None, then the key type is deprecated
fn get_deprecated_keys() -> Vec<(Type, Option)> {
vec![
(Type::Des, None),
(Type::Arc4, None),
(
Type::EccPublicKey {
curve_family: key::EccFamily::BrainpoolPR1,
},
Some(160),
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SectR2,
},
None,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SectR1,
},
Some(163),
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SectK1,
},
Some(163),
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SecpR2,
},
None,
),
]
}
/// Check if the key or the key type is deprecated by PSA Crypto API
pub fn is_key_deprecated(key_type: Type, key_size: usize) -> bool {
for (ktype, ksize) in get_deprecated_keys() {
if ktype == key_type && (ksize.is_none() || ksize == Some(key_size)) {
return true;
}
}
false
}
/// Checks if any part of the key template is deprecated by PSA Crypto API
pub trait CheckDeprecated {
/// Return Error with status ResponseStatus::DeprecatedPrimitive
/// if any part of the key template is deprecated by PSA Crypto API
fn check_deprecated(&self) -> Result<()>;
}
impl CheckDeprecated for crate::operations::psa_import_key::Operation {
/// Checks if any part of the key template is deprecated by PSA Crypto API
fn check_deprecated(&self) -> Result<()> {
if is_algorithm_deprecated(self.attributes.policy.permitted_algorithms)
|| is_key_deprecated(self.attributes.key_type, self.attributes.bits)
{
return Err(ResponseStatus::DeprecatedPrimitive);
}
Ok(())
}
}
impl CheckDeprecated for crate::operations::psa_generate_key::Operation {
/// Check if any part of the key template is deprecated by PSA Crypto API
fn check_deprecated(&self) -> Result<()> {
if is_algorithm_deprecated(self.attributes.policy.permitted_algorithms)
|| is_key_deprecated(self.attributes.key_type, self.attributes.bits)
{
return Err(ResponseStatus::DeprecatedPrimitive);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn get_selection_non_deprecated_hashes() -> Vec {
vec![Hash::Sha256, Hash::Sha3_512, Hash::Sha384, Hash::Ripemd160]
}
fn get_deprecated_macs() -> Vec {
let mut deprecated_macs: Vec = vec![];
for hash in get_deprecated_hashes() {
deprecated_macs.push(Mac::FullLength(FullLengthMac::Hmac { hash_alg: hash }));
// mac_length is chosen arbitary
deprecated_macs.push(Mac::Truncated {
mac_alg: FullLengthMac::Hmac { hash_alg: hash },
mac_length: 1234,
});
}
deprecated_macs
}
fn get_selection_non_deprecated_macs() -> Vec {
let mut selection_non_deprecated_macs: Vec = vec![
Mac::FullLength(FullLengthMac::CbcMac),
Mac::FullLength(FullLengthMac::Cmac),
Mac::Truncated {
mac_alg: FullLengthMac::CbcMac,
// mac_length is chosen arbitary
mac_length: 1234,
},
Mac::Truncated {
mac_alg: FullLengthMac::Cmac,
// mac_length is chosen arbitary
mac_length: 1234,
},
];
for hash in get_selection_non_deprecated_hashes() {
selection_non_deprecated_macs
.push(Mac::FullLength(FullLengthMac::Hmac { hash_alg: hash }));
selection_non_deprecated_macs.push(Mac::Truncated {
mac_alg: FullLengthMac::Hmac { hash_alg: hash },
// mac_length is chosen arbitary
mac_length: 1234,
});
}
selection_non_deprecated_macs
}
fn get_deprecated_ciphers() -> Vec {
vec![]
}
fn get_selection_non_deprecated_ciphers() -> Vec {
vec![Cipher::Ctr, Cipher::CbcNoPadding, Cipher::StreamCipher]
}
fn get_deprecated_aeads() -> Vec {
vec![]
}
fn get_selection_non_deprecated_aeads() -> Vec {
vec![
Aead::AeadWithDefaultLengthTag(AeadWithDefaultLengthTag::Ccm),
Aead::AeadWithDefaultLengthTag(AeadWithDefaultLengthTag::Gcm),
// tag_length is chosen arbitary
Aead::AeadWithShortenedTag {
aead_alg: AeadWithDefaultLengthTag::Chacha20Poly1305,
tag_length: 121,
},
Aead::AeadWithShortenedTag {
aead_alg: AeadWithDefaultLengthTag::Ccm,
tag_length: 212,
},
]
}
fn get_deprecated_asymmetric_signatures() -> Vec {
let mut deprecated_asymmetric_signatures = vec![];
for hash in get_deprecated_hashes() {
deprecated_asymmetric_signatures.push(AsymmetricSignature::RsaPkcs1v15Sign {
hash_alg: hash.into(),
});
deprecated_asymmetric_signatures.push(AsymmetricSignature::RsaPss {
hash_alg: hash.into(),
});
deprecated_asymmetric_signatures.push(AsymmetricSignature::Ecdsa {
hash_alg: hash.into(),
});
deprecated_asymmetric_signatures.push(AsymmetricSignature::DeterministicEcdsa {
hash_alg: hash.into(),
});
}
deprecated_asymmetric_signatures
}
fn get_selection_non_deprecated_asymmetric_signatures() -> Vec {
let mut selection_non_deprecated_asymmetric_signatures = vec![
AsymmetricSignature::RsaPkcs1v15SignRaw,
AsymmetricSignature::EcdsaAny,
];
for hash in get_selection_non_deprecated_hashes() {
selection_non_deprecated_asymmetric_signatures.push(
AsymmetricSignature::RsaPkcs1v15Sign {
hash_alg: hash.into(),
},
);
selection_non_deprecated_asymmetric_signatures.push(AsymmetricSignature::RsaPss {
hash_alg: hash.into(),
});
selection_non_deprecated_asymmetric_signatures.push(AsymmetricSignature::Ecdsa {
hash_alg: hash.into(),
});
selection_non_deprecated_asymmetric_signatures.push(
AsymmetricSignature::DeterministicEcdsa {
hash_alg: hash.into(),
},
);
}
selection_non_deprecated_asymmetric_signatures
}
fn get_deprecated_asymmetric_encryptions() -> Vec {
let mut deprecated_asymmetric_encryptions = vec![];
for hash in get_deprecated_hashes() {
deprecated_asymmetric_encryptions
.push(AsymmetricEncryption::RsaOaep { hash_alg: hash });
}
deprecated_asymmetric_encryptions
}
fn get_selection_non_deprecated_asymmetric_encryptions() -> Vec {
let mut selection_non_deprecated_asymmetric_encryptions =
vec![AsymmetricEncryption::RsaPkcs1v15Crypt];
for hash in get_selection_non_deprecated_hashes() {
selection_non_deprecated_asymmetric_encryptions
.push(AsymmetricEncryption::RsaOaep { hash_alg: hash });
}
selection_non_deprecated_asymmetric_encryptions
}
fn get_deprecated_key_derivations() -> Vec {
let mut deprecated_key_derivations = vec![];
for hash in get_deprecated_hashes() {
deprecated_key_derivations.push(KeyDerivation::Hkdf { hash_alg: hash });
deprecated_key_derivations.push(KeyDerivation::Tls12Prf { hash_alg: hash });
deprecated_key_derivations.push(KeyDerivation::Tls12PskToMs { hash_alg: hash });
}
deprecated_key_derivations
}
fn get_selection_non_deprecated_key_derivations() -> Vec {
let mut selection_non_deprecated_key_derivations = vec![];
for hash in get_selection_non_deprecated_hashes() {
selection_non_deprecated_key_derivations.push(KeyDerivation::Hkdf { hash_alg: hash });
selection_non_deprecated_key_derivations
.push(KeyDerivation::Tls12Prf { hash_alg: hash });
selection_non_deprecated_key_derivations
.push(KeyDerivation::Tls12PskToMs { hash_alg: hash });
}
selection_non_deprecated_key_derivations
}
fn get_deprecated_key_agreements() -> Vec {
let mut deprecated_key_agreements = vec![];
for keyderv in get_deprecated_key_derivations() {
deprecated_key_agreements.push(KeyAgreement::WithKeyDerivation {
ka_alg: RawKeyAgreement::Ffdh,
kdf_alg: keyderv,
});
deprecated_key_agreements.push(KeyAgreement::WithKeyDerivation {
ka_alg: RawKeyAgreement::Ecdh,
kdf_alg: keyderv,
});
}
deprecated_key_agreements
}
fn get_selection_non_deprecated_key_agreements() -> Vec {
let mut selection_non_deprecated_key_agreements = vec![];
for keyderv in get_selection_non_deprecated_key_derivations() {
selection_non_deprecated_key_agreements.push(KeyAgreement::WithKeyDerivation {
ka_alg: RawKeyAgreement::Ffdh,
kdf_alg: keyderv,
});
selection_non_deprecated_key_agreements.push(KeyAgreement::WithKeyDerivation {
ka_alg: RawKeyAgreement::Ecdh,
kdf_alg: keyderv,
});
}
selection_non_deprecated_key_agreements.push(KeyAgreement::Raw(RawKeyAgreement::Ffdh));
selection_non_deprecated_key_agreements.push(KeyAgreement::Raw(RawKeyAgreement::Ecdh));
selection_non_deprecated_key_agreements
}
fn get_deprecated_algorithms() -> Vec {
let mut deprecated_algorithms: Vec = vec![];
// Hashes
for hash in get_deprecated_hashes() {
deprecated_algorithms.push(Algorithm::Hash(hash));
}
// Macs
for mac in get_deprecated_macs() {
deprecated_algorithms.push(Algorithm::Mac(mac));
}
// Cipher
for cipher in get_deprecated_ciphers() {
deprecated_algorithms.push(Algorithm::Cipher(cipher));
}
// Aead
for aead in get_deprecated_aeads() {
deprecated_algorithms.push(Algorithm::Aead(aead));
}
// AsymmetricSignatures
for asymm_sig in get_deprecated_asymmetric_signatures() {
deprecated_algorithms.push(Algorithm::AsymmetricSignature(asymm_sig));
}
// AsymmetricEncryptions
for asymm_enc in get_deprecated_asymmetric_encryptions() {
deprecated_algorithms.push(Algorithm::AsymmetricEncryption(asymm_enc));
}
// KeyDerivations
for key_derv in get_deprecated_key_derivations() {
deprecated_algorithms.push(Algorithm::KeyDerivation(key_derv));
}
// KeyAgreements
for key_agreement in get_deprecated_key_agreements() {
deprecated_algorithms.push(Algorithm::KeyAgreement(key_agreement));
}
deprecated_algorithms
}
fn get_selection_non_deprecated_algorithms() -> Vec {
let mut selection_non_deprecated_algorithms: Vec = vec![];
// Hashes
for hash in get_selection_non_deprecated_hashes() {
selection_non_deprecated_algorithms.push(Algorithm::Hash(hash));
}
// Macs
for mac in get_selection_non_deprecated_macs() {
selection_non_deprecated_algorithms.push(Algorithm::Mac(mac));
}
// Cipher
for cipher in get_selection_non_deprecated_ciphers() {
selection_non_deprecated_algorithms.push(Algorithm::Cipher(cipher));
}
// Aead
for aead in get_selection_non_deprecated_aeads() {
selection_non_deprecated_algorithms.push(Algorithm::Aead(aead));
}
// AsymmetricSignatures
for asymm_sig in get_selection_non_deprecated_asymmetric_signatures() {
selection_non_deprecated_algorithms.push(Algorithm::AsymmetricSignature(asymm_sig));
}
// AsymmetricEncryptions
for asymm_enc in get_selection_non_deprecated_asymmetric_encryptions() {
selection_non_deprecated_algorithms.push(Algorithm::AsymmetricEncryption(asymm_enc));
}
// KeyDerivations
for key_derv in get_selection_non_deprecated_key_derivations() {
selection_non_deprecated_algorithms.push(Algorithm::KeyDerivation(key_derv));
}
// KeyAgreements
for key_agreement in get_selection_non_deprecated_key_agreements() {
selection_non_deprecated_algorithms.push(Algorithm::KeyAgreement(key_agreement));
}
selection_non_deprecated_algorithms
}
#[test]
fn deprecated_algorithms() {
for algo in get_deprecated_algorithms() {
assert!(is_algorithm_deprecated(algo), "algorithm: {algo:?}");
}
}
#[test]
fn non_deprecated_algorithms() {
for algo in get_selection_non_deprecated_algorithms() {
assert!(!is_algorithm_deprecated(algo), "algorithm: {algo:?}");
}
}
#[test]
fn deprecated_keys() {
let test_keys = vec![
(
Type::EccPublicKey {
curve_family: key::EccFamily::SecpR2,
},
160,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SectK1,
},
163,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SectR1,
},
163,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SectR2,
},
163,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::BrainpoolPR1,
},
160,
),
(Type::Des, 56),
(Type::Des, 56 * 2),
(Type::Des, 56 * 3),
(Type::Arc4, 40),
(Type::Arc4, 2048),
];
for (ktype, ksize) in test_keys {
assert!(
is_key_deprecated(ktype, ksize),
"key: ({ktype:?} : {ksize:?})"
);
}
}
#[test]
fn non_deprecated_keys() {
let test_keys = vec![
(
Type::EccPublicKey {
curve_family: key::EccFamily::SecpK1,
},
192,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SecpR1,
},
256,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SectK1,
},
239,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::SectR1,
},
409,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::BrainpoolPR1,
},
192,
),
(
Type::EccPublicKey {
curve_family: key::EccFamily::BrainpoolPR1,
},
256,
),
(Type::Aes, 256),
(Type::RsaPublicKey, 2048),
(Type::Hmac, 128),
(Type::Chacha20, 256),
];
for (ktype, ksize) in test_keys {
assert!(
!is_key_deprecated(ktype, ksize),
"key: ({ktype:?} : {ksize:?})"
);
}
}
#[test]
fn op_check_deprecated_for_deprecated() {
use psa_crypto::types::key::{Attributes, Lifetime, Policy, UsageFlags};
let mut generate_key_op = crate::operations::psa_generate_key::Operation {
key_name: "dummy".to_string(),
attributes: Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::RawData,
bits: 0,
policy: Policy {
usage_flags: UsageFlags::default(),
permitted_algorithms: Algorithm::None,
},
},
};
let mut import_key_op = crate::operations::psa_import_key::Operation {
key_name: "dummy".to_string(),
attributes: Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::RawData,
bits: 0,
policy: Policy {
usage_flags: UsageFlags::default(),
permitted_algorithms: Algorithm::None,
},
},
data: secrecy::Secret::new(vec![]),
};
let (test_key_type, test_key_size) = get_deprecated_keys()[0];
let test_algorithm = Algorithm::Hash(Hash::Md2);
generate_key_op.attributes.key_type = test_key_type;
generate_key_op.attributes.bits = test_key_size.unwrap_or(0);
generate_key_op.attributes.policy.permitted_algorithms = test_algorithm;
assert_eq!(
generate_key_op.check_deprecated(),
Err(ResponseStatus::DeprecatedPrimitive)
);
import_key_op.attributes.key_type = test_key_type;
import_key_op.attributes.bits = test_key_size.unwrap_or(0);
import_key_op.attributes.policy.permitted_algorithms = test_algorithm;
assert_eq!(
import_key_op.check_deprecated(),
Err(ResponseStatus::DeprecatedPrimitive)
);
}
#[test]
fn op_check_deprecated_for_non_deprecated() {
use psa_crypto::types::key::{Attributes, Lifetime, Policy, UsageFlags};
let mut generate_key_op = crate::operations::psa_generate_key::Operation {
key_name: "dummy".to_string(),
attributes: Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::RawData,
bits: 0,
policy: Policy {
usage_flags: UsageFlags::default(),
permitted_algorithms: Algorithm::None,
},
},
};
let mut import_key_op = crate::operations::psa_import_key::Operation {
key_name: "dummy".to_string(),
attributes: Attributes {
lifetime: Lifetime::Persistent,
key_type: Type::RawData,
bits: 0,
policy: Policy {
usage_flags: UsageFlags::default(),
permitted_algorithms: Algorithm::None,
},
},
data: secrecy::Secret::new(vec![]),
};
let test_key_type = Type::Aes;
let test_key_size: usize = 256;
let test_algorithm = Algorithm::Cipher(Cipher::CbcNoPadding);
generate_key_op.attributes.key_type = test_key_type;
generate_key_op.attributes.bits = test_key_size;
generate_key_op.attributes.policy.permitted_algorithms = test_algorithm;
assert_eq!(generate_key_op.check_deprecated(), Ok(()));
import_key_op.attributes.key_type = test_key_type;
import_key_op.attributes.bits = test_key_size;
import_key_op.attributes.policy.permitted_algorithms = test_algorithm;
assert_eq!(import_key_op.check_deprecated(), Ok(()));
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_attest_key.rs 0000644 0000000 0000000 00000026714 10461020230 0024316 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::attest_key::{
attestation_mechanism_params, attestation_output, AttestationMechanismParams,
AttestationOutput, Operation as OperationProto, Result as ResultProto,
};
use crate::operations::attest_key::{Operation, Result};
use crate::requests::ResponseStatus;
use log::error;
use std::convert::TryFrom;
impl TryFrom for OperationProto {
type Error = ResponseStatus;
fn try_from(op: Operation) -> std::result::Result {
match op {
Operation::ActivateCredential {
attested_key_name,
attesting_key_name,
credential_blob,
secret,
} => Ok(OperationProto {
attested_key_name,
attesting_key_name: attesting_key_name.unwrap_or_default(),
parameters: Some(AttestationMechanismParams {
mechanism: Some(attestation_mechanism_params::Mechanism::ActivateCredential(
attestation_mechanism_params::ActivateCredential {
credential_blob: credential_blob.to_vec(),
secret: secret.to_vec(),
},
)),
}),
}),
}
}
}
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(proto_op: OperationProto) -> std::result::Result {
match proto_op.parameters {
Some(AttestationMechanismParams {
mechanism:
Some(attestation_mechanism_params::Mechanism::ActivateCredential(
attestation_mechanism_params::ActivateCredential {
credential_blob,
secret,
},
)),
}) => Ok(Operation::ActivateCredential {
attested_key_name: proto_op.attested_key_name,
attesting_key_name: if proto_op.attesting_key_name.is_empty() {
None
} else {
Some(proto_op.attesting_key_name)
},
credential_blob: credential_blob.into(),
secret: secret.into(),
}),
_ => {
error!("The encoding of the operation does not follow the expected pattern");
Err(ResponseStatus::InvalidEncoding)
}
}
}
}
impl TryFrom for ResultProto {
type Error = ResponseStatus;
fn try_from(op: Result) -> std::result::Result {
match op {
Result::ActivateCredential { credential } => Ok(ResultProto {
output: Some(AttestationOutput {
mechanism: Some(attestation_output::Mechanism::ActivateCredential(
attestation_output::ActivateCredential {
credential: credential.to_vec(),
},
)),
}),
}),
}
}
}
impl TryFrom for Result {
type Error = ResponseStatus;
fn try_from(proto_op: ResultProto) -> std::result::Result {
match proto_op {
ResultProto {
output:
Some(AttestationOutput {
mechanism:
Some(attestation_output::Mechanism::ActivateCredential(
attestation_output::ActivateCredential { credential },
)),
}),
} => Ok(Result::ActivateCredential {
credential: credential.into(),
}),
_ => {
error!("The encoding of the result does not follow the expected pattern");
Err(ResponseStatus::InvalidEncoding)
}
}
}
}
#[cfg(test)]
mod test {
use super::super::generated_ops::attest_key::{
attestation_mechanism_params, attestation_output, AttestationMechanismParams,
AttestationOutput, Operation as OperationProto, Result as ResultProto,
};
use super::super::{Convert, ProtobufConverter};
use crate::operations::{
attest_key::Operation, attest_key::Result, NativeOperation, NativeResult,
};
use crate::requests::Opcode;
use std::convert::TryInto;
static CONVERTER: ProtobufConverter = ProtobufConverter {};
#[test]
fn attest_key_op_from_proto() {
let op_attested_key_name = String::from("attested key name");
let op_attesting_key_name = String::from("attesting key name");
let op_credential_blob = vec![0xaa; 32];
let op_secret = vec![0x11; 16];
let proto = OperationProto {
attested_key_name: op_attested_key_name.clone(),
attesting_key_name: op_attesting_key_name.clone(),
parameters: Some(AttestationMechanismParams {
mechanism: Some(attestation_mechanism_params::Mechanism::ActivateCredential(
attestation_mechanism_params::ActivateCredential {
credential_blob: op_credential_blob.clone(),
secret: op_secret.clone(),
},
)),
}),
};
let op: Operation = proto.try_into().expect("Failed conversion");
let Operation::ActivateCredential {
attested_key_name,
attesting_key_name,
credential_blob,
secret,
} = op;
assert_eq!(attested_key_name, op_attested_key_name);
assert_eq!(
attesting_key_name.unwrap_or_default(),
op_attesting_key_name
);
assert_eq!(credential_blob.to_vec(), op_credential_blob);
assert_eq!(secret.to_vec(), op_secret);
}
#[test]
fn attest_key_proto_no_attesting() {
let op_attested_key_name = String::from("attested key name");
let op_credential_blob = vec![0xaa; 32];
let op_secret = vec![0x11; 16];
let proto = OperationProto {
attested_key_name: op_attested_key_name,
attesting_key_name: String::new(),
parameters: Some(AttestationMechanismParams {
mechanism: Some(attestation_mechanism_params::Mechanism::ActivateCredential(
attestation_mechanism_params::ActivateCredential {
credential_blob: op_credential_blob,
secret: op_secret,
},
)),
}),
};
let op: Operation = proto.try_into().expect("Failed conversion");
let Operation::ActivateCredential {
attesting_key_name, ..
} = op;
assert!(attesting_key_name.is_none());
}
#[test]
fn attest_key_proto_from_op() {
let op_attested_key_name = String::from("attested key name");
let op_attesting_key_name = String::from("attesting key name");
let op_credential_blob = vec![0xaa; 32];
let op_secret = vec![0x11; 16];
let op = Operation::ActivateCredential {
attested_key_name: op_attested_key_name.clone(),
attesting_key_name: Some(op_attesting_key_name.clone()),
credential_blob: op_credential_blob.clone().into(),
secret: op_secret.clone().into(),
};
let proto: OperationProto = op.try_into().expect("Failed conversion");
if let OperationProto {
attested_key_name,
attesting_key_name,
parameters:
Some(AttestationMechanismParams {
mechanism:
Some(attestation_mechanism_params::Mechanism::ActivateCredential(
attestation_mechanism_params::ActivateCredential {
credential_blob,
secret,
},
)),
}),
} = proto
{
assert_eq!(attested_key_name, op_attested_key_name);
assert_eq!(attesting_key_name, op_attesting_key_name);
assert_eq!(credential_blob, op_credential_blob);
assert_eq!(secret, op_secret);
}
}
#[test]
fn attest_key_op_no_attesting() {
let op_attested_key_name = String::from("attested key name");
let op_credential_blob = vec![0xaa; 32];
let op_secret = vec![0x11; 16];
let op = Operation::ActivateCredential {
attested_key_name: op_attested_key_name,
attesting_key_name: None,
credential_blob: op_credential_blob.into(),
secret: op_secret.into(),
};
let proto: OperationProto = op.try_into().expect("Failed conversion");
assert_eq!(proto.attesting_key_name, String::new());
}
#[test]
fn attest_key_op_e2e() {
let op_attested_key_name = String::from("attested key name");
let op_attesting_key_name = String::from("attesting key name");
let op_credential_blob = vec![0xaa; 32];
let op_secret = vec![0x11; 16];
let op = Operation::ActivateCredential {
attested_key_name: op_attested_key_name,
attesting_key_name: Some(op_attesting_key_name),
credential_blob: op_credential_blob.into(),
secret: op_secret.into(),
};
let body = CONVERTER
.operation_to_body(NativeOperation::AttestKey(op))
.expect("Failed to convert to body");
let _ = CONVERTER
.body_to_operation(body, Opcode::AttestKey)
.expect("Failed to convert to operation");
}
#[test]
fn attest_key_resp_from_proto() {
let resp_credential = vec![0xbb; 32];
let proto = ResultProto {
output: Some(AttestationOutput {
mechanism: Some(attestation_output::Mechanism::ActivateCredential(
attestation_output::ActivateCredential {
credential: resp_credential.clone(),
},
)),
}),
};
let resp: Result = proto.try_into().expect("Failed conversion");
let Result::ActivateCredential { credential } = resp;
assert_eq!(credential.to_vec(), resp_credential);
}
#[test]
fn attest_key_resp_to_proto() {
let resp_credential = vec![0xbb; 32];
let resp = Result::ActivateCredential {
credential: resp_credential.clone().into(),
};
let proto: ResultProto = resp.try_into().expect("Failed conversion");
if let ResultProto {
output:
Some(AttestationOutput {
mechanism:
Some(attestation_output::Mechanism::ActivateCredential(
attestation_output::ActivateCredential { credential },
)),
}),
} = proto
{
assert_eq!(credential.to_vec(), resp_credential);
}
}
#[test]
fn attest_key_resp_e2e() {
let resp_credential = vec![0xbb; 32];
let resp = Result::ActivateCredential {
credential: resp_credential.into(),
};
let body = CONVERTER
.result_to_body(NativeResult::AttestKey(resp))
.expect("Failed to convert to body");
let _ = CONVERTER
.body_to_result(body, Opcode::AttestKey)
.expect("Failed to convert to operation");
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_can_do_crypto.rs 0000644 0000000 0000000 00000014341 10461020230 0024756 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::can_do_crypto::{
CheckType as CheckTypeProto, Operation as OperationProto, Result as ResultProto,
};
use crate::operations::can_do_crypto::{CheckType, Operation, Result};
use crate::requests::ResponseStatus;
use log::error;
use std::convert::{TryFrom, TryInto};
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(proto_op: OperationProto) -> std::result::Result {
let key_attributes = proto_op.attributes.ok_or_else(|| {
error!("The attributes field of CanDoCrypto::Operation message is not set (mandatory field).");
ResponseStatus::InvalidEncoding
})?;
Ok(Operation {
check_type: i32_to_check_type(proto_op.check_type)?,
attributes: key_attributes.try_into()?,
})
}
}
impl TryFrom for OperationProto {
type Error = ResponseStatus;
fn try_from(op: Operation) -> std::result::Result {
Ok(OperationProto {
check_type: check_type_to_i32(op.check_type),
attributes: Some(op.attributes.try_into()?),
})
}
}
impl TryFrom for ResultProto {
type Error = ResponseStatus;
fn try_from(_result: Result) -> std::result::Result {
Ok(ResultProto {})
}
}
impl TryFrom for Result {
type Error = ResponseStatus;
fn try_from(_response: ResultProto) -> std::result::Result {
Ok(Result {})
}
}
// CheckType: from protobuf to native
impl TryFrom for CheckType {
type Error = ResponseStatus;
fn try_from(check_type_proto_val: CheckTypeProto) -> std::result::Result {
match check_type_proto_val {
CheckTypeProto::ChecktypeNone => Err(ResponseStatus::InvalidEncoding),
CheckTypeProto::Use => Ok(CheckType::Use),
CheckTypeProto::Generate => Ok(CheckType::Generate),
CheckTypeProto::Import => Ok(CheckType::Import),
CheckTypeProto::Derive => Ok(CheckType::Derive),
}
}
}
// CheckType: from native to protobuf
impl TryFrom for CheckTypeProto {
type Error = ResponseStatus;
fn try_from(check_type_val: CheckType) -> std::result::Result {
match check_type_val {
CheckType::Use => Ok(CheckTypeProto::Use),
CheckType::Generate => Ok(CheckTypeProto::Generate),
CheckType::Import => Ok(CheckTypeProto::Import),
CheckType::Derive => Ok(CheckTypeProto::Derive),
}
}
}
// CheckType from protobuf to native
pub fn i32_to_check_type(check_type_val: i32) -> std::result::Result {
let check_type_proto: CheckTypeProto = check_type_val.try_into()?;
check_type_proto.try_into()
}
// CheckType from native to protobuf
pub fn check_type_to_i32(check_type: CheckType) -> i32 {
match check_type {
CheckType::Use => CheckTypeProto::Use.into(),
CheckType::Generate => CheckTypeProto::Generate.into(),
CheckType::Import => CheckTypeProto::Import.into(),
CheckType::Derive => CheckTypeProto::Derive.into(),
}
}
#[cfg(test)]
mod test {
use super::super::generated_ops::can_do_crypto::Operation as OperationProto;
use crate::operations::can_do_crypto::{CheckType, Operation};
use crate::operations::psa_algorithm::{Algorithm, AsymmetricSignature, Hash};
use crate::operations::psa_key_attributes::{self, Attributes, Lifetime, Policy, UsageFlags};
use crate::operations_protobuf::convert_can_do_crypto::check_type_to_i32;
use std::convert::TryInto;
#[test]
fn proto_to_resp() {
let mut usage_flags: UsageFlags = Default::default();
let _ = usage_flags
.set_export()
.set_copy()
.set_cache()
.set_encrypt()
.set_decrypt()
.set_sign_message()
.set_verify_message()
.set_sign_hash()
.set_verify_hash()
.set_derive();
let key_attrs = Attributes {
lifetime: Lifetime::Persistent,
key_type: psa_key_attributes::Type::RsaKeyPair,
bits: 1024,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(
AsymmetricSignature::RsaPkcs1v15Sign {
hash_alg: Hash::Sha1.into(),
},
),
},
};
let proto = OperationProto {
check_type: check_type_to_i32(CheckType::Use),
attributes: Some(key_attrs.try_into().expect("Failed conversion")),
};
let resp: Operation = proto.try_into().expect("Failed conversion");
assert_eq!(resp.check_type, CheckType::Use);
assert_eq!(resp.attributes, key_attrs);
}
#[test]
fn resp_to_proto() {
let mut usage_flags: UsageFlags = Default::default();
let _ = usage_flags
.set_export()
.set_copy()
.set_cache()
.set_encrypt()
.set_decrypt()
.set_sign_message()
.set_verify_message()
.set_sign_hash()
.set_verify_hash()
.set_derive();
let key_attrs = Attributes {
lifetime: Lifetime::Persistent,
key_type: psa_key_attributes::Type::RsaKeyPair,
bits: 1024,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(
AsymmetricSignature::RsaPkcs1v15Sign {
hash_alg: Hash::Sha1.into(),
},
),
},
};
let resp: Operation = Operation {
check_type: CheckType::Use,
attributes: key_attrs,
};
let proto: OperationProto = resp.try_into().expect("Failed conversion");
assert_eq!(proto.check_type, check_type_to_i32(CheckType::Use));
assert_eq!(
proto.attributes.expect("Failed conversion"),
key_attrs.try_into().expect("Failed conversion")
);
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_delete_client.rs 0000644 0000000 0000000 00000002570 10461020230 0024734 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::delete_client::{Operation as OperationProto, Result as ResultProto};
use crate::operations::delete_client::{Operation, Result};
impl From for Operation {
fn from(proto_op: OperationProto) -> Self {
Operation {
client: proto_op.client,
}
}
}
impl From for OperationProto {
fn from(op: Operation) -> Self {
OperationProto { client: op.client }
}
}
impl From for Result {
fn from(_proto_op: ResultProto) -> Self {
Result {}
}
}
impl From for ResultProto {
fn from(_op: Result) -> Self {
ResultProto {}
}
}
#[cfg(test)]
mod test {
use super::super::generated_ops::delete_client::Operation as OperationProto;
use crate::operations::delete_client::Operation;
#[test]
fn proto_to_resp() {
let proto = OperationProto {
client: String::from("toto"),
};
let resp: Operation = proto.into();
assert_eq!(resp.client, String::from("toto"));
}
#[test]
fn resp_to_proto() {
let resp: Operation = Operation {
client: String::from("toto"),
};
let proto: OperationProto = resp.into();
assert_eq!(proto.client, String::from("toto"));
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_list_authenticators.rs 0000644 0000000 0000000 00000020735 10461020230 0026227 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::list_authenticators::{
AuthenticatorInfo as AuthenticatorInfoProto, Operation as OperationProto, Result as ResultProto,
};
use crate::operations::list_authenticators::{AuthenticatorInfo, Operation, Result};
use crate::requests::{AuthType, ResponseStatus};
use num::FromPrimitive;
use std::convert::{TryFrom, TryInto};
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(_proto_op: OperationProto) -> std::result::Result {
Ok(Operation {})
}
}
impl TryFrom for OperationProto {
type Error = ResponseStatus;
fn try_from(_op: Operation) -> std::result::Result {
Ok(Default::default())
}
}
impl TryFrom for AuthenticatorInfo {
type Error = ResponseStatus;
fn try_from(proto_info: AuthenticatorInfoProto) -> std::result::Result {
let id: AuthType = match FromPrimitive::from_u32(proto_info.id) {
Some(id) => id,
None => return Err(ResponseStatus::AuthenticatorDoesNotExist),
};
Ok(AuthenticatorInfo {
description: proto_info.description,
version_maj: proto_info.version_maj,
version_min: proto_info.version_min,
version_rev: proto_info.version_rev,
id,
})
}
}
impl TryFrom for AuthenticatorInfoProto {
type Error = ResponseStatus;
fn try_from(info: AuthenticatorInfo) -> std::result::Result {
Ok(AuthenticatorInfoProto {
description: info.description,
version_maj: info.version_maj,
version_min: info.version_min,
version_rev: info.version_rev,
id: info.id as u32,
})
}
}
impl TryFrom for Result {
type Error = ResponseStatus;
fn try_from(proto_op: ResultProto) -> std::result::Result {
let mut authenticators: Vec = Vec::new();
for authenticator in proto_op.authenticators {
authenticators.push(authenticator.try_into()?);
}
Ok(Result { authenticators })
}
}
impl TryFrom for ResultProto {
type Error = ResponseStatus;
fn try_from(op: Result) -> std::result::Result {
let mut authenticators: Vec = Vec::new();
for authenticator in op.authenticators {
authenticators.push(authenticator.try_into()?);
}
Ok(ResultProto { authenticators })
}
}
#[cfg(test)]
mod test {
// Operation <-> Proto conversions are not tested since they're too simple
use super::super::generated_ops::list_authenticators::{
AuthenticatorInfo as AuthenticatorInfoProto, Result as ResultProto,
};
use super::super::{Convert, ProtobufConverter};
use crate::operations::list_authenticators::{AuthenticatorInfo, Operation, Result};
use crate::operations::{NativeOperation, NativeResult};
use crate::requests::{request::RequestBody, response::ResponseBody, AuthType, Opcode};
use std::convert::TryInto;
static CONVERTER: ProtobufConverter = ProtobufConverter {};
#[test]
fn proto_to_resp() {
let mut proto: ResultProto = Default::default();
let authenticator_info = AuthenticatorInfoProto {
description: String::from("authenticator description"),
version_maj: 0,
version_min: 1,
version_rev: 0,
id: AuthType::Direct as u32,
};
proto.authenticators.push(authenticator_info);
let resp: Result = proto.try_into().unwrap();
assert_eq!(resp.authenticators.len(), 1);
assert_eq!(
resp.authenticators[0].description,
"authenticator description"
);
assert_eq!(resp.authenticators[0].version_maj, 0);
assert_eq!(resp.authenticators[0].version_min, 1);
assert_eq!(resp.authenticators[0].version_rev, 0);
assert_eq!(resp.authenticators[0].id, AuthType::Direct);
}
#[test]
fn resp_to_proto() {
let mut resp: Result = Result {
authenticators: Vec::new(),
};
let authenticator_info = AuthenticatorInfo {
description: String::from("authenticator description"),
version_maj: 0,
version_min: 1,
version_rev: 0,
id: AuthType::Direct,
};
resp.authenticators.push(authenticator_info);
let proto: ResultProto = resp.try_into().unwrap();
assert_eq!(proto.authenticators.len(), 1);
assert_eq!(
proto.authenticators[0].description,
"authenticator description"
);
assert_eq!(proto.authenticators[0].version_maj, 0);
assert_eq!(proto.authenticators[0].version_min, 1);
assert_eq!(proto.authenticators[0].version_rev, 0);
assert_eq!(proto.authenticators[0].id, AuthType::Direct as u32);
}
#[test]
fn list_authenticators_req_to_native() {
let req_body = RequestBody::from_bytes(Vec::new());
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListAuthenticators)
.is_ok());
}
#[test]
fn op_list_authenticators_from_native() {
let list_authenticators = Operation {};
let body = CONVERTER
.operation_to_body(NativeOperation::ListAuthenticators(list_authenticators))
.expect("Failed to convert request");
assert!(body.is_empty());
}
#[test]
fn op_list_authenticators_e2e() {
let list_authenticators = Operation {};
let req_body = CONVERTER
.operation_to_body(NativeOperation::ListAuthenticators(list_authenticators))
.expect("Failed to convert request");
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListAuthenticators)
.is_ok());
}
#[test]
fn req_from_native_mangled_body() {
let req_body =
RequestBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListAuthenticators)
.is_err());
}
#[test]
fn list_authenticators_body_to_native() {
let resp_body = ResponseBody::from_bytes(Vec::new());
assert!(CONVERTER
.body_to_result(resp_body, Opcode::ListAuthenticators)
.is_ok());
}
#[test]
fn result_list_authenticators_from_native() {
let mut list_authenticators = Result {
authenticators: Vec::new(),
};
let authenticator_info = AuthenticatorInfo {
description: String::from("authenticator description"),
version_maj: 0,
version_min: 1,
version_rev: 0,
id: AuthType::Direct,
};
list_authenticators.authenticators.push(authenticator_info);
let body = CONVERTER
.result_to_body(NativeResult::ListAuthenticators(list_authenticators))
.expect("Failed to convert response");
assert!(!body.is_empty());
}
#[test]
fn list_authenticators_result_e2e() {
let mut list_authenticators = Result {
authenticators: Vec::new(),
};
let authenticator_info = AuthenticatorInfo {
description: String::from("authenticator description"),
version_maj: 0,
version_min: 1,
version_rev: 0,
id: AuthType::Direct,
};
list_authenticators.authenticators.push(authenticator_info);
let body = CONVERTER
.result_to_body(NativeResult::ListAuthenticators(list_authenticators))
.expect("Failed to convert response");
assert!(!body.is_empty());
let result = CONVERTER
.body_to_result(body, Opcode::ListAuthenticators)
.expect("Failed to convert back to result");
match result {
NativeResult::ListAuthenticators(result) => {
assert_eq!(result.authenticators.len(), 1);
}
_ => panic!("Expected list_authenticators"),
}
}
#[test]
fn resp_from_native_mangled_body() {
let resp_body =
ResponseBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_result(resp_body, Opcode::ListAuthenticators)
.is_err());
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_list_clients.rs 0000644 0000000 0000000 00000002761 10461020230 0024632 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::list_clients::{Operation as OperationProto, Result as ResultProto};
use crate::operations::list_clients::{Operation, Result};
impl From for Operation {
fn from(_proto_op: OperationProto) -> Self {
Operation {}
}
}
impl From for OperationProto {
fn from(_op: Operation) -> Self {
Default::default()
}
}
impl From for Result {
fn from(proto_op: ResultProto) -> Self {
Result {
clients: proto_op.clients,
}
}
}
impl From for ResultProto {
fn from(op: Result) -> Self {
ResultProto {
clients: op.clients,
}
}
}
#[cfg(test)]
mod test {
use super::super::generated_ops::list_clients::Result as ResultProto;
use crate::operations::list_clients::Result;
#[test]
fn proto_to_resp() {
let mut proto: ResultProto = Default::default();
proto.clients.push(String::from("toto"));
let resp: Result = proto.into();
assert_eq!(resp.clients.len(), 1);
assert_eq!(resp.clients[0], String::from("toto"));
}
#[test]
fn resp_to_proto() {
let resp: Result = Result {
clients: vec![String::from("toto")],
};
let proto: ResultProto = resp.into();
assert_eq!(proto.clients.len(), 1);
assert_eq!(proto.clients[0], String::from("toto"));
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_list_keys.rs 0000644 0000000 0000000 00000025757 10461020230 0024156 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::list_keys::{
KeyInfo as KeyInfoProto, Operation as OperationProto, Result as ResultProto,
};
use crate::operations::list_keys::{KeyInfo, Operation, Result};
use crate::requests::{ProviderId, ResponseStatus};
use log::error;
use num::FromPrimitive;
use std::convert::{TryFrom, TryInto};
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(_proto_op: OperationProto) -> std::result::Result {
Ok(Operation {})
}
}
impl TryFrom for OperationProto {
type Error = ResponseStatus;
fn try_from(_op: Operation) -> std::result::Result {
Ok(Default::default())
}
}
impl TryFrom for KeyInfo {
type Error = ResponseStatus;
fn try_from(proto_info: KeyInfoProto) -> std::result::Result {
let id: ProviderId = match FromPrimitive::from_u32(proto_info.provider_id) {
Some(id) => id,
None => return Err(ResponseStatus::ProviderDoesNotExist),
};
let attributes = proto_info
.attributes
.ok_or_else(|| {
error!("The attributes field of KeyInfo protobuf message is not set (mandatory field).");
ResponseStatus::InvalidEncoding
})?
.try_into()?;
Ok(KeyInfo {
provider_id: id,
name: proto_info.name,
attributes,
})
}
}
impl TryFrom for KeyInfoProto {
type Error = ResponseStatus;
fn try_from(info: KeyInfo) -> std::result::Result {
Ok(KeyInfoProto {
provider_id: info.provider_id as u32,
name: info.name,
attributes: Some(info.attributes.try_into()?),
})
}
}
impl TryFrom for Result {
type Error = ResponseStatus;
fn try_from(proto_op: ResultProto) -> std::result::Result {
let mut keys: Vec = Vec::new();
for key in proto_op.keys {
keys.push(key.try_into()?);
}
Ok(Result { keys })
}
}
impl TryFrom for ResultProto {
type Error = ResponseStatus;
fn try_from(op: Result) -> std::result::Result {
let mut keys: Vec = Vec::new();
for key in op.keys {
keys.push(key.try_into()?);
}
Ok(ResultProto { keys })
}
}
#[cfg(test)]
mod test {
// Operation <-> Proto conversions are not tested since they're too simple
use super::super::generated_ops::list_keys::{KeyInfo as KeyInfoProto, Result as ResultProto};
use super::super::generated_ops::psa_key_attributes::KeyAttributes as KeyAttributesProto;
use super::super::{Convert, ProtobufConverter};
use crate::operations::list_keys::{KeyInfo, Operation, Result};
use crate::operations::psa_algorithm::{Algorithm, AsymmetricSignature, Hash};
use crate::operations::psa_key_attributes::{self, Attributes, Lifetime, Policy, UsageFlags};
use crate::operations::{NativeOperation, NativeResult};
use crate::requests::{request::RequestBody, response::ResponseBody, Opcode, ProviderId};
use std::convert::TryInto;
static CONVERTER: ProtobufConverter = ProtobufConverter {};
#[test]
fn proto_to_resp() {
let mut proto: ResultProto = Default::default();
let mut usage_flags = UsageFlags::default();
let _ = usage_flags
.set_decrypt()
.set_export()
.set_copy()
.set_cache()
.set_encrypt()
.set_decrypt()
.set_sign_message()
.set_verify_message()
.set_sign_hash()
.set_verify_hash()
.set_derive();
let key_attrs = Attributes {
lifetime: Lifetime::Persistent,
key_type: psa_key_attributes::Type::RsaKeyPair,
bits: 1024,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(
AsymmetricSignature::RsaPkcs1v15Sign {
hash_alg: Hash::Sha1.into(),
},
),
},
};
let key_attrs_proto: KeyAttributesProto = key_attrs.try_into().unwrap();
let key_info = KeyInfoProto {
provider_id: ProviderId::MbedCrypto as u32,
name: String::from("Some Key Name"),
attributes: Some(key_attrs_proto),
};
proto.keys.push(key_info);
let resp: Result = proto.try_into().unwrap();
assert_eq!(resp.keys.len(), 1);
assert_eq!(resp.keys[0].name, "Some Key Name");
assert_eq!(resp.keys[0].provider_id, ProviderId::MbedCrypto);
assert_eq!(resp.keys[0].attributes, key_attrs);
}
#[test]
fn resp_to_proto() {
let mut resp: Result = Result { keys: Vec::new() };
let mut usage_flags = UsageFlags::default();
let _ = usage_flags
.set_decrypt()
.set_export()
.set_copy()
.set_cache()
.set_encrypt()
.set_decrypt()
.set_sign_message()
.set_verify_message()
.set_sign_hash()
.set_verify_hash()
.set_derive();
let key_attributes = Attributes {
lifetime: Lifetime::Persistent,
key_type: psa_key_attributes::Type::RsaKeyPair,
bits: 1024,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(
AsymmetricSignature::RsaPkcs1v15Sign {
hash_alg: Hash::Sha1.into(),
},
),
},
};
let key_info = KeyInfo {
provider_id: ProviderId::MbedCrypto,
name: String::from("Foo"),
attributes: key_attributes,
};
resp.keys.push(key_info);
let proto: ResultProto = resp.try_into().unwrap();
let key_attributes_proto: KeyAttributesProto = key_attributes.try_into().unwrap();
assert_eq!(proto.keys.len(), 1);
assert_eq!(proto.keys[0].provider_id, ProviderId::MbedCrypto as u32);
assert_eq!(proto.keys[0].name, "Foo");
assert_eq!(proto.keys[0].attributes, Some(key_attributes_proto));
}
#[test]
fn list_keys_req_to_native() {
let req_body = RequestBody::from_bytes(Vec::new());
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListKeys)
.is_ok());
}
#[test]
fn op_list_keys_from_native() {
let list_keys = Operation {};
let body = CONVERTER
.operation_to_body(NativeOperation::ListKeys(list_keys))
.expect("Failed to convert request");
assert!(body.is_empty());
}
#[test]
fn op_list_keys_e2e() {
let list_keys = Operation {};
let req_body = CONVERTER
.operation_to_body(NativeOperation::ListKeys(list_keys))
.expect("Failed to convert request");
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListKeys)
.is_ok());
}
#[test]
fn req_from_native_mangled_body() {
let req_body =
RequestBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListKeys)
.is_err());
}
#[test]
fn list_keys_body_to_native() {
let resp_body = ResponseBody::from_bytes(Vec::new());
assert!(CONVERTER
.body_to_result(resp_body, Opcode::ListKeys)
.is_ok());
}
#[test]
fn result_list_keys_from_native() {
let mut list_keys = Result { keys: Vec::new() };
let mut usage_flags = UsageFlags::default();
let _ = usage_flags
.set_decrypt()
.set_export()
.set_copy()
.set_cache()
.set_encrypt()
.set_decrypt()
.set_sign_message()
.set_verify_message()
.set_sign_hash()
.set_verify_hash()
.set_derive();
let key_info = KeyInfo {
provider_id: ProviderId::MbedCrypto,
name: String::from("Bar"),
attributes: Attributes {
lifetime: Lifetime::Persistent,
key_type: psa_key_attributes::Type::RsaKeyPair,
bits: 1024,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(
AsymmetricSignature::RsaPkcs1v15Sign {
hash_alg: Hash::Sha1.into(),
},
),
},
},
};
list_keys.keys.push(key_info);
let body = CONVERTER
.result_to_body(NativeResult::ListKeys(list_keys))
.expect("Failed to convert response");
assert!(!body.is_empty());
}
#[test]
fn list_keys_result_e2e() {
let mut usage_flags = UsageFlags::default();
let _ = usage_flags
.set_decrypt()
.set_export()
.set_copy()
.set_cache()
.set_encrypt()
.set_decrypt()
.set_sign_message()
.set_verify_message()
.set_sign_hash()
.set_verify_hash()
.set_derive();
let mut list_keys = Result { keys: Vec::new() };
let key_info = KeyInfo {
provider_id: ProviderId::MbedCrypto,
name: String::from("Baz"),
attributes: Attributes {
lifetime: Lifetime::Persistent,
key_type: psa_key_attributes::Type::RsaKeyPair,
bits: 1024,
policy: Policy {
usage_flags,
permitted_algorithms: Algorithm::AsymmetricSignature(
AsymmetricSignature::RsaPkcs1v15Sign {
hash_alg: Hash::Sha1.into(),
},
),
},
},
};
list_keys.keys.push(key_info);
let body = CONVERTER
.result_to_body(NativeResult::ListKeys(list_keys))
.expect("Failed to convert response");
assert!(!body.is_empty());
let result = CONVERTER
.body_to_result(body, Opcode::ListKeys)
.expect("Failed to convert back to result");
match result {
NativeResult::ListKeys(result) => {
assert_eq!(result.keys.len(), 1);
}
_ => panic!("Expected list_keys"),
}
}
#[test]
fn resp_from_native_mangled_body() {
let resp_body =
ResponseBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_result(resp_body, Opcode::ListKeys)
.is_err());
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_list_opcodes.rs 0000644 0000000 0000000 00000013701 10461020230 0024621 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::list_opcodes::{Operation as OperationProto, Result as ResultProto};
use crate::operations::list_opcodes::{Operation, Result};
use crate::requests::{Opcode, ResponseStatus};
use log::error;
use num::FromPrimitive;
use std::collections::HashSet;
use std::convert::TryFrom;
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(proto_op: OperationProto) -> std::result::Result {
match FromPrimitive::from_u32(proto_op.provider_id) {
None => {
error!("Invalid provider ID: {}", proto_op.provider_id);
Err(ResponseStatus::ProviderDoesNotExist)
}
Some(provider_id) => Ok(Operation { provider_id }),
}
}
}
impl TryFrom for OperationProto {
type Error = ResponseStatus;
fn try_from(op: Operation) -> std::result::Result {
Ok(OperationProto {
provider_id: op.provider_id as u32,
})
}
}
impl TryFrom for Result {
type Error = ResponseStatus;
fn try_from(proto_op: ResultProto) -> std::result::Result {
let mut opcodes: HashSet = HashSet::new();
for opcode in proto_op.opcodes {
let opcode = match FromPrimitive::from_u32(opcode) {
Some(code) => code,
None => return Err(ResponseStatus::OpcodeDoesNotExist),
};
let _ = opcodes.insert(opcode);
}
Ok(Result { opcodes })
}
}
impl TryFrom for ResultProto {
type Error = ResponseStatus;
fn try_from(op: Result) -> std::result::Result {
let mut opcodes: Vec = Vec::new();
for opcode in op.opcodes {
opcodes.push(opcode as u32);
}
Ok(ResultProto { opcodes })
}
}
#[cfg(test)]
mod test {
// Operation <-> Proto conversions are not tested since they're too simple
use super::super::generated_ops::list_opcodes::Result as ResultProto;
use super::super::{Convert, ProtobufConverter};
use crate::operations::{
list_opcodes::Operation, list_opcodes::Result, NativeOperation, NativeResult,
};
use crate::requests::{request::RequestBody, response::ResponseBody, Opcode, ProviderId};
use std::collections::HashSet;
use std::convert::TryInto;
static CONVERTER: ProtobufConverter = ProtobufConverter {};
#[test]
fn proto_to_resp() {
let mut proto: ResultProto = Default::default();
proto.opcodes.push(1);
let resp: Result = proto.try_into().unwrap();
assert_eq!(resp.opcodes.len(), 1);
assert!(resp.opcodes.contains(&Opcode::Ping));
}
#[test]
fn resp_to_proto() {
let mut resp: Result = Result {
opcodes: HashSet::new(),
};
let _ = resp.opcodes.insert(Opcode::Ping);
let proto: ResultProto = resp.try_into().unwrap();
assert_eq!(proto.opcodes.len(), 1);
assert_eq!(proto.opcodes[0], 1);
}
#[test]
fn list_opcodes_req_to_native() {
let req_body = RequestBody::from_bytes(Vec::new());
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListOpcodes)
.is_ok());
}
#[test]
fn op_list_opcodes_from_native() {
let list_opcodes = Operation {
provider_id: ProviderId::Core,
};
let body = CONVERTER
.operation_to_body(NativeOperation::ListOpcodes(list_opcodes))
.expect("Failed to convert request");
assert!(body.is_empty());
}
#[test]
fn op_list_opcodes_e2e() {
let list_opcodes = Operation {
provider_id: ProviderId::Pkcs11,
};
let req_body = CONVERTER
.operation_to_body(NativeOperation::ListOpcodes(list_opcodes))
.expect("Failed to convert request");
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListOpcodes)
.is_ok());
}
#[test]
fn req_from_native_mangled_body() {
let req_body =
RequestBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListOpcodes)
.is_err());
}
#[test]
fn list_opcodes_body_to_native() {
let resp_body = ResponseBody::from_bytes(Vec::new());
assert!(CONVERTER
.body_to_result(resp_body, Opcode::ListOpcodes)
.is_ok());
}
#[test]
fn result_list_opcodes_from_native() {
let mut list_opcodes = Result {
opcodes: HashSet::new(),
};
let _ = list_opcodes.opcodes.insert(Opcode::Ping);
let body = CONVERTER
.result_to_body(NativeResult::ListOpcodes(list_opcodes))
.expect("Failed to convert response");
assert!(!body.is_empty());
}
#[test]
fn list_opcodes_result_e2e() {
let mut list_opcodes = Result {
opcodes: HashSet::new(),
};
let _ = list_opcodes.opcodes.insert(Opcode::Ping);
let body = CONVERTER
.result_to_body(NativeResult::ListOpcodes(list_opcodes))
.expect("Failed to convert response");
assert!(!body.is_empty());
let result = CONVERTER
.body_to_result(body, Opcode::ListOpcodes)
.expect("Failed to convert back to result");
match result {
NativeResult::ListOpcodes(result) => {
assert_eq!(result.opcodes.len(), 1);
}
_ => panic!("Expected list_opcodes"),
}
}
#[test]
fn resp_from_native_mangled_body() {
let resp_body =
ResponseBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_result(resp_body, Opcode::ListOpcodes)
.is_err());
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_list_providers.rs 0000644 0000000 0000000 00000022353 10461020230 0025205 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::list_providers::{
Operation as OperationProto, ProviderInfo as ProviderInfoProto, Result as ResultProto,
};
use crate::operations::list_providers::{Operation, ProviderInfo, Result};
use crate::requests::{ProviderId, ResponseStatus};
use num::FromPrimitive;
use std::convert::{TryFrom, TryInto};
use uuid::Uuid;
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(_proto_op: OperationProto) -> std::result::Result {
Ok(Operation {})
}
}
impl TryFrom for OperationProto {
type Error = ResponseStatus;
fn try_from(_op: Operation) -> std::result::Result {
Ok(Default::default())
}
}
impl TryFrom for ProviderInfo {
type Error = ResponseStatus;
fn try_from(proto_info: ProviderInfoProto) -> std::result::Result {
// UUIDs are strings of 36 ASCII characters (bytes) containing 32 lowercase hexadecimal
// digits and 4 hyphens.
let provider_uuid = match Uuid::parse_str(&proto_info.uuid) {
Ok(provider_uuid) => provider_uuid,
Err(_) => return Err(ResponseStatus::WrongProviderUuid),
};
let id: ProviderId = match FromPrimitive::from_u32(proto_info.id) {
Some(id) => id,
None => return Err(ResponseStatus::ProviderDoesNotExist),
};
Ok(ProviderInfo {
uuid: provider_uuid,
description: proto_info.description,
vendor: proto_info.vendor,
version_maj: proto_info.version_maj,
version_min: proto_info.version_min,
version_rev: proto_info.version_rev,
id,
})
}
}
impl TryFrom for ProviderInfoProto {
type Error = ResponseStatus;
fn try_from(info: ProviderInfo) -> std::result::Result {
Ok(ProviderInfoProto {
uuid: info.uuid.to_string(),
description: info.description,
vendor: info.vendor,
version_maj: info.version_maj,
version_min: info.version_min,
version_rev: info.version_rev,
id: info.id as u32,
})
}
}
impl TryFrom for Result {
type Error = ResponseStatus;
fn try_from(proto_op: ResultProto) -> std::result::Result {
let mut providers: Vec = Vec::new();
for provider in proto_op.providers {
providers.push(provider.try_into()?);
}
Ok(Result { providers })
}
}
impl TryFrom for ResultProto {
type Error = ResponseStatus;
fn try_from(op: Result) -> std::result::Result {
let mut providers: Vec = Vec::new();
for provider in op.providers {
providers.push(provider.try_into()?);
}
Ok(ResultProto { providers })
}
}
#[cfg(test)]
mod test {
// Operation <-> Proto conversions are not tested since they're too simple
use super::super::generated_ops::list_providers::{
ProviderInfo as ProviderInfoProto, Result as ResultProto,
};
use super::super::{Convert, ProtobufConverter};
use crate::operations::list_providers::{Operation, ProviderInfo, Result};
use crate::operations::{NativeOperation, NativeResult};
use crate::requests::{request::RequestBody, response::ResponseBody, Opcode, ProviderId};
use std::convert::TryInto;
use uuid::Uuid;
static CONVERTER: ProtobufConverter = ProtobufConverter {};
#[test]
fn proto_to_resp() {
let mut proto: ResultProto = Default::default();
let provider_info = ProviderInfoProto {
uuid: String::from("9840cd61-9367-4010-bc24-f5b98a6174d1"),
description: String::from("provider description"),
vendor: String::from("Arm"),
version_maj: 0,
version_min: 1,
version_rev: 0,
id: 1,
};
proto.providers.push(provider_info);
let resp: Result = proto.try_into().unwrap();
assert_eq!(resp.providers.len(), 1);
assert_eq!(
resp.providers[0].uuid,
Uuid::parse_str("9840CD6193674010BC24F5B98A6174D1").unwrap()
);
assert_eq!(resp.providers[0].description, "provider description");
assert_eq!(resp.providers[0].vendor, "Arm");
assert_eq!(resp.providers[0].version_maj, 0);
assert_eq!(resp.providers[0].version_min, 1);
assert_eq!(resp.providers[0].version_rev, 0);
assert_eq!(resp.providers[0].id, ProviderId::MbedCrypto);
}
#[test]
fn resp_to_proto() {
let mut resp: Result = Result {
providers: Vec::new(),
};
let provider_info = ProviderInfo {
uuid: Uuid::parse_str("9840CD6193674010BC24F5B98A6174D1").unwrap(),
description: String::from("provider description"),
vendor: String::from("Arm"),
version_maj: 0,
version_min: 1,
version_rev: 0,
id: ProviderId::MbedCrypto,
};
resp.providers.push(provider_info);
let proto: ResultProto = resp.try_into().unwrap();
assert_eq!(proto.providers.len(), 1);
assert_eq!(
proto.providers[0].uuid,
"9840cd61-9367-4010-bc24-f5b98a6174d1"
);
assert_eq!(proto.providers[0].description, "provider description");
assert_eq!(proto.providers[0].vendor, "Arm");
assert_eq!(proto.providers[0].version_maj, 0);
assert_eq!(proto.providers[0].version_min, 1);
assert_eq!(proto.providers[0].version_rev, 0);
assert_eq!(proto.providers[0].id, 1);
}
#[test]
fn list_providers_req_to_native() {
let req_body = RequestBody::from_bytes(Vec::new());
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListProviders)
.is_ok());
}
#[test]
fn op_list_providers_from_native() {
let list_providers = Operation {};
let body = CONVERTER
.operation_to_body(NativeOperation::ListProviders(list_providers))
.expect("Failed to convert request");
assert!(body.is_empty());
}
#[test]
fn op_list_providers_e2e() {
let list_providers = Operation {};
let req_body = CONVERTER
.operation_to_body(NativeOperation::ListProviders(list_providers))
.expect("Failed to convert request");
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListProviders)
.is_ok());
}
#[test]
fn req_from_native_mangled_body() {
let req_body =
RequestBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_operation(req_body, Opcode::ListProviders)
.is_err());
}
#[test]
fn list_providers_body_to_native() {
let resp_body = ResponseBody::from_bytes(Vec::new());
assert!(CONVERTER
.body_to_result(resp_body, Opcode::ListProviders)
.is_ok());
}
#[test]
fn result_list_providers_from_native() {
let mut list_providers = Result {
providers: Vec::new(),
};
let provider_info = ProviderInfo {
uuid: Uuid::parse_str("9840cd61-9367-4010-bc24-f5b98a6174d1").unwrap(),
description: String::from("provider description"),
vendor: String::from("Arm"),
version_maj: 0,
version_min: 1,
version_rev: 0,
id: ProviderId::MbedCrypto,
};
list_providers.providers.push(provider_info);
let body = CONVERTER
.result_to_body(NativeResult::ListProviders(list_providers))
.expect("Failed to convert response");
assert!(!body.is_empty());
}
#[test]
fn list_providers_result_e2e() {
let mut list_providers = Result {
providers: Vec::new(),
};
let provider_info = ProviderInfo {
uuid: Uuid::parse_str("9840cd61-9367-4010-bc24-f5b98a6174d1").unwrap(),
description: String::from("provider description"),
vendor: String::from("Arm"),
version_maj: 0,
version_min: 1,
version_rev: 0,
id: ProviderId::MbedCrypto,
};
list_providers.providers.push(provider_info);
let body = CONVERTER
.result_to_body(NativeResult::ListProviders(list_providers))
.expect("Failed to convert response");
assert!(!body.is_empty());
let result = CONVERTER
.body_to_result(body, Opcode::ListProviders)
.expect("Failed to convert back to result");
match result {
NativeResult::ListProviders(result) => {
assert_eq!(result.providers.len(), 1);
}
_ => panic!("Expected list_providers"),
}
}
#[test]
fn resp_from_native_mangled_body() {
let resp_body =
ResponseBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_result(resp_body, Opcode::ListProviders)
.is_err());
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_ping.rs 0000644 0000000 0000000 00000012113 10461020230 0023063 0 ustar 0000000 0000000 // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::ping::{Operation as OperationProto, Result as ResultProto};
use crate::operations::ping::{Operation, Result};
use crate::requests::ResponseStatus;
use std::convert::TryFrom;
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(_proto_op: OperationProto) -> std::result::Result {
Ok(Operation {})
}
}
impl TryFrom for OperationProto {
type Error = ResponseStatus;
fn try_from(_proto_op: Operation) -> std::result::Result {
Ok(Default::default())
}
}
impl TryFrom for ResultProto {
type Error = ResponseStatus;
fn try_from(result: Result) -> std::result::Result {
let proto_response = ResultProto {
wire_protocol_version_maj: u32::from(result.wire_protocol_version_maj),
wire_protocol_version_min: u32::from(result.wire_protocol_version_min),
};
Ok(proto_response)
}
}
impl TryFrom for Result {
type Error = ResponseStatus;
fn try_from(response: ResultProto) -> std::result::Result {
Ok(Result {
wire_protocol_version_maj: u8::try_from(response.wire_protocol_version_maj)?,
wire_protocol_version_min: u8::try_from(response.wire_protocol_version_min)?,
})
}
}
#[cfg(test)]
mod test {
// Operation <-> Proto conversions are not tested since they're too simple
use super::super::generated_ops::ping::Result as ResultProto;
use super::super::{Convert, ProtobufConverter};
use crate::operations::ping::{Operation, Result};
use crate::operations::{NativeOperation, NativeResult};
use crate::requests::{request::RequestBody, response::ResponseBody, Opcode};
use std::convert::TryInto;
static CONVERTER: ProtobufConverter = ProtobufConverter {};
#[test]
fn proto_to_resp() {
let proto = ResultProto {
wire_protocol_version_maj: 1,
wire_protocol_version_min: 1,
};
let resp: Result = proto.try_into().unwrap();
assert!(resp.wire_protocol_version_maj == 1);
assert!(resp.wire_protocol_version_min == 1);
}
#[test]
fn resp_to_proto() {
let resp: Result = Result {
wire_protocol_version_maj: 1,
wire_protocol_version_min: 1,
};
let proto: ResultProto = resp.try_into().unwrap();
assert!(proto.wire_protocol_version_maj == 1);
assert!(proto.wire_protocol_version_min == 1);
}
#[test]
fn ping_req_to_native() {
let req_body = RequestBody::from_bytes(Vec::new());
assert!(CONVERTER.body_to_operation(req_body, Opcode::Ping).is_ok());
}
#[test]
fn op_ping_from_native() {
let ping = Operation {};
let body = CONVERTER
.operation_to_body(NativeOperation::Ping(ping))
.expect("Failed to convert request");
assert!(body.is_empty());
}
#[test]
fn op_ping_e2e() {
let ping = Operation {};
let req_body = CONVERTER
.operation_to_body(NativeOperation::Ping(ping))
.expect("Failed to convert request");
assert!(CONVERTER.body_to_operation(req_body, Opcode::Ping).is_ok());
}
#[test]
fn req_from_native_mangled_body() {
let req_body =
RequestBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER.body_to_operation(req_body, Opcode::Ping).is_err());
}
#[test]
fn ping_body_to_native() {
let resp_body = ResponseBody::from_bytes(Vec::new());
assert!(CONVERTER.body_to_result(resp_body, Opcode::Ping).is_ok());
}
#[test]
fn result_ping_from_native() {
let ping = Result {
wire_protocol_version_maj: 1,
wire_protocol_version_min: 0,
};
let body = CONVERTER
.result_to_body(NativeResult::Ping(ping))
.expect("Failed to convert response");
assert!(!body.is_empty());
}
#[test]
fn ping_result_e2e() {
let ping = Result {
wire_protocol_version_maj: 1,
wire_protocol_version_min: 0,
};
let body = CONVERTER
.result_to_body(NativeResult::Ping(ping))
.expect("Failed to convert response");
assert!(!body.is_empty());
let result = CONVERTER
.body_to_result(body, Opcode::Ping)
.expect("Failed to convert back to result");
match result {
NativeResult::Ping(result) => {
assert_eq!(result.wire_protocol_version_maj, 1);
assert_eq!(result.wire_protocol_version_min, 0);
}
_ => panic!("Expected ping"),
}
}
#[test]
fn resp_from_native_mangled_body() {
let resp_body =
ResponseBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER.body_to_result(resp_body, Opcode::Ping).is_err());
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_prepare_key_attestation.rs 0000644 0000000 0000000 00000031453 10461020230 0027063 0 ustar 0000000 0000000 // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::prepare_key_attestation::{
prepare_key_attestation_output, prepare_key_attestation_params, Operation as OperationProto,
PrepareKeyAttestationOutput, PrepareKeyAttestationParams, Result as ResultProto,
};
use crate::operations::prepare_key_attestation::{Operation, Result};
use crate::requests::ResponseStatus;
use log::error;
use std::convert::TryFrom;
impl TryFrom for OperationProto {
type Error = ResponseStatus;
fn try_from(op: Operation) -> std::result::Result {
match op {
Operation::ActivateCredential {
attested_key_name,
attesting_key_name,
} => Ok(OperationProto {
parameters: Some(PrepareKeyAttestationParams {
mechanism: Some(
prepare_key_attestation_params::Mechanism::ActivateCredential(
prepare_key_attestation_params::ActivateCredential {
attested_key_name,
attesting_key_name: attesting_key_name.unwrap_or_default(),
},
),
),
}),
}),
}
}
}
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(op: OperationProto) -> std::result::Result {
match op {
OperationProto {
parameters:
Some(PrepareKeyAttestationParams {
mechanism:
Some(prepare_key_attestation_params::Mechanism::ActivateCredential(
prepare_key_attestation_params::ActivateCredential {
attested_key_name,
attesting_key_name,
},
)),
}),
} => Ok(Operation::ActivateCredential {
attested_key_name,
attesting_key_name: if attesting_key_name.is_empty() {
None
} else {
Some(attesting_key_name)
},
}),
_ => {
error!("The encoding of the operation does not follow the expected pattern");
Err(ResponseStatus::InvalidEncoding)
}
}
}
}
impl TryFrom for ResultProto {
type Error = ResponseStatus;
fn try_from(op: Result) -> std::result::Result {
match op {
Result::ActivateCredential {
name,
public,
attesting_key_pub,
} => Ok(ResultProto {
output: Some(PrepareKeyAttestationOutput {
mechanism: Some(
prepare_key_attestation_output::Mechanism::ActivateCredential(
prepare_key_attestation_output::ActivateCredential {
name: name.to_vec(),
public: public.to_vec(),
attesting_key_pub: attesting_key_pub.to_vec(),
},
),
),
}),
}),
}
}
}
impl TryFrom for Result {
type Error = ResponseStatus;
fn try_from(op: ResultProto) -> std::result::Result {
match op {
ResultProto {
output:
Some(PrepareKeyAttestationOutput {
mechanism:
Some(prepare_key_attestation_output::Mechanism::ActivateCredential(
prepare_key_attestation_output::ActivateCredential {
name,
public,
attesting_key_pub,
},
)),
}),
} => Ok(Result::ActivateCredential {
name: name.into(),
public: public.into(),
attesting_key_pub: attesting_key_pub.into(),
}),
_ => {
error!("The encoding of the operation does not follow the expected pattern");
Err(ResponseStatus::InvalidEncoding)
}
}
}
}
#[cfg(test)]
mod test {
use super::super::generated_ops::prepare_key_attestation::{
prepare_key_attestation_output, prepare_key_attestation_params,
Operation as OperationProto, PrepareKeyAttestationOutput, PrepareKeyAttestationParams,
Result as ResultProto,
};
use super::super::{Convert, ProtobufConverter};
use crate::operations::{
prepare_key_attestation::Operation, prepare_key_attestation::Result, NativeOperation,
NativeResult,
};
use crate::requests::Opcode;
use std::convert::TryInto;
static CONVERTER: ProtobufConverter = ProtobufConverter {};
#[test]
fn prepare_key_attestation_op_from_proto() {
let op_attested_key_name = String::from("attested key name");
let op_attesting_key_name = String::from("attesting key name");
let proto = OperationProto {
parameters: Some(PrepareKeyAttestationParams {
mechanism: Some(
prepare_key_attestation_params::Mechanism::ActivateCredential(
prepare_key_attestation_params::ActivateCredential {
attested_key_name: op_attested_key_name.clone(),
attesting_key_name: op_attesting_key_name.clone(),
},
),
),
}),
};
let op: Operation = proto.try_into().expect("Conversion failed");
let Operation::ActivateCredential {
attested_key_name,
attesting_key_name,
} = op;
assert_eq!(attested_key_name, op_attested_key_name);
assert_eq!(
attesting_key_name.expect("Attesting key name was empty"),
op_attesting_key_name
);
}
#[test]
fn prepare_key_attestation_proto_no_attesting() {
let op_attested_key_name = String::from("attested key name");
let proto = OperationProto {
parameters: Some(PrepareKeyAttestationParams {
mechanism: Some(
prepare_key_attestation_params::Mechanism::ActivateCredential(
prepare_key_attestation_params::ActivateCredential {
attested_key_name: op_attested_key_name,
attesting_key_name: String::new(),
},
),
),
}),
};
let op: Operation = proto.try_into().expect("Conversion failed");
let Operation::ActivateCredential {
attesting_key_name, ..
} = op;
assert!(attesting_key_name.is_none());
}
#[test]
fn prepare_key_attestation_op_to_proto() {
let op_attested_key_name = String::from("attested key name");
let op_attesting_key_name = String::from("attesting key name");
let op: Operation = Operation::ActivateCredential {
attested_key_name: op_attested_key_name.clone(),
attesting_key_name: Some(op_attesting_key_name.clone()),
};
let proto: OperationProto = op.try_into().expect("Conversion failed");
if let OperationProto {
parameters:
Some(PrepareKeyAttestationParams {
mechanism:
Some(prepare_key_attestation_params::Mechanism::ActivateCredential(
prepare_key_attestation_params::ActivateCredential {
attested_key_name,
attesting_key_name,
},
)),
}),
} = proto
{
assert_eq!(attested_key_name, op_attested_key_name);
assert_eq!(attesting_key_name, op_attesting_key_name);
}
}
#[test]
fn prepare_key_attestation_op_no_attesting() {
let op_attested_key_name = String::from("attested key name");
let op: Operation = Operation::ActivateCredential {
attested_key_name: op_attested_key_name,
attesting_key_name: None,
};
let proto: OperationProto = op.try_into().expect("Conversion failed");
if let OperationProto {
parameters:
Some(PrepareKeyAttestationParams {
mechanism:
Some(prepare_key_attestation_params::Mechanism::ActivateCredential(
prepare_key_attestation_params::ActivateCredential {
attesting_key_name,
..
},
)),
}),
} = proto
{
assert_eq!(attesting_key_name, String::new());
}
}
#[test]
fn prepare_key_attestation_op_e2e() {
let op_attested_key_name = String::from("attested key name");
let op_attesting_key_name = String::from("attesting key name");
let op: Operation = Operation::ActivateCredential {
attested_key_name: op_attested_key_name,
attesting_key_name: Some(op_attesting_key_name),
};
let body = CONVERTER
.operation_to_body(NativeOperation::PrepareKeyAttestation(op))
.expect("Failed to convert to body");
let _ = CONVERTER
.body_to_operation(body, Opcode::PrepareKeyAttestation)
.expect("Failed to convert to operation");
}
#[test]
fn prepare_key_attestation_resp_to_proto() {
let resp_name = vec![0xff; 32];
let resp_public = vec![0xcc; 32];
let resp_attesting_key_pub = vec![0x22; 32];
let result = Result::ActivateCredential {
name: resp_name.clone().into(),
public: resp_public.clone().into(),
attesting_key_pub: resp_attesting_key_pub.clone().into(),
};
let proto: ResultProto = result.try_into().expect("Conversion failed");
if let ResultProto {
output:
Some(PrepareKeyAttestationOutput {
mechanism:
Some(prepare_key_attestation_output::Mechanism::ActivateCredential(
prepare_key_attestation_output::ActivateCredential {
name,
public,
attesting_key_pub,
},
)),
}),
} = proto
{
assert_eq!(name, resp_name);
assert_eq!(public, resp_public);
assert_eq!(attesting_key_pub, resp_attesting_key_pub);
}
}
#[test]
fn prepare_key_attestation_resp_from_proto() {
let resp_name = vec![0xff; 32];
let resp_public = vec![0xcc; 32];
let resp_attesting_key_pub = vec![0x22; 32];
let proto = ResultProto {
output: Some(PrepareKeyAttestationOutput {
mechanism: Some(
prepare_key_attestation_output::Mechanism::ActivateCredential(
prepare_key_attestation_output::ActivateCredential {
name: resp_name.clone(),
public: resp_public.clone(),
attesting_key_pub: resp_attesting_key_pub.clone(),
},
),
),
}),
};
let result: Result = proto.try_into().expect("Conversion failed");
let Result::ActivateCredential {
name,
public,
attesting_key_pub,
} = result;
assert_eq!(name.to_vec(), resp_name);
assert_eq!(public.to_vec(), resp_public);
assert_eq!(attesting_key_pub.to_vec(), resp_attesting_key_pub);
}
#[test]
fn prepare_key_attestation_resp_e2e() {
let resp_name = vec![0xff; 32];
let resp_public = vec![0xcc; 32];
let resp_attesting_key_pub = vec![0x22; 32];
let result = Result::ActivateCredential {
name: resp_name.into(),
public: resp_public.into(),
attesting_key_pub: resp_attesting_key_pub.into(),
};
let body = CONVERTER
.result_to_body(NativeResult::PrepareKeyAttestation(result))
.expect("Failed to convert to body");
let _ = CONVERTER
.body_to_result(body, Opcode::PrepareKeyAttestation)
.expect("Failed to convert to operation");
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_psa_aead_decrypt.rs 0000644 0000000 0000000 00000015471 10461020230 0025427 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::psa_aead_decrypt::{Operation as OperationProto, Result as ResultProto};
use crate::operations::psa_aead_decrypt::{Operation, Result};
use crate::requests::ResponseStatus;
use log::error;
use std::convert::{TryFrom, TryInto};
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(proto_op: OperationProto) -> std::result::Result {
Ok(Operation {
key_name: proto_op.key_name,
alg: proto_op
.alg
.ok_or_else(|| {
error!("The alg field of PsaAeadDecrypt::Operation message is not set (mandatory field).");
ResponseStatus::InvalidEncoding
})?
.try_into()?,
additional_data: proto_op.additional_data.into(),
ciphertext: proto_op.ciphertext.into(),
nonce: proto_op.nonce.into(),
})
}
}
impl TryFrom for OperationProto {
type Error = ResponseStatus;
fn try_from(op: Operation) -> std::result::Result {
let alg = Some(op.alg.try_into()?);
Ok(OperationProto {
key_name: op.key_name,
alg,
additional_data: op.additional_data.to_vec(),
ciphertext: op.ciphertext.to_vec(),
nonce: op.nonce.to_vec(),
})
}
}
impl TryFrom for Result {
type Error = ResponseStatus;
fn try_from(proto_result: ResultProto) -> std::result::Result {
Ok(Result {
plaintext: proto_result.plaintext.into(),
})
}
}
impl TryFrom for ResultProto {
type Error = ResponseStatus;
fn try_from(result: Result) -> std::result::Result {
Ok(ResultProto {
plaintext: result.plaintext.to_vec(),
})
}
}
#[cfg(test)]
mod test {
use super::super::generated_ops::psa_aead_decrypt::{
Operation as OperationProto, Result as ResultProto,
};
use super::super::generated_ops::psa_algorithm as algorithm_proto;
use super::super::{Convert, ProtobufConverter};
use crate::operations::psa_aead_decrypt::{Operation, Result};
use crate::operations::psa_algorithm::AeadWithDefaultLengthTag;
use std::convert::TryInto;
static CONVERTER: ProtobufConverter = ProtobufConverter {};
use crate::operations::{NativeOperation, NativeResult};
use crate::requests::{request::RequestBody, response::ResponseBody, Opcode};
#[test]
fn aead_proto_to_op() {
let mut proto: OperationProto = Default::default();
let ciphertext = vec![0x11, 0x22, 0x33];
let additional_data = vec![0x66, 0x77, 0x88];
let key_name = "test name".to_string();
let nonce: Vec = vec![0x55; 12];
proto.ciphertext = ciphertext.clone();
proto.alg = Some(algorithm_proto::algorithm::Aead {
variant: Some(
algorithm_proto::algorithm::aead::Variant::AeadWithDefaultLengthTag(
algorithm_proto::algorithm::aead::AeadWithDefaultLengthTag::Ccm.into(),
),
),
});
proto.key_name = key_name.clone();
proto.nonce = nonce.clone();
proto.additional_data = additional_data.clone();
let op: Operation = proto.try_into().expect("Failed to convert");
assert_eq!(*op.ciphertext, ciphertext);
assert_eq!(op.key_name, key_name);
assert_eq!(*op.additional_data, additional_data);
assert_eq!(*op.nonce, nonce);
assert_eq!(op.alg, AeadWithDefaultLengthTag::Ccm.into());
}
#[test]
fn aead_op_to_proto() {
let ciphertext = vec![0x11, 0x22, 0x33];
let additional_data = vec![0x55, 0x66, 0x77];
let nonce: Vec = vec![0x55; 12];
let key_name = "test name".to_string();
let op = Operation {
ciphertext: ciphertext.clone().into(),
alg: AeadWithDefaultLengthTag::Ccm.into(),
key_name: key_name.clone(),
nonce: nonce.clone().into(),
additional_data: additional_data.clone().into(),
};
let proto: OperationProto = op.try_into().expect("Failed to convert");
assert_eq!(proto.ciphertext, ciphertext);
assert_eq!(proto.key_name, key_name);
assert_eq!(proto.nonce, nonce);
assert_eq!(proto.additional_data, additional_data);
}
#[test]
fn aead_proto_to_resp() {
let mut proto: ResultProto = Default::default();
let plaintext = vec![0x11, 0x22, 0x33];
proto.plaintext = plaintext.clone();
let result: Result = proto.try_into().expect("Failed to convert");
assert_eq!(*result.plaintext, plaintext);
}
#[test]
fn aead_resp_to_proto() {
let plaintext = vec![0x11, 0x22, 0x33];
let result = Result {
plaintext: plaintext.clone().into(),
};
let proto: ResultProto = result.try_into().expect("Failed to convert");
assert_eq!(proto.plaintext, plaintext);
}
#[test]
fn psa_decrypt_message_op_e2e() {
let ciphertext = vec![0x11, 0x22, 0x33];
let additional_data = vec![0x55, 0x66, 0x77];
let nonce: Vec = vec![0x55; 12];
let key_name = "test name".to_string();
let op = Operation {
ciphertext: ciphertext.into(),
alg: AeadWithDefaultLengthTag::Ccm.into(),
key_name,
nonce: nonce.into(),
additional_data: additional_data.into(),
};
let body = CONVERTER
.operation_to_body(NativeOperation::PsaAeadDecrypt(op))
.expect("Failed to convert to body");
let _ = CONVERTER
.body_to_operation(body, Opcode::PsaAeadDecrypt)
.expect("Failed to convert to operation");
}
#[test]
fn resp_aead_decrypt_e2e() {
let result = Result {
plaintext: vec![0x11, 0x22, 0x33].into(),
};
let body = CONVERTER
.result_to_body(NativeResult::PsaAeadDecrypt(result))
.expect("Failed to convert request");
assert!(CONVERTER
.body_to_result(body, Opcode::PsaAeadDecrypt)
.is_ok());
}
#[test]
fn result_from_mangled_resp_body() {
let resp_body =
ResponseBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_result(resp_body, Opcode::PsaAeadDecrypt)
.is_err());
}
#[test]
fn op_from_mangled_req_body() {
let req_body =
RequestBody::from_bytes(vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
assert!(CONVERTER
.body_to_operation(req_body, Opcode::PsaAeadDecrypt)
.is_err());
}
}
parsec-interface-0.29.1/src/operations_protobuf/convert_psa_aead_encrypt.rs 0000644 0000000 0000000 00000015470 10461020230 0025440 0 ustar 0000000 0000000 // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use super::generated_ops::psa_aead_encrypt::{Operation as OperationProto, Result as ResultProto};
use crate::operations::psa_aead_encrypt::{Operation, Result};
use crate::requests::ResponseStatus;
use log::error;
use std::convert::{TryFrom, TryInto};
impl TryFrom for Operation {
type Error = ResponseStatus;
fn try_from(proto_op: OperationProto) -> std::result::Result