ssri-9.2.0/.cargo_vcs_info.json0000644000000001360000000000100120240ustar { "git": { "sha1": "1b376803bd31b4b583e1f3fdec7c042483eedb51" }, "path_in_vcs": "" }ssri-9.2.0/.github/FUNDING.yml000064400000000000000000000001030072674642500140130ustar 00000000000000# These are supported funding model platforms github: [zkat] ssri-9.2.0/.github/workflows/rust.yml000064400000000000000000000012520072674642500157610ustar 00000000000000name: Rust on: [push, pull_request] jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: rust: [1.57.0, stable] os: [ubuntu-latest, macOS-latest, windows-latest] steps: - uses: actions/checkout@v1 - name: Install Rust uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.rust }} components: rustfmt, clippy override: true - name: Check run: cargo check - name: Rustfmt run: cargo fmt --all -- --check - name: Clippy run: cargo clippy -- -D warnings - name: Run tests run: cargo test --verbose ssri-9.2.0/.gitignore000064400000000000000000000000540072674642500126330ustar 00000000000000/target **/*.rs.bk /.vscode /Cargo.lock ssri-9.2.0/CHANGELOG.md000064400000000000000000000123600072674642500124570ustar 00000000000000# `ssri` Release Changelog ## 9.2.0 (2023-07-18) ### Features * **from_hex:** Implemented Integrity::from_hex(), inverse of Integrity::to_hex() (#11) ([19b34fe4](https://github.com/zkat/ssri-rs/commit/19b34fe4cc2ad788398ac3a61472230a7966b5d7)) ## 9.1.0 (2023-07-16) ### Features * **deps:** Relax sha-1 dep constraint (#12) ([95473be7](https://github.com/zkat/ssri-rs/commit/95473be7c23b1a1e350409c7d0c6177ab663b9f9)) ## 9.0.0 (2023-05-20) ### Features * **xxhash:** add xxhash as a supported algorithm (#9) ([f458aa5e](https://github.com/zkat/ssri-rs/commit/f458aa5ee980e3ba7d96ee547dc05909c3fa2674)) * **BREAKING CHANGE**: Adds a new algorithm, and makes Algorithm and Hasher `#[non_exhaustive]`. ## 8.1.0 (2023-04-01) This release upgrades miette and thiserror in lockstep, bringing in syn2, in order to avoid [potential issues with the upgrade](https://github.com/yaahc/eyre/pull/92). ### Features * **deps:** bump miette and thiserror ([4ecc2c08](https://github.com/zkat/ssri-rs/commit/4ecc2c0885b6221c42f8c0cf9c3d6448843adb80)) ## 8.0.0 (2023-02-19) ### Features * **msrv:** Set new MSRV after dep upgrades ([ac29f2c3](https://github.com/zkat/ssri-rs/commit/ac29f2c32caa1fe810f3763279e8b0a0f52c6a70)) * **BREAKING CHANGE**: The MSRV has been increased to 1.57.0 * **traits:** Derive more traits, including Hash, and fix line endings ([9dbb1e8c](https://github.com/zkat/ssri-rs/commit/9dbb1e8c99869e19533d6abeeb6b09930c426791)) * **miette:** Add miette and derive Diagnostic for Error ([c2071f6a](https://github.com/zkat/ssri-rs/commit/c2071f6ab74ff89448b28fd016f2f090479d44a5)) ### Bug Fixes * **clippy:** appease the paperclip ([0b1eb50d](https://github.com/zkat/ssri-rs/commit/0b1eb50def2e86ba5fe0e7a6651b65452190d1e6)) * **deps:** bump digest, sha-1 and sha2 to 0.10.x ([c611c543](https://github.com/zkat/ssri-rs/commit/c611c543c6150017b259bc990820bd5ea5915670)) * **deps:** bump thiserror from 1.0.3 to 1.0.38 ([93429d8c](https://github.com/zkat/ssri-rs/commit/93429d8c496f858182889343cded2616b007357b)) * **deps:** bump serde from 1.0.92 to 1.0.152 ([0fd3812f](https://github.com/zkat/ssri-rs/commit/0fd3812f0846238aef86a3c544ba915ffe359775)) * **deps:** bump hex to from 0.3.2 to 0.4.3 ([a01e8522](https://github.com/zkat/ssri-rs/commit/a01e852295a262753a72b056cc87395622d6175a)) * **deps:** bump base64 from 0.10.1 to 0.21.0 ([bf4ec575](https://github.com/zkat/ssri-rs/commit/bf4ec57566774c698891240f3d9f489fe95ab941)) * **clippy:** resolve linting issues ([354f686e](https://github.com/zkat/ssri-rs/commit/354f686e2fea55e371f656a14f673c4fabc66993)) * **clippy:** set MSRV for clippy, too ([7fb5e90b](https://github.com/zkat/ssri-rs/commit/7fb5e90b4fcba9ffce9c7c851b7a73ddbcf32a97)) * **clippy:** update for lower clippy version ([399eafd0](https://github.com/zkat/ssri-rs/commit/399eafd04fcfe0abf22fd195341d16636c3377da)) * **clippy:** more clippy fixes (#8) ([0d6c019d](https://github.com/zkat/ssri-rs/commit/0d6c019d5e581e533aaccd1113a50a2ad4f72115)) ### Miscellaneous Tasks * **deps:** bump dev dependencies to latest ([9d9d4a67](https://github.com/zkat/ssri-rs/commit/9d9d4a6789d25cd36f4f342450a9f61368db2857)) ## 7.0.0 (2021-09-16) I've decided to move away from Parity for various Rust libraries, such as `ssri`. So it can be more permissively used now! ### Features * **license:** change license to Apache-2.0 ([dad568fb](https://github.com/zkat/ssri-rs/commit/dad568fb7d61a71b428308f279cb287e45164cb8)) * **BREAKING CHANGE**: This is a significant licensing change. Please review. ## (2020-08-20) #### Breaking Changes - **integrity:** serialize/deserialize as a string ([6762fd53](https://github.com/zkat/ssri-rs/commit/6762fd533330e7202f9409c0971948b4eba6bd5e)) ## 5.0.0 (2019-10-20) #### Bug Fixes - **integrity:** sort hashes after parse ([c9f92a00](https://github.com/zkat/ssri-rs/commit/c9f92a00cc183c65e7fd48c39fe95b09236d65da)) #### Features - **errors:** More detailed errors ([6d5cba7e](https://github.com/zkat/ssri-rs/commit/6d5cba7ebb731a8da1717976ccc957671423bc52)) - **license:** switch license to Parity + Apache-2.0 ([adac5dc0](https://github.com/zkat/ssri-rs/commit/adac5dc04f33ac8efc3dadf7ab75c4c67bfccf5c)) #### Breaking Changes - **errors:** More detailed errors ([6d5cba7e](https://github.com/zkat/ssri-rs/commit/6d5cba7ebb731a8da1717976ccc957671423bc52)) ## 4.1.0 (2019-10-20) #### Bug Fixes - **docs:** oops, used the cacache config ([67fa5ed0](https://github.com/zkat/ssri-rs/commit/67fa5ed0a39d3d6009aa322e5c71197ab653ef5d)) #### Features - **error:** switch from failure to thiserror crate (#3) ([0ce03070](https://github.com/zkat/ssri-rs/commit/0ce030708ce9ef52be33171612a79a3f2489af4c)) ## 4.0.0 (2019-09-07) #### Features - **license:** relicense under MPL-2.0 (#2) ([9dd2b3a9](https://github.com/zkat/ssri-rs/commit/9dd2b3a97cf04266a9d99246cc8dcf2db2a6b632) #### Breaking Changes - **license:** relicense under MPL-2.0 (#2) ([9dd2b3a9](https://github.com/zkat/ssri-rs/commit/9dd2b3a97cf04266a9d99246cc8dcf2db2a6b632) ssri-9.2.0/CODE_OF_CONDUCT.md000064400000000000000000000236320072674642500134510ustar 00000000000000# Code of Conduct ## When Something Happens If you see a Code of Conduct violation, follow these steps: 1. Let the person know that what they did is not appropriate and ask them to stop and/or edit their message(s) or commits. 2. That person should immediately stop the behavior and correct the issue. 3. If this doesn’t happen, or if you're uncomfortable speaking up, [contact the maintainers](#contacting-maintainers). 4. As soon as available, a maintainer will look into the issue, and take [further action (see below)](#further-enforcement), starting with a warning, then temporary block, then long-term repo or organization ban. When reporting, please include any relevant details, links, screenshots, context, or other information that may be used to better understand and resolve the situation. **The maintainer team will prioritize the well-being and comfort of the recipients of the violation over the comfort of the violator.** See [some examples below](#enforcement-examples). ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers of this project pledge to making participation in our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, technical preferences, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language. - Being respectful of differing viewpoints and experiences. - Gracefully accepting constructive feedback. - Focusing on what is best for the community. - Showing empathy and kindness towards other community members. - Encouraging and raising up your peers in the project so you can all bask in hacks and glory. Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances, including when simulated online. The only exception to sexual topics is channels/spaces specifically for topics of sexual identity. - Casual mention of slavery or indentured servitude and/or false comparisons of one's occupation or situation to slavery. Please consider using or asking about alternate terminology when referring to such metaphors in technology. - Making light of/making mocking comments about trigger warnings and content warnings. - Trolling, insulting/derogatory comments, and personal or political attacks. - Public or private harassment, deliberate intimidation, or threats. - Publishing others' private information, such as a physical or electronic address, without explicit permission. This includes any sort of "outing" of any aspect of someone's identity without their consent. - Publishing private screenshots or quotes of interactions in the context of this project without all quoted users' _explicit_ consent. - Publishing of private communication that doesn't have to do with reporting harrassment. - Any of the above even when [presented as "ironic" or "joking"](https://en.wikipedia.org/wiki/Hipster_racism). - Any attempt to present "reverse-ism" versions of the above as violations. Examples of reverse-isms are "reverse racism", "reverse sexism", "heterophobia", and "cisphobia". - Unsolicited explanations under the assumption that someone doesn't already know it. Ask before you teach! Don't assume what people's knowledge gaps are. - [Feigning or exaggerating surprise](https://www.recurse.com/manual#no-feigned-surprise) when someone admits to not knowing something. - "[Well-actuallies](https://www.recurse.com/manual#no-well-actuallys)" - Other conduct which could reasonably be considered inappropriate in a professional or community setting. ## Scope This Code of Conduct applies both within spaces involving this project and in other spaces involving community members. This includes the repository, its Pull Requests and Issue tracker, its Twitter community, private email communications in the context of the project, and any events where members of the project are participating, as well as adjacent communities and venues affecting the project's members. Depending on the violation, the maintainers may decide that violations of this code of conduct that have happened outside of the scope of the community may deem an individual unwelcome, and take appropriate action to maintain the comfort and safety of its members. ### Other Community Standards As a project on GitHub, this project is additionally covered by the [GitHub Community Guidelines](https://help.github.com/articles/github-community-guidelines/). Additionally, as a project hosted on npm, is is covered by [npm, Inc's Code of Conduct](https://www.npmjs.com/policies/conduct). Enforcement of those guidelines after violations overlapping with the above are the responsibility of the entities, and enforcement may happen in any or all of the services/communities. ## Maintainer Enforcement Process Once the maintainers get involved, they will follow a documented series of steps and do their best to preserve the well-being of project members. This section covers actual concrete steps. ### Contacting Maintainers You may get in touch with the maintainer team through any of the following methods: - Through email: - [kzm@sykosomatic.org](mailto:coc@zkat.tech) (Kat Marchán) - Through Twitter: - [@maybekatz](https://twitter.com/maybekatz) (Kat Marchán) ### Further Enforcement If you've already followed the [initial enforcement steps](#enforcement), these are the steps maintainers will take for further enforcement, as needed: 1. Repeat the request to stop. 2. If the person doubles down, they will have offending messages removed or edited by a maintainers given an official warning. The PR or Issue may be locked. 3. If the behavior continues or is repeated later, the person will be blocked from participating for 24 hours. 4. If the behavior continues or is repeated after the temporary block, a long-term (6-12mo) ban will be used. On top of this, maintainers may remove any offending messages, images, contributions, etc, as they deem necessary. Maintainers reserve full rights to skip any of these steps, at their discretion, if the violation is considered to be a serious and/or immediate threat to the health and well-being of members of the community. These include any threats, serious physical or verbal attacks, and other such behavior that would be completely unacceptable in any social setting that puts our members at risk. Members expelled from events or venues with any sort of paid attendance will not be refunded. ### Who Watches the Watchers? Maintainers and other leaders who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. These may include anything from removal from the maintainer team to a permanent ban from the community. Additionally, as a project hosted on both GitHub and npm, [their own Codes of Conducts may be applied against maintainers of this project](#other-community-standards), externally of this project's procedures. ### Enforcement Examples #### The Best Case The vast majority of situations work out like this. This interaction is common, and generally positive. > Alex: "Yeah I used X and it was really crazy!" > Patt (not a maintainer): "Hey, could you not use that word? What about 'ridiculous' instead?" > Alex: "oh sorry, sure." -> edits old comment to say "it was really confusing!" #### The Maintainer Case Sometimes, though, you need to get maintainers involved. Maintainers will do their best to resolve conflicts, but people who were harmed by something **will take priority**. > Patt: "Honestly, sometimes I just really hate using \$library and anyone who uses it probably sucks at their job." > Alex: "Whoa there, could you dial it back a bit? There's a CoC thing about attacking folks' tech use like that." > Patt: "I'm not attacking anyone, what's your problem?" > Alex: "@maintainers hey uh. Can someone look at this issue? Patt is getting a bit aggro. I tried to nudge them about it, but nope." > KeeperOfCommitBits: (on issue) "Hey Patt, maintainer here. Could you tone it down? This sort of attack is really not okay in this space." > Patt: "Leave me alone I haven't said anything bad wtf is wrong with you." > KeeperOfCommitBits: (deletes user's comment), "@patt I mean it. Please refer to the CoC over at (URL to this CoC) if you have questions, but you can consider this an actual warning. I'd appreciate it if you reworded your messages in this thread, since they made folks there uncomfortable. Let's try and be kind, yeah?" > Patt: "@keeperofbits Okay sorry. I'm just frustrated and I'm kinda burnt out and I guess I got carried away. I'll DM Alex a note apologizing and edit my messages. Sorry for the trouble." > KeeperOfCommitBits: "@patt Thanks for that. I hear you on the stress. Burnout sucks :/. Have a good one!" #### The Nope Case > PepeTheFrog🐸: "Hi, I am a literal actual nazi and I think white supremacists are quite fashionable." > Patt: "NOOOOPE. OH NOPE NOPE." > Alex: "JFC NO. NOPE. @keeperofbits NOPE NOPE LOOK HERE" > KeeperOfCommitBits: "👀 Nope. NOPE NOPE NOPE. 🔥" > PepeTheFrog🐸 has been banned from all organization or user repositories belonging to KeeperOfCommitBits. ## Attribution This Code of Conduct was generated using [WeAllJS Code of Conduct Generator](https://npm.im/weallbehave), which is based on the [WeAllJS Code of Conduct](https://wealljs.org/code-of-conduct), which is itself based on [Contributor Covenant](http://contributor-covenant.org), version 1.4, available at [http://contributor-covenant.org/version/1/4](http://contributor-covenant.org/version/1/4), and the LGBTQ in Technology Slack [Code of Conduct](http://lgbtq.technology/coc.html). ssri-9.2.0/CONTRIBUTING.md000064400000000000000000000671660072674642500131150ustar 00000000000000# Contributing ## How do I... - [Use This Guide](#introduction)? - Ask or Say Something? 🤔🐛😱 - [Request Support](#request-support) - [Report an Error or Bug](#report-an-error-or-bug) - [Request a Feature](#request-a-feature) - Make Something? 🤓👩🏽‍💻📜🍳 - [Project Setup](#project-setup) - [Contribute Documentation](#contribute-documentation) - [Contribute Code](#contribute-code) - Manage Something ✅🙆🏼💃👔 - [Provide Support on Issues](#provide-support-on-issues) - [Label Issues](#label-issues) - [Clean Up Issues and PRs](#clean-up-issues-and-prs) - [Review Pull Requests](#review-pull-requests) - [Merge Pull Requests](#merge-pull-requests) - [Tag a Release](#tag-a-release) - [Join the Project Team](#join-the-project-team) - Add a Guide Like This One [To My Project](#attribution)? 🤖😻👻 ## Introduction Thank you so much for your interest in contributing!. All types of contributions are encouraged and valued. See the [table of contents](#toc) for different ways to help and details about how this project handles them!📝 Please make sure to read the relevant section before making your contribution! It will make it a lot easier for us maintainers to make the most of it and smooth out the experience for all involved. 💚 The [Project Team](#join-the-project-team) looks forward to your contributions. 🙌🏾✨ ## Request Support If you have a question about this project, how to use it, or just need clarification about something: - Open an Issue at https://github.com/zkat/ssri-rs/issues - Provide as much context as you can about what you're running into. - Provide project and platform versions, depending on what seems relevant. If not, please be ready to provide that information if maintainers ask for it. Once it's filed: - The project team will [label the issue](#label-issues). - Someone will try to have a response soon. - If you or the maintainers don't respond to an issue for 30 days, the [issue will be closed](#clean-up-issues-and-prs). If you want to come back to it, reply (once, please), and we'll reopen the existing issue. Please avoid filing new issues as extensions of one you already made. ## Report an Error or Bug If you run into an error or bug with the project: - Open an Issue at https://github.com/zkat/ssri-rs/issues - Include _reproduction steps_ that someone else can follow to recreate the bug or error on their own. - Provide project and platform versions, depending on what seems relevant. If not, please be ready to provide that information if maintainers ask for it. Once it's filed: - The project team will [label the issue](#label-issues). - A team member will try to reproduce the issue with your provided steps. If there are no repro steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. - If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#contribute-code). - If you or the maintainers don't respond to an issue for 30 days, the [issue will be closed](#clean-up-issues-and-prs). If you want to come back to it, reply (once, please), and we'll reopen the existing issue. Please avoid filing new issues as extensions of one you already made. - `critical` issues may be left open, depending on perceived immediacy and severity, even past the 30 day deadline. ## Request a Feature If the project doesn't do something you need or want it to do: - Open an Issue at https://github.com/zkat/ssri-rs/issues - Provide as much context as you can about what you're running into. - Please try and be clear about why existing features and alternatives would not work for you. Once it's filed: - The project team will [label the issue](#label-issues). - The project team will evaluate the feature request, possibly asking you more questions to understand its purpose and any relevant requirements. If the issue is closed, the team will convey their reasoning and suggest an alternative path forward. - If the feature request is accepted, it will be marked for implementation with `feature-accepted`, which can then be done by either by a core team member or by anyone in the community who wants to [contribute code](#contribute-code). Note: The team is unlikely to be able to accept every single feature request that is filed. Please understand if they need to say no. ## Project Setup So you wanna contribute some code! That's great! This project uses GitHub Pull Requests to manage contributions, so [read up on how to fork a GitHub project and file a PR](https://guides.github.com/activities/forking) if you've never done it before. If this seems like a lot or you aren't able to do all this setup, you might also be able to [edit the files directly](https://help.github.com/articles/editing-files-in-another-user-s-repository/) without having to do any of this setup. Yes, [even code](#contribute-code). If you want to go the usual route and run the project locally, though: - [Install Rust](https://www.rust-lang.org/learn/get-started) - [Fork the project](https://guides.github.com/activities/forking/#fork) Then in your terminal: - `cd path/to/your/clone` - `cargo test` And you should be ready to go! ## Contribute Documentation Documentation is a super important, critical part of this project. Docs are how we keep track of what we're doing, how, and why. It's how we stay on the same page about our policies. And it's how we tell others everything they need in order to be able to use this project -- or contribute to it. So thank you in advance. Documentation contributions of any size are welcome! Feel free to file a PR even if you're just rewording a sentence to be more clear, or fixing a spelling mistake! To contribute documentation: - [Set up the project](#project-setup). - Edit or add any relevant documentation. - Make sure your changes are formatted correctly and consistently with the rest of the documentation. - Re-read what you wrote, and run a spellchecker on it to make sure you didn't miss anything. - Write clear, concise commit message(s) using [conventional-changelog format](https://github.com/conventional-changelog/conventional-changelog-angular/blob/master/convention.md). Documentation commits should use `docs(): `. - Go to https://github.com/zkat/ssri-rs/pulls and open a new pull request with your changes. - If your PR is connected to an open issue, add a line in your PR's description that says `Fixes: #123`, where `#123` is the number of the issue you're fixing. Once you've filed the PR: - One or more maintainers will use GitHub's review feature to review your PR. - If the maintainer asks for any changes, edit your changes, push, and ask for another review. - If the maintainer decides to pass on your PR, they will thank you for the contribution and explain why they won't be accepting the changes. That's ok! We still really appreciate you taking the time to do it, and we don't take that lightly. 💚 - If your PR gets accepted, it will be marked as such, and merged into the `latest` branch soon after. Your contribution will be distributed to the masses next time the maintainers [tag a release](#tag-a-release) ## Contribute Code We like code commits a lot! They're super handy, and they keep the project going and doing the work it needs to do to be useful to others. Code contributions of just about any size are acceptable! The main difference between code contributions and documentation contributions is that contributing code requires inclusion of relevant tests for the code being added or changed. Contributions without accompanying tests will be held off until a test is added, unless the maintainers consider the specific tests to be either impossible, or way too much of a burden for such a contribution. To contribute code: - [Set up the project](#project-setup). - Make any necessary changes to the source code. - Include any [additional documentation](#contribute-documentation) the changes might need. - Write tests that verify that your contribution works as expected. - Write clear, concise commit message(s) using [conventional-changelog format](https://github.com/conventional-changelog/conventional-changelog-angular/blob/master/convention.md). - Dependency updates, additions, or removals must be in individual commits, and the message must use the format: `(deps): PKG@VERSION`, where `` is any of the usual `conventional-changelog` prefixes, at your discretion. - Go to https://github.com/zkat/ssri-rs/pulls and open a new pull request with your changes. - If your PR is connected to an open issue, add a line in your PR's description that says `Fixes: #123`, where `#123` is the number of the issue you're fixing. Once you've filed the PR: - Barring special circumstances, maintainers will not review PRs until all checks pass (Travis, AppVeyor, etc). - One or more maintainers will use GitHub's review feature to review your PR. - If the maintainer asks for any changes, edit your changes, push, and ask for another review. Additional tags (such as `needs-tests`) will be added depending on the review. - If the maintainer decides to pass on your PR, they will thank you for the contribution and explain why they won't be accepting the changes. That's ok! We still really appreciate you taking the time to do it, and we don't take that lightly. 💚 - If your PR gets accepted, it will be marked as such, and merged into the `latest` branch soon after. Your contribution will be distributed to the masses next time the maintainers [tag a release](#tag-a-release) ## Provide Support on Issues [Needs Collaborator](#join-the-project-team): none Helping out other users with their questions is a really awesome way of contributing to any community. It's not uncommon for most of the issues on an open source projects being support-related questions by users trying to understand something they ran into, or find their way around a known bug. Sometimes, the `support` label will be added to things that turn out to actually be other things, like bugs or feature requests. In that case, suss out the details with the person who filed the original issue, add a comment explaining what the bug is, and change the label from `support` to `bug` or `feature`. If you can't do this yourself, @mention a maintainer so they can do it. In order to help other folks out with their questions: - Go to the issue tracker and [filter open issues by the `support` label](https://github.com/zkat/ssri-rs/issues?q=is%3Aopen+is%3Aissue+label%3Asupport). - Read through the list until you find something that you're familiar enough with to give an answer to. - Respond to the issue with whatever details are needed to clarify the question, or get more details about what's going on. - Once the discussion wraps up and things are clarified, either close the issue, or ask the original issue filer (or a maintainer) to close it for you. Some notes on picking up support issues: - Avoid responding to issues you don't know you can answer accurately. - As much as possible, try to refer to past issues with accepted answers. Link to them from your replies with the `#123` format. - Be kind and patient with users -- often, folks who have run into confusing things might be upset or impatient. This is ok. Try to understand where they're coming from, and if you're too uncomfortable with the tone, feel free to stay away or withdraw from the issue. (note: if the user is outright hostile or is violating the CoC, [refer to the Code of Conduct](CODE_OF_CONDUCT.md) to resolve the conflict). ## Label Issues [Needs Collaborator](#join-the-project-team): Issue Tracker One of the most important tasks in handling issues is labeling them usefully and accurately. All other tasks involving issues ultimately rely on the issue being classified in such a way that relevant parties looking to do their own tasks can find them quickly and easily. In order to label issues, [open up the list of unlabeled issues](https://github.com/zkat/ssri-rs/issues?q=is%3Aopen+is%3Aissue+no%3Alabel) and, **from newest to oldest**, read through each one and apply issue labels according to the table below. If you're unsure about what label to apply, skip the issue and try the next one: don't feel obligated to label each and every issue yourself! | Label | Apply When | Notes | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `bug` | Cases where the code (or documentation) is behaving in a way it wasn't intended to. | If something is happening that surprises the _user_ but does not go against the way the code is designed, it should use the `enhancement` label. | | `critical` | Added to `bug` issues if the problem described makes the code completely unusable in a common situation. | | `documentation` | Added to issues or pull requests that affect any of the documentation for the project. | Can be combined with other labels, such as `bug` or `enhancement`. | | `duplicate` | Added to issues or PRs that refer to the exact same issue as another one that's been previously labeled. | Duplicate issues should be marked and closed right away, with a message referencing the issue it's a duplicate of (with `#123`) | | `enhancement` | Added to [feature requests](#request-a-feature), PRs, or documentation issues that are purely additive: the code or docs currently work as expected, but a change is being requested or suggested. | | `help wanted` | Applied by [Committers](#join-the-project-team) to issues and PRs that they would like to get outside help for. Generally, this means it's lower priority for the maintainer team to itself implement, but that the community is encouraged to pick up if they so desire | Never applied on first-pass labeling. | | `in-progress` | Applied by [Committers](#join-the-project-team) to PRs that are pending some work before they're ready for review. | The original PR submitter should @mention the team member that applied the label once the PR is complete. | | `performance` | This issue or PR is directly related to improving performance. | | `refactor` | Added to issues or PRs that deal with cleaning up or modifying the project for the betterment of it. | | `starter` | Applied by [Committers](#join-the-project-team) to issues that they consider good introductions to the project for people who have not contributed before. These are not necessarily "easy", but rather focused around how much context is necessary in order to understand what needs to be done for this project in particular. | Existing project members are expected to stay away from these unless they increase in priority. | | `support` | This issue is either asking a question about how to use the project, clarifying the reason for unexpected behavior, or possibly reporting a `bug` but does not have enough detail yet to determine whether it would count as such. | The label should be switched to `bug` if reliable reproduction steps are provided. Issues primarily with unintended configurations of a user's environment are not considered bugs, even if they cause crashes. | | `tests` | This issue or PR either requests or adds primarily tests to the project. | If a PR is pending tests, that will be handled through the [PR review process](#review-pull-requests) | | `wontfix` | Labelers may apply this label to issues that clearly have nothing at all to do with the project or are otherwise entirely outside of its scope/sphere of influence. [Committers](#join-the-project-team) may apply this label and close an issue or PR if they decide to pass on an otherwise relevant issue. | The issue or PR should be closed as soon as the label is applied, and a clear explanation provided of why the label was used. Contributors are free to contest the labeling, but the decision ultimately falls on committers as to whether to accept something or not. | ## Clean Up Issues and PRs [Needs Collaborator](#join-the-project-team): Issue Tracker Issues and PRs can go stale after a while. Maybe they're abandoned. Maybe the team will just plain not have time to address them any time soon. In these cases, they should be closed until they're brought up again or the interaction starts over. To clean up issues and PRs: - Search the issue tracker for issues or PRs, and add the term `updated:<=YYYY-MM-DD`, where the date is 30 days before today. - Go through each issue _from oldest to newest_, and close them if **all of the following are true**: - not opened by a maintainer - not marked as `critical` - not marked as `starter` or `help wanted` (these might stick around for a while, in general, as they're intended to be available) - no explicit messages in the comments asking for it to be left open - does not belong to a milestone - Leave a message when closing saying "Cleaning up stale issue. Please reopen or ping us if and when you're ready to resume this. See https://github.com/zkat/ssri-rs/blob/latest/CONTRIBUTING.md#clean-up-issues-and-prs for more details." ## Review Pull Requests [Needs Collaborator](#join-the-project-team): Issue Tracker While anyone can comment on a PR, add feedback, etc, PRs are only _approved_ by team members with Issue Tracker or higher permissions. PR reviews use [GitHub's own review feature](https://help.github.com/articles/about-pull-request-reviews/), which manages comments, approval, and review iteration. Some notes: - You may ask for minor changes ("nitpicks"), but consider whether they are really blockers to merging: try to err on the side of "approve, with comments". - _ALL PULL REQUESTS_ should be covered by a test: either by a previously-failing test, an existing test that covers the entire functionality of the submitted code, or new tests to verify any new/changed behavior. All tests must also pass and follow established conventions. Test coverage should not drop, unless the specific case is considered reasonable by maintainers. - Please make sure you're familiar with the code or documentation being updated, unless it's a minor change (spellchecking, minor formatting, etc). You may @mention another project member who you think is better suited for the review, but still provide a non-approving review of your own. - Be extra kind: people who submit code/doc contributions are putting themselves in a pretty vulnerable position, and have put time and care into what they've done (even if that's not obvious to you!) -- always respond with respect, be understanding, but don't feel like you need to sacrifice your standards for their sake, either. Just don't be a jerk about it? ## Merge Pull Requests [Needs Collaborator](#join-the-project-team): Committer TBD - need to hash out a bit more of this process. ## Tag A Release [Needs Collaborator](#join-the-project-team): Committer TBD - need to hash out a bit more of this process. The most important bit here is probably that all tests must pass, and tags must use [semver](https://semver.org). ## Join the Project Team ### Ways to Join There are many ways to contribute! Most of them don't require any official status unless otherwise noted. That said, there's a couple of positions that grant special repository abilities, and this section describes how they're granted and what they do. All of the below positions are granted based on the project team's needs, as well as their consensus opinion about whether they would like to work with the person and think that they would fit well into that position. The process is relatively informal, and it's likely that people who express interest in participating can just be granted the permissions they'd like. You can spot a collaborator on the repo by looking for the `[Collaborator]` or `[Owner]` tags next to their names. | Permission | Description | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Issue Tracker | Granted to contributors who express a strong interest in spending time on the project's issue tracker. These tasks are mainly [labeling issues](#label-issues), [cleaning up old ones](#clean-up-issues-and-prs), and [reviewing pull requests](#review-pull-requests), as well as all the usual things non-team-member contributors can do. Issue handlers should not merge pull requests, tag releases, or directly commit code themselves: that should still be done through the usual pull request process. Becoming an Issue Handler means the project team trusts you to understand enough of the team's process and context to implement it on the issue tracker. | | Committer | Granted to contributors who want to handle the actual pull request merges, tagging new versions, etc. Committers should have a good level of familiarity with the codebase, and enough context to understand the implications of various changes, as well as a good sense of the will and expectations of the project team. | | Admin/Owner | Granted to people ultimately responsible for the project, its community, etc. | ## Attribution This guide was generated using the WeAllJS `CONTRIBUTING.md` generator. [Make your own](https://npm.im/weallcontribute)! ssri-9.2.0/Cargo.toml0000644000000025030000000000100100220ustar # 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.57.0" name = "ssri" version = "9.2.0" authors = ["Kat Marchán "] description = "Various utilities for handling Subresource Integrity." homepage = "https://github.com/zkat/ssri-rs" readme = "README.md" license = "Apache-2.0" repository = "https://github.com/zkat/ssri-rs" [dependencies.base64] version = "0.21.0" [dependencies.digest] version = "0.10.6" [dependencies.hex] version = "0.4.3" [dependencies.miette] version = "5.7.0" [dependencies.serde] version = "1.0.152" optional = true [dependencies.sha-1] version = "0.10.0" [dependencies.sha2] version = "0.10.6" [dependencies.thiserror] version = "1.0.40" [dependencies.xxhash-rust] version = "0.8.6" features = ["xxh3"] [dev-dependencies.serde_derive] version = "1.0.152" [dev-dependencies.serde_json] version = "1.0.93" [features] default = ["serde"] ssri-9.2.0/Cargo.toml.orig000064400000000000000000000012420072674642500135320ustar 00000000000000[package] name = "ssri" version = "9.2.0" authors = ["Kat Marchán "] edition = "2018" description = "Various utilities for handling Subresource Integrity." license = "Apache-2.0" repository = "https://github.com/zkat/ssri-rs" homepage = "https://github.com/zkat/ssri-rs" readme = "README.md" rust-version = "1.57.0" [dependencies] base64 = "0.21.0" digest = "0.10.6" hex = "0.4.3" miette = "5.7.0" serde = { version = "1.0.152", optional = true } sha-1 = "0.10.0" sha2 = "0.10.6" thiserror = "1.0.40" xxhash-rust = { version = "0.8.6", features = ["xxh3"] } [features] default = ["serde"] [dev-dependencies] serde_derive = "1.0.152" serde_json = "1.0.93" ssri-9.2.0/LICENSE.md000064400000000000000000000010770072674642500122550ustar 00000000000000Copyright 2019 Cacache Contributors 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. ssri-9.2.0/Makefile.toml000064400000000000000000000004240072674642500132560ustar 00000000000000[tasks.changelog] workspace=false install_crate="git-cliff" command = "git-cliff" args = ["--prepend", "CHANGELOG.md", "-u", "--tag", "${@}"] [tasks.release] workspace=false install_crate="cargo-release" command = "cargo" args = ["release", "--workspace", "${@}"] ssri-9.2.0/README.md000064400000000000000000000046040072674642500121270ustar 00000000000000# ssri [`ssri`](https://github.com/zkat/ssri-rs), short for Standard Subresource Integrity, is a Rust library for parsing, manipulating, serializing, generating, and verifying [Subresource Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) hashes. ## Example Parse a string as [`Integrity`](struct.Integrity.html) to convert it to a struct: ```rust use ssri::Integrity; let source = "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="; let parsed: Integrity = source.parse().unwrap(); assert_eq!(parsed.to_string(), source) ``` Generating a new hash from file data: ```rust use ssri::Integrity; // By default, generates Integrity as Sha256. // Use IntegrityOpts to pick the algorithm yourself. let sri = Integrity::from(b"hello world"); assert_eq!(sri.to_string(), "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="); ``` Verifying data against an SRI: ```rust use ssri::{Integrity, Algorithm}; let sri = Integrity::from(b"hello world"); assert_eq!(sri.check(b"hello world").unwrap(), Algorithm::Sha256); ``` You can also use [`IntegrityOpts`](struct.IntegrityOpts.html) and [`IntegrityChecker`](struct.IntegrityChecker.html) to generate and check subresource integrity, respectively. These allow things like multiple algorithms, and incremental/streamed data input. ## Install Using [`cargo-edit`](https://crates.io/crates/cargo-edit) `$ cargo add ssri` ## Documentation - [API Docs](https://docs.rs/ssri) ## Features - Parses and stringifies [Subresource Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) strings. - Generates SRI strings from raw data. - Strict standard compliance. - Multiple entries for the same algorithm. ## Contributing The ssri team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. All participants and maintainers in this project are expected to follow [Code of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each other. Happy hacking! ## License This project is licensed under [the Apache-2.0 License](LICENSE.md). ssri-9.2.0/cliff.toml000064400000000000000000000036470072674642500126360ustar 00000000000000# configuration file for git-cliff (0.1.0) [changelog] # changelog header header = """ # `ssri` Release Changelog """ # template for the changelog body # https://tera.netlify.app/docs/#introduction body = """ {% if version %}\ ## {{ version | replace(from="v", to="") }} ({{ timestamp | date(format="%Y-%m-%d") }}) {% else %}\ ## Unreleased {% endif %}\ {% for group, commits in commits | filter(attribute="scope") | group_by(attribute="group") %} ### {{ group | upper_first }} {% for commit in commits %} {% if commit.scope %}\ * **{{ commit.scope }}:** {{ commit.message }} ([{{ commit.id | truncate(length=8, end="") }}](https://github.com/zkat/ssri-rs/commit/{{ commit.id }})) {%- if commit.breaking %} * **BREAKING CHANGE**: {{ commit.breaking_description }} {%- endif %}\ {% endif %}\ {% endfor %} {% endfor %} """ # remove the leading and trailing whitespace from the template trim = false # changelog footer # footer = """ # # """ [git] # allow only conventional commits # https://www.conventionalcommits.org conventional_commits = true # regex for parsing and grouping commits commit_parsers = [ { message = "^feat*", group = "Features"}, { message = "^fix*", group = "Bug Fixes"}, { message = "^doc*", group = "Documentation"}, { message = "^perf*", group = "Performance"}, { message = "^refactor*", group = "Refactor"}, { message = "^style*", group = "Styling"}, { message = "^test*", group = "Testing"}, { message = "^chore\\(release\\): prepare for*", skip = true}, { message = "^chore*", group = "Miscellaneous Tasks"}, { body = ".*security", group = "Security"}, ] # filter out the commits that are not matched by commit parsers filter_commits = true # glob pattern for matching git tags # tag_pattern = "v?[0-9]*" # regex for skipping tags # skip_tags = "v0.1.0-beta.1" ssri-9.2.0/clippy.toml000064400000000000000000000000200072674642500130310ustar 00000000000000msrv = "1.57.0" ssri-9.2.0/src/algorithm.rs000064400000000000000000000040650072674642500137740ustar 00000000000000use std::fmt; use crate::errors::Error; /** Valid algorithms for integrity strings. `Sha1` and `Xxh3` are special cases in this library--they're not allowed by the current SRI spec, but they're useful enough that having first-class support makes sense. They should also be completely harmless to have in your strings if you do use it in a browser context--they just won't be used. */ #[non_exhaustive] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Algorithm { Sha512, Sha384, Sha256, Sha1, /// xxh3 is a non-cryptographic hash function that is very fast and can be /// used to speed up integrity calculations, at the cost of /// cryptographically-secure guarantees. /// /// `ssri` uses 128-bit xxh3 hashes, which have been shown to have no /// conflicts even on billions of hashes. Xxh3, } impl fmt::Display for Algorithm { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", format!("{:?}", self).to_lowercase()) } } impl std::str::FromStr for Algorithm { type Err = Error; fn from_str(s: &str) -> Result { match s { "sha1" => Ok(Algorithm::Sha1), "sha256" => Ok(Algorithm::Sha256), "sha384" => Ok(Algorithm::Sha384), "sha512" => Ok(Algorithm::Sha512), "xxh3" => Ok(Algorithm::Xxh3), _ => Err(Error::ParseIntegrityError(s.into())), } } } #[cfg(test)] mod tests { use super::Algorithm::*; #[test] fn algorithm_formatting() { assert_eq!(format!("{}", Sha1), "sha1"); assert_eq!(format!("{}", Sha256), "sha256"); assert_eq!(format!("{}", Sha384), "sha384"); assert_eq!(format!("{}", Sha512), "sha512"); assert_eq!(format!("{}", Xxh3), "xxh3"); } #[test] fn ordering() { let mut arr = [Sha1, Sha256, Sha384, Sha512, Xxh3]; arr.sort_unstable(); assert_eq!(arr, [Sha512, Sha384, Sha256, Sha1, Xxh3]) } } ssri-9.2.0/src/checker.rs000064400000000000000000000045710072674642500134140ustar 00000000000000use crate::algorithm::Algorithm; use crate::integrity::Integrity; use crate::opts::IntegrityOpts; use crate::Error; /** Check data against an [`Integrity`](struct.Integrity.html). # Examples ``` # use ssri::{Algorithm, Integrity, IntegrityChecker}; let data = b"hello world"; let sri = Integrity::from(&data); let checker = IntegrityChecker::new(sri).chain(&data); assert_eq!(checker.result().unwrap(), Algorithm::Sha256); ``` */ #[derive(Debug)] pub struct IntegrityChecker { sri: Integrity, builder: IntegrityOpts, } impl IntegrityChecker { /// Creates a new `IntegrityChecker` builder. Use this to verify chunked /// data. pub fn new(sri: Integrity) -> IntegrityChecker { let builder = IntegrityOpts::new().algorithm(sri.pick_algorithm()); IntegrityChecker { sri, builder } } /// Add some data to the running checker. pub fn input>(&mut self, data: B) { self.builder.input(data); } /// Same as `IntegrityChecker::input`, but allows chained calls. pub fn chain>(mut self, data: B) -> Self { self.builder.input(data); self } /// Returns the matching algorithm if the inputted data matches the input `Integrity`. pub fn result(self) -> Result { let sri = self.builder.result(); let algo = self.sri.pick_algorithm(); let wanted = self.sri; wanted .hashes .iter() .take_while(|h| h.algorithm == algo) .find(|&h| *h == sri.hashes[0]) .map(|_| algo) .ok_or(Error::IntegrityCheckError(wanted, sri)) } } #[cfg(test)] mod tests { use super::Algorithm; use super::Integrity; use super::IntegrityChecker; #[test] fn basic_test() { let sri = Integrity::from(b"hello world"); let result = IntegrityChecker::new(sri).chain(b"hello world").result(); assert_eq!(result.unwrap(), Algorithm::Sha256) } #[test] fn multi_hash() { let sri = "sha256-deadbeef" .parse::() .unwrap() .concat(Integrity::from(b"hello world")); eprintln!("\n{}", sri); let result = IntegrityChecker::new(sri).chain(b"hello world").result(); assert_eq!(result.unwrap(), Algorithm::Sha256) } } ssri-9.2.0/src/errors.rs000064400000000000000000000015100072674642500133120ustar 00000000000000use miette::Diagnostic; use thiserror::Error; use crate::Integrity; /// Integrity-related error values. #[derive(Diagnostic, Error, Debug, Clone, PartialEq, Eq)] pub enum Error { /// Error parsing an SRI string into an Integrity object. #[error("Failed to parse subresource integrity string: {0}")] #[diagnostic(code(ssri::parse_integrity_error), url(docsrs))] ParseIntegrityError(String), /// Error matching two Integrity values. #[error("Integrity check failed.\n\tWanted: {0}\n\tActual: {1}")] #[diagnostic(code(ssri::integrity_check_error), url(docsrs))] IntegrityCheckError(Integrity, Integrity), /// Error Decoding Hex Data #[error("Failed decode hexadecimal data, reason: {0}")] #[diagnostic(code(ssri::hex_decode_error), url(docsrs))] HexDecodeError(String), } ssri-9.2.0/src/hash.rs000064400000000000000000000073330072674642500127320ustar 00000000000000use std::cmp::Ordering; use std::fmt; use crate::algorithm::Algorithm; use crate::errors::Error; /** Represents a single algorithm/digest pair. This is mostly internal, although users might interact with it directly on occasion. */ #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Hash { pub algorithm: Algorithm, pub digest: String, } impl PartialOrd for Hash { fn partial_cmp(&self, other: &Hash) -> Option { Some(self.cmp(other)) } } impl Ord for Hash { fn cmp(&self, other: &Hash) -> Ordering { self.algorithm.cmp(&other.algorithm) } } impl fmt::Display for Hash { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}-{}", self.algorithm, self.digest) } } impl std::str::FromStr for Hash { type Err = Error; /// Tries to parse a [&str] into a [struct@Hash]. /// Note the length of the digest is not validated to encode the number of /// bytes expected by the chosen hash algorithm. fn from_str(s: &str) -> Result { let mut parsed = s.trim().split(|c| c == '-'); let algorithm = parsed .next() .ok_or_else(|| Error::ParseIntegrityError(s.into()))? .parse()?; let digest = String::from( parsed .next() .ok_or_else(|| Error::ParseIntegrityError(s.into()))?, ); Ok(Hash { algorithm, digest }) } } #[cfg(test)] mod tests { use super::Algorithm; use super::Hash; #[test] fn hash_stringify() { assert_eq!( format!( "{}", Hash { algorithm: Algorithm::Sha256, digest: String::from("deadbeef==") } ), "sha256-deadbeef==" ) } #[test] fn parsing() { assert_eq!( " sha256-deadbeef== \n".parse::().unwrap(), Hash { algorithm: Algorithm::Sha256, digest: String::from("deadbeef==") } ) } #[test] #[should_panic] fn bad_algorithm() { // TODO - test the actual error returned when it's more valuable "sha7-deadbeef==".parse::().unwrap(); } #[test] fn ordering() { let mut arr = [ Hash { algorithm: Algorithm::Sha1, digest: String::from("foo=="), }, Hash { algorithm: Algorithm::Sha256, digest: String::from("foo=="), }, Hash { algorithm: Algorithm::Sha384, digest: String::from("foo=="), }, Hash { algorithm: Algorithm::Sha512, digest: String::from("foo=="), }, Hash { algorithm: Algorithm::Xxh3, digest: String::from("foo=="), }, ]; arr.sort_unstable(); assert_eq!( arr, [ Hash { algorithm: Algorithm::Sha512, digest: String::from("foo==") }, Hash { algorithm: Algorithm::Sha384, digest: String::from("foo==") }, Hash { algorithm: Algorithm::Sha256, digest: String::from("foo==") }, Hash { algorithm: Algorithm::Sha1, digest: String::from("foo==") }, Hash { algorithm: Algorithm::Xxh3, digest: String::from("foo==") } ] ) } } ssri-9.2.0/src/integrity.rs000064400000000000000000000233700072674642500140240ustar 00000000000000use std::fmt; use crate::algorithm::Algorithm; use crate::checker::IntegrityChecker; use crate::errors::Error; use crate::hash::Hash; use crate::opts::IntegrityOpts; use base64::Engine as _; #[cfg(feature = "serde")] use serde::de::{self, Deserialize, Deserializer, Visitor}; #[cfg(feature = "serde")] use serde::ser::{Serialize, Serializer}; /** Representation of a full [Subresource Integrity string](https://w3c.github.io/webappsec/specs/subresourceintegrity/). `Integrity` can be used for parsing and also includes convenience methods for shorthand versions of [`IntegrityOpts`](struct.IntegrityOpts.html) and [`IntegrityChecker`](struct.IntegrityChecker.html). # Example ``` # use ssri::Integrity; let source = "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="; let parsed: Integrity = source.parse().unwrap(); assert_eq!(parsed.to_string(), source); ``` */ #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Integrity { pub hashes: Vec, } impl fmt::Display for Integrity { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", self.hashes .iter() .map(|h| h.to_string()) .collect::>() .join(" ") ) } } impl std::str::FromStr for Integrity { type Err = Error; /// Parses a string into an Integrity instance. /// /// # Example /// ``` /// use ssri::Integrity; /// let sri: Integrity = "sha256-deadbeef".parse().unwrap(); /// assert_eq!(sri.to_string(), String::from("sha256-deadbeef")); /// ``` fn from_str(s: &str) -> Result { let mut hashes = String::from(s) .split_whitespace() .map(|x| x.parse()) .collect::, Self::Err>>()?; hashes.sort(); Ok(Integrity { hashes }) } } #[cfg(feature = "serde")] impl Serialize for Integrity { fn serialize(&self, serializer: S) -> std::result::Result where S: Serializer, { serializer.collect_str(self) } } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for Integrity { fn deserialize(deserializer: D) -> std::result::Result where D: Deserializer<'de>, { struct IntegrityVisitor; impl<'de> Visitor<'de> for IntegrityVisitor { type Value = Integrity; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an Integrity object as a string") } fn visit_str(self, v: &str) -> std::result::Result where E: de::Error, { v.parse::().map_err(de::Error::custom) } } deserializer.deserialize_str(IntegrityVisitor) } } impl Integrity { /// Pick the most secure available `Algorithm` in this `Integrity`. /// /// # Example /// ``` /// use ssri::{Integrity, Algorithm}; /// /// let sri: Integrity = "sha1-deadbeef sha256-badc0ffee".parse().unwrap(); /// let algorithm = sri.pick_algorithm(); /// assert_eq!(algorithm, Algorithm::Sha256); /// ``` pub fn pick_algorithm(&self) -> Algorithm { self.hashes[0].algorithm } /// Create a new `Integrity` based on `data`. Use /// [`IntegrityOpts`](struct.IntegrityOpts.html) for more options. /// /// # Example /// ``` /// use ssri::Integrity; /// let sri = Integrity::from(b"hello"); /// assert_eq!(sri.to_string(), "sha256-LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=".to_owned()); /// ``` pub fn from>(data: B) -> Integrity { IntegrityOpts::new() .algorithm(Algorithm::Sha256) .chain(&data) .result() } /// Converts a hex string obtained from `to_hex()` to an `Integrity` with a `Hash` containing algorithm and decoded hex string. /// /// # Example ///``` /// use ssri::{Integrity, Algorithm}; /// /// let expected = Integrity::from(b"hello"); /// let hex = String::from("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); /// assert_eq!(Integrity::from_hex(hex, Algorithm::Sha256).unwrap(), expected); ///``` pub fn from_hex>(hex: B, algorithm: Algorithm) -> Result { let b16 = hex::decode(hex).map_err(|e| Error::HexDecodeError(e.to_string()))?; let digest = base64::prelude::BASE64_STANDARD.encode(b16); Ok(Integrity { hashes: vec![Hash { algorithm, digest }], }) } /// Join together two `Integrity` instances. Hashes will be grouped and /// sorted by algorithm but otherwise kept in the same order. /// /// # Example /// ``` /// use ssri::Integrity; /// let sri1: Integrity = "sha256-deadbeef".parse().unwrap(); /// let sri2: Integrity = "sha256-badc0ffee".parse().unwrap(); /// let sri3 = sri1.concat(sri2); /// assert_eq!(sri3.to_string(), "sha256-deadbeef sha256-badc0ffee".to_owned()); /// ``` pub fn concat(&self, other: Integrity) -> Self { let mut hashes = [self.hashes.clone(), other.hashes].concat(); hashes.sort(); hashes.dedup(); Integrity { hashes } } /// Check some data against this `Integrity`. For more options, use /// [`Checker`](struct.Checker.html). /// /// # Example /// ``` /// use ssri::{Algorithm, Integrity}; /// /// let sri = Integrity::from(b"hello"); /// let algorithm = sri.check(b"hello").unwrap(); /// assert_eq!(algorithm, Algorithm::Sha256); /// ``` pub fn check>(&self, data: B) -> Result { let mut checker = IntegrityChecker::new(self.clone()); checker.input(&data); checker.result() } /// Converts the first `Hash` in this `Integrity` into its hex string /// format. /// /// # Example /// ``` /// use ssri::{Algorithm, Integrity}; /// /// let sri = Integrity::from(b"hello"); /// let (algo, hex) = sri.to_hex(); /// assert_eq!(algo, Algorithm::Sha256); /// assert_eq!(hex, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824".to_owned()); /// ``` pub fn to_hex(&self) -> (Algorithm, String) { let hash = self.hashes.get(0).unwrap(); ( hash.algorithm, hex::encode( base64::prelude::BASE64_STANDARD .decode(&hash.digest) .unwrap(), ), ) } /// Compares `self` against a given SRI to see if there's a match. The /// deciding algorithm is determined by `other`. /// /// # Example /// ``` /// use ssri::{Algorithm, Integrity}; /// /// let sri1 = Integrity::from(b"hello"); /// let sri2 = Integrity::from(b"hello").concat(Integrity::from(b"world")); /// let m = sri1.matches(&sri2); /// assert_eq!(m, Some(Algorithm::Sha256)); /// ``` pub fn matches(&self, other: &Self) -> Option { let algo = other.pick_algorithm(); self.hashes .iter() .filter(|h| h.algorithm == algo) .find(|&h| { other .hashes .iter() .filter(|i| i.algorithm == algo) .any(|i| h == i) }) .map(|h| h.algorithm) } } #[cfg(test)] mod tests { use super::{Algorithm, Hash, Integrity, IntegrityOpts}; #[test] fn parse() { let sri: Integrity = "sha1-deadbeef=".parse().unwrap(); assert_eq!( sri.hashes.get(0).unwrap(), &Hash { algorithm: Algorithm::Sha1, digest: String::from("deadbeef=") } ) } #[test] fn from_hex() { let expected_integrity = Integrity::from(b"hello world"); let hex = String::from("b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"); assert_eq!( Integrity::from_hex(hex, Algorithm::Sha256).unwrap(), expected_integrity ); } #[test] fn to_hex() { let sri = Integrity::from(b"hello world"); assert_eq!( sri.to_hex(), ( Algorithm::Sha256, String::from("b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9") ) ) } #[test] fn matches() { let sri1 = IntegrityOpts::new() .algorithm(Algorithm::Sha512) .algorithm(Algorithm::Sha256) .chain(b"hello world") .result(); let sri2 = Integrity::from(b"hello world"); let sri3 = Integrity::from(b"goodbye world"); assert_eq!(sri1.matches(&sri2), Some(Algorithm::Sha256)); assert_eq!(sri1.matches(&sri3), None); assert_eq!(sri2.matches(&sri1), None) } #[test] fn de_json() { use serde_derive::Deserialize; #[derive(Debug, PartialEq, Deserialize)] struct Thing { integrity: Integrity, } let json = r#"{ "integrity": "sha1-deadbeef" }"#; let de: Thing = serde_json::from_str(json).unwrap(); assert_eq!( de, Thing { integrity: "sha1-deadbeef".parse().unwrap() } ); } #[test] fn ser_json() { use serde_derive::Serialize; #[derive(Debug, PartialEq, Serialize)] struct Thing { integrity: Integrity, } let thing = Thing { integrity: "sha1-deadbeef".parse().unwrap(), }; let ser = serde_json::to_string(&thing).unwrap(); let json = r#"{"integrity":"sha1-deadbeef"}"#; assert_eq!(ser, json); } } ssri-9.2.0/src/lib.rs000064400000000000000000000030770072674642500125560ustar 00000000000000/*! [`ssri`](https://github.com/zkat/ssri-rs), short for Standard Subresource Integrity, is a Rust library for parsing, manipulating, serializing, generating, and verifying [Subresource Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) hashes. # Examples Parse a string as [`Integrity`](struct.Integrity.html) to convert it to a struct: ``` # use ssri::Integrity; let source = "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="; let parsed: Integrity = source.parse().unwrap(); assert_eq!(parsed.to_string(), source) ``` Generating a new hash from file data: ``` # use ssri::Integrity; // By default, generates Integrity as Sha256. // Use IntegrityOpts to pick the algorithm yourself. let sri = Integrity::from(b"hello world"); assert_eq!(sri.to_string(), "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="); ``` Verifying data against an SRI: ``` # use ssri::{Integrity, Algorithm}; let sri = Integrity::from(b"hello world"); assert_eq!(sri.check(b"hello world").unwrap(), Algorithm::Sha256); ``` You can also use [`IntegrityOpts`](struct.IntegrityOpts.html) and [`IntegrityChecker`](struct.IntegrityChecker.html) to generate and check subresource integrity, respectively. These allow things like multiple algorithms, and incremental/streamed data input. */ mod algorithm; mod checker; mod errors; mod hash; mod integrity; mod opts; pub use algorithm::Algorithm::{self, *}; pub use checker::IntegrityChecker; pub use errors::Error; pub use hash::Hash; pub use integrity::Integrity; pub use opts::IntegrityOpts; ssri-9.2.0/src/opts.rs000064400000000000000000000135470072674642500130000ustar 00000000000000use std::fmt::Debug; use crate::algorithm::Algorithm; use crate::hash::Hash; use crate::integrity::Integrity; use base64::prelude::BASE64_STANDARD; use base64::Engine; use digest::Digest; #[allow(clippy::enum_variant_names)] #[non_exhaustive] #[derive(Clone)] enum Hasher { Sha1(sha1::Sha1), Sha256(sha2::Sha256), Sha384(sha2::Sha384), Sha512(sha2::Sha512), Xxh3(Box), } impl Debug for Hasher { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Sha1(arg0) => f.debug_tuple("Sha1").field(arg0).finish(), Self::Sha256(arg0) => f.debug_tuple("Sha256").field(arg0).finish(), Self::Sha384(arg0) => f.debug_tuple("Sha384").field(arg0).finish(), Self::Sha512(arg0) => f.debug_tuple("Sha512").field(arg0).finish(), Self::Xxh3(_arg0) => f.debug_tuple("Xxh3").finish(), } } } /** Builds a new [`Integrity`](struct.Integrity.html), allowing multiple algorithms and incremental input. # Examples ``` use ssri::{Algorithm, IntegrityOpts}; let contents = b"hello world"; let sri = IntegrityOpts::new() .algorithm(Algorithm::Sha512) .algorithm(Algorithm::Sha1) .chain(&contents) .result(); ``` */ #[derive(Clone, Debug, Default)] pub struct IntegrityOpts { hashers: Vec, disturbed: bool, } impl IntegrityOpts { /// Creates a new hashing IntegrityOpts. pub fn new() -> IntegrityOpts { IntegrityOpts { hashers: vec![], disturbed: false, } } /// Generate a hash for this algorithm. Can be called multiple times to generate an `Integrity` string with multiple entries. pub fn algorithm(mut self, algo: Algorithm) -> Self { if self.disturbed { panic!("Can't add new algorithms if IntegrityOpts::input() has already been called"); } self.hashers.push(match algo { Algorithm::Sha1 => Hasher::Sha1(sha1::Sha1::new()), Algorithm::Sha256 => Hasher::Sha256(sha2::Sha256::new()), Algorithm::Sha384 => Hasher::Sha384(sha2::Sha384::new()), Algorithm::Sha512 => Hasher::Sha512(sha2::Sha512::new()), Algorithm::Xxh3 => Hasher::Xxh3(Box::new(xxhash_rust::xxh3::Xxh3::new())), }); self } /// Add some data to this IntegrityOpts. All internal hashers will be updated for all configured `Algorithm`s. pub fn input>(&mut self, input: B) { let input = input.as_ref(); self.disturbed = true; for hasher in self.hashers.iter_mut() { match hasher { Hasher::Sha1(h) => digest::Digest::update(h, input), Hasher::Sha256(h) => digest::Digest::update(h, input), Hasher::Sha384(h) => digest::Digest::update(h, input), Hasher::Sha512(h) => digest::Digest::update(h, input), Hasher::Xxh3(h) => h.update(input), } } } /// Same as `IntegrityOpts::input`, but allows chaining. pub fn chain>(mut self, input: B) -> Self { self.input(&input); self } /// Resets internal state for this IntegrityOpts. pub fn reset(&mut self) { self.hashers = vec![]; self.disturbed = false; } /// Generate a new `Integrity` from the inputted data and configured algorithms. pub fn result(self) -> Integrity { let mut hashes = self .hashers .into_iter() .map(|h| { let (algorithm, data) = match h { Hasher::Sha1(h) => (Algorithm::Sha1, BASE64_STANDARD.encode(h.finalize())), Hasher::Sha256(h) => (Algorithm::Sha256, BASE64_STANDARD.encode(h.finalize())), Hasher::Sha384(h) => (Algorithm::Sha384, BASE64_STANDARD.encode(h.finalize())), Hasher::Sha512(h) => (Algorithm::Sha512, BASE64_STANDARD.encode(h.finalize())), Hasher::Xxh3(h) => ( Algorithm::Xxh3, BASE64_STANDARD.encode(h.digest128().to_be_bytes()), ), }; Hash { algorithm, digest: data, } }) .collect::>(); hashes.sort(); Integrity { hashes } } } impl digest::Update for IntegrityOpts { fn update(&mut self, data: &[u8]) { self.input(data); } fn chain(self, input: impl AsRef<[u8]>) -> Self { self.chain(input) } } impl digest::Reset for IntegrityOpts { fn reset(&mut self) { self.reset() } } impl std::io::Write for IntegrityOpts { fn write(&mut self, buf: &[u8]) -> std::io::Result { self.input(buf); Ok(buf.len()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[cfg(test)] mod tests { use super::Algorithm; use super::IntegrityOpts; #[test] fn basic_test() { let result = IntegrityOpts::new() .algorithm(Algorithm::Sha1) .algorithm(Algorithm::Sha256) .chain(b"hello world") .result(); assert_eq!( result.to_string(), "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek= sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=" ) } #[test] fn write_test() { use std::io::Write; let mut it = IntegrityOpts::new() .algorithm(Algorithm::Sha1) .algorithm(Algorithm::Sha256); let size = it.write(b"hello ").expect("failed to write bytes"); assert_eq!(6, size); let size = it.write(b"world").expect("failed to write bytes"); assert_eq!(5, size); assert_eq!( it.result().to_string(), "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek= sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=" ) } }