mirror of
https://git.asonix.dog/asonix/http-signature-normalization.git
synced 2024-09-20 19:10:00 +00:00
Compare commits
86 commits
v0.5.0-bet
...
main
Author | SHA1 | Date | |
---|---|---|---|
|
3d7b620bc0 | ||
|
07413815d5 | ||
|
c38072e65d | ||
|
47d28c6f47 | ||
|
47d07e7f1f | ||
|
b89acf7918 | ||
|
bf8e0e5f69 | ||
|
369a1e8a96 | ||
|
6e0a6fa3a2 | ||
|
f0dc14d5f1 | ||
|
92a73f0313 | ||
|
e8588efda7 | ||
|
6acd291315 | ||
|
ef266eed95 | ||
|
c1d36000dd | ||
|
ec73fe55c9 | ||
|
ff0290a488 | ||
|
ce2d14824e | ||
|
bbafc22d08 | ||
|
8750783667 | ||
|
ea964decc8 | ||
|
1f23b72140 | ||
|
e526699c87 | ||
|
cb198f6922 | ||
|
40ace55619 | ||
|
5de17a130b | ||
|
ac25b1d951 | ||
|
c7cb3ce602 | ||
|
85bbcb0bae | ||
|
b53c88fc2e | ||
|
356c801dac | ||
|
3e2639670e | ||
|
1224b3201c | ||
|
3734b8201f | ||
|
ca4e9e8b9c | ||
|
aae38f490d | ||
|
c8f1489ad9 | ||
|
2fdd82e949 | ||
|
953b75a22d | ||
|
69e607bf7a | ||
|
deec774ffc | ||
|
19d3c28116 | ||
|
878abecd4c | ||
|
670dd5129d | ||
|
0068556382 | ||
|
c5065542c8 | ||
|
8697413adb | ||
|
8c9e7af2b9 | ||
|
08e5013296 | ||
|
2720a3f4a3 | ||
|
6364794c8e | ||
|
92a6f53dd6 | ||
|
efc55fd9a1 | ||
|
82b59317cb | ||
|
68e55bee28 | ||
|
fa76edf777 | ||
|
cefea4b7ec | ||
|
1573372778 | ||
|
02b85e55d8 | ||
|
2d13b04199 | ||
|
d2f8669002 | ||
|
e02a40e3a5 | ||
|
8c8fef35fc | ||
|
c8d88b10b6 | ||
|
d10ba12dd0 | ||
|
4426030551 | ||
|
4c7affdef4 | ||
|
97c9dd3cd6 | ||
|
bc34e8e054 | ||
|
d42c0464a4 | ||
|
1c7c7ef51e | ||
|
4bd4f0f797 | ||
|
13fbb3d12a | ||
|
8667701c74 | ||
|
361d15a126 | ||
|
53be90297d | ||
|
6f286375f9 | ||
|
ad10a85e5c | ||
|
200c298de0 | ||
|
fa08da9158 | ||
|
e97cfbf925 | ||
|
6d17e67da9 | ||
|
70dfed093a | ||
|
bfcf09225b | ||
|
53fc6eeb95 | ||
|
bb42dd3f9a |
60 changed files with 7869 additions and 3108 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -2,3 +2,5 @@
|
|||
/target
|
||||
**/*.rs.bk
|
||||
Cargo.lock
|
||||
/.direnv
|
||||
/.envrc
|
||||
|
|
18
Cargo.toml
18
Cargo.toml
|
@ -1,24 +1,24 @@
|
|||
[package]
|
||||
name = "http-signature-normalization"
|
||||
description = "An HTTP Signatures library that leaves the signing to you"
|
||||
version = "0.5.4"
|
||||
version = "0.7.0"
|
||||
authors = ["asonix <asonix@asonix.dog>"]
|
||||
license-file = "LICENSE"
|
||||
license = "AGPL-3.0"
|
||||
readme = "README.md"
|
||||
repository = "https://git.asonix.dog/Aardwolf/http-signature-normalization"
|
||||
keywords = ["http", "signatures", "digest"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
"http-signature-normalization-actix",
|
||||
"http-signature-normalization-http",
|
||||
"http-signature-normalization-reqwest",
|
||||
# "http-signature-normalization-warp",
|
||||
"actix",
|
||||
"actix-extractor",
|
||||
"http",
|
||||
"reqwest",
|
||||
# "warp",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
chrono = "0.4"
|
||||
thiserror = "1.0"
|
||||
httpdate = "1"
|
||||
|
|
20
README.md
20
README.md
|
@ -41,19 +41,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
```
|
||||
|
||||
### Contributing
|
||||
Unless otherwise stated, all contributions to this project will be licensed under the CSL with
|
||||
the exceptions listed in the License section of this file.
|
||||
Feel free to open issues for anything you find an issue with. Please note that any contributed code will be licensed under the AGPLv3.
|
||||
|
||||
### License
|
||||
This work is licensed under the Cooperative Software License. This is not a Free Software
|
||||
License, but may be considered a "source-available License." For most hobbyists, self-employed
|
||||
developers, worker-owned companies, and cooperatives, this software can be used in most
|
||||
projects so long as this software is distributed under the terms of the CSL. For more
|
||||
information, see the provided LICENSE file. If none exists, the license can be found online
|
||||
[here](https://lynnesbian.space/csl/). If you are a free software project and wish to use this
|
||||
software under the terms of the GNU Affero General Public License, please contact me at
|
||||
[asonix@asonix.dog](mailto:asonix@asonix.dog) and we can sort that out. If you wish to use this
|
||||
project under any other license, especially in proprietary software, the answer is likely no.
|
||||
Copyright © 2022 Riley Trautman
|
||||
|
||||
Http Signature Normalization is currently licensed under the AGPL to the Lemmy project, found
|
||||
at [github.com/LemmyNet/lemmy](https://github.com/LemmyNet/lemmy)
|
||||
HTTP Signature Normalization is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
HTTP Signature Normalization is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. This file is part of HTTP Signature Normalization.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with HTTP Signature Normalization. If not, see [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/).
|
||||
|
|
30
actix-extractor/Cargo.toml
Normal file
30
actix-extractor/Cargo.toml
Normal file
|
@ -0,0 +1,30 @@
|
|||
[package]
|
||||
name = "http-signature-normalization-actix-extractor"
|
||||
description = "An HTTP Signatures library that leaves the signing to you"
|
||||
version = "0.2.0"
|
||||
authors = ["asonix <asonix@asonix.dog>"]
|
||||
license = "AGPL-3.0"
|
||||
readme = "README.md"
|
||||
repository = "https://git.asonix.dog/asonix/http-signature-normalization"
|
||||
documentation = "https://docs.rs/http-signature-normalization-actix-extractor"
|
||||
keywords = ["http", "signatures", "digest", "actix"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[features]
|
||||
default = ["sha-2"]
|
||||
sha-2 = ["base64", "sha2", "subtle"]
|
||||
|
||||
[dependencies]
|
||||
base64 = { version = "0.13", optional = true }
|
||||
actix-web = { version = "4", default-features = false }
|
||||
actix-web-lab = "0.18.5"
|
||||
async-trait = "0.1.58"
|
||||
http-signature-normalization = { version = "0.7", path = "../" }
|
||||
sha2 = { version = "0.10", optional = true }
|
||||
subtle = { version = "2.4.1", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "4", features = ["macros"] }
|
||||
openssl = { version = "0.10.43", features = ["vendored"] }
|
||||
thiserror = "1"
|
661
actix-extractor/LICENSE
Normal file
661
actix-extractor/LICENSE
Normal file
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
123
actix-extractor/README.md
Normal file
123
actix-extractor/README.md
Normal file
|
@ -0,0 +1,123 @@
|
|||
# Http Signature Normalization Actix-Web Extractor
|
||||
_Experimental Extractor for request signatures_
|
||||
|
||||
- [crates.io](https://crates.io/crates/http-signature-normalization-actix-extractor)
|
||||
- [docs.rs](https://docs.rs/http-signature-normalization-actix-extractor)
|
||||
- [Hit me up on Mastodon](https://masto.asonix.dog/@asonix)
|
||||
|
||||
Http Signature Normalization is a minimal-dependency crate for producing HTTP Signatures with user-provided signing and verification. The API is simple; there's a series of steps for creation and verification with types that ensure reasonable usage. This library takes a different approach from the other implementation, which prefers Middlewares.
|
||||
|
||||
## Usage
|
||||
|
||||
This crate provides extensions the ClientRequest type from Actix Web, and provides middlewares for verifying HTTP Signatures, and optionally, Digest headers
|
||||
|
||||
#### First, add this crate to your dependencies
|
||||
```toml
|
||||
actix-rt = "2.7.0"
|
||||
actix-web = "4.0.0"
|
||||
thiserror = "1"
|
||||
http-signature-normalization-actix-extractor = "0.1.0"
|
||||
sha2 = "0.10"
|
||||
```
|
||||
|
||||
#### Then, use it in your client
|
||||
|
||||
```rust
|
||||
use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
|
||||
use http_signature_normalization_actix_extractor::{
|
||||
Algorithm, Config, ConfigGenerator, DeprecatedAlgorithm, Signed, VerifyKey,
|
||||
};
|
||||
use sha2::Sha256;
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
HttpServer::new(|| App::new().route("/", web::post().to(protected)))
|
||||
.bind("127.0.0.1:8010")?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn protected(signed_request: Signed<String, Cfg, Sha256, Key>) -> &'static str {
|
||||
let (value, signature) = signed_request.into_parts();
|
||||
|
||||
println!("{}", value);
|
||||
println!("{:#?}", signature);
|
||||
|
||||
"hewwo, mr obama"
|
||||
}
|
||||
|
||||
pub struct Cfg;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Key;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum VerifyError {
|
||||
#[error("Unsupported algorithm")]
|
||||
Algorithm,
|
||||
|
||||
#[error("Couldn't decode signature")]
|
||||
Decode,
|
||||
|
||||
#[error("Invalid key")]
|
||||
Key,
|
||||
}
|
||||
|
||||
impl ConfigGenerator for Cfg {
|
||||
fn config() -> Config {
|
||||
Config::new().require_header("accept")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait(?Send)]
|
||||
impl VerifyKey for Key {
|
||||
type Error = VerifyError;
|
||||
|
||||
async fn init(
|
||||
_: &HttpRequest,
|
||||
key_id: &str,
|
||||
algorithm: Option<&Algorithm>,
|
||||
) -> Result<Self, Self::Error> {
|
||||
match algorithm {
|
||||
Some(Algorithm::Hs2019 | Algorithm::Deprecated(DeprecatedAlgorithm::RsaSha256)) => (),
|
||||
_ => return Err(VerifyError::Algorithm),
|
||||
};
|
||||
|
||||
if key_id != "my-key-id" {
|
||||
return Err(VerifyError::Key);
|
||||
}
|
||||
|
||||
Ok(Key)
|
||||
}
|
||||
|
||||
fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error> {
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
let decoded = base64::decode(&signature).map_err(|_| VerifyError::Decode)?;
|
||||
|
||||
Ok(decoded.ct_eq(signing_string.as_bytes()).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl ResponseError for VerifyError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
HttpResponse::BadRequest().finish()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Contributing
|
||||
Feel free to open issues for anything you find an issue with. Please note that any contributed code will be licensed under the AGPLv3.
|
||||
|
||||
### License
|
||||
Copyright © 2022 Riley Trautman
|
||||
|
||||
HTTP Signature Normalization Actix Extractor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
HTTP Signature Normalization Actix Extractor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. This file is part of HTTP Signature Normalization Actix Extractor.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with HTTP Signature Normalization Actix Extractor. If not, see [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/).
|
85
actix-extractor/examples/server.rs
Normal file
85
actix-extractor/examples/server.rs
Normal file
|
@ -0,0 +1,85 @@
|
|||
use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
|
||||
use http_signature_normalization_actix_extractor::{
|
||||
Algorithm, Config, ConfigGenerator, DeprecatedAlgorithm, Signed, VerifyKey,
|
||||
};
|
||||
use sha2::Sha256;
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
HttpServer::new(|| App::new().route("/", web::post().to(protected)))
|
||||
.bind("127.0.0.1:8010")?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn protected(signed_request: Signed<String, Cfg, Sha256, Key>) -> &'static str {
|
||||
let (value, signature) = signed_request.into_parts();
|
||||
|
||||
println!("{}", value);
|
||||
println!("{:#?}", signature);
|
||||
|
||||
"hewwo, mr obama"
|
||||
}
|
||||
|
||||
pub struct Cfg;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Key;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum VerifyError {
|
||||
#[error("Unsupported algorithm")]
|
||||
Algorithm,
|
||||
|
||||
#[error("Couldn't decode signature")]
|
||||
Decode,
|
||||
|
||||
#[error("Invalid key")]
|
||||
Key,
|
||||
}
|
||||
|
||||
impl ConfigGenerator for Cfg {
|
||||
fn config() -> Config {
|
||||
Config::new().require_header("accept")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait(?Send)]
|
||||
impl VerifyKey for Key {
|
||||
type Error = VerifyError;
|
||||
|
||||
async fn init(
|
||||
_: &HttpRequest,
|
||||
key_id: &str,
|
||||
algorithm: Option<&Algorithm>,
|
||||
) -> Result<Self, Self::Error> {
|
||||
match algorithm {
|
||||
Some(Algorithm::Hs2019 | Algorithm::Deprecated(DeprecatedAlgorithm::RsaSha256)) => (),
|
||||
_ => return Err(VerifyError::Algorithm),
|
||||
};
|
||||
|
||||
if key_id != "my-key-id" {
|
||||
return Err(VerifyError::Key);
|
||||
}
|
||||
|
||||
Ok(Key)
|
||||
}
|
||||
|
||||
fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error> {
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
let decoded = base64::decode(&signature).map_err(|_| VerifyError::Decode)?;
|
||||
|
||||
Ok(decoded.ct_eq(signing_string.as_bytes()).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl ResponseError for VerifyError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
HttpResponse::BadRequest().finish()
|
||||
}
|
||||
}
|
539
actix-extractor/src/lib.rs
Normal file
539
actix-extractor/src/lib.rs
Normal file
|
@ -0,0 +1,539 @@
|
|||
#![deny(missing_docs)]
|
||||
|
||||
//! # Http Signature Normalization Actix Extractor
|
||||
//! _Experimental Extractor for request signatures_
|
||||
//!
|
||||
//! This library takes a different approach from the other implementation, which prefers
|
||||
//! Middlewares.
|
||||
//!
|
||||
//! ```rust
|
||||
//! use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
|
||||
//! use http_signature_normalization_actix_extractor::{
|
||||
//! Algorithm, Config, ConfigGenerator, DeprecatedAlgorithm, Signed, VerifyKey,
|
||||
//! };
|
||||
//! use sha2::Sha256;
|
||||
//!
|
||||
//! #[actix_web::main]
|
||||
//! async fn main() -> std::io::Result<()> {
|
||||
//! /*
|
||||
//! HttpServer::new(|| App::new().route("/", web::post().to(protected)))
|
||||
//! .bind("127.0.0.1:8010")?
|
||||
//! .run()
|
||||
//! .await
|
||||
//! */
|
||||
//! Ok(())
|
||||
//! }
|
||||
//!
|
||||
//! async fn protected(signed_request: Signed<String, Cfg, Sha256, Key>) -> &'static str {
|
||||
//! let (value, signature) = signed_request.into_parts();
|
||||
//!
|
||||
//! println!("{}", value);
|
||||
//! println!("{:#?}", signature);
|
||||
//!
|
||||
//! "hewwo, mr obama"
|
||||
//! }
|
||||
//!
|
||||
//! pub struct Cfg;
|
||||
//!
|
||||
//! #[derive(Debug)]
|
||||
//! pub struct Key;
|
||||
//!
|
||||
//! #[derive(Debug, thiserror::Error)]
|
||||
//! pub enum VerifyError {
|
||||
//! #[error("Unsupported algorithm")]
|
||||
//! Algorithm,
|
||||
//!
|
||||
//! #[error("Couldn't decode signature")]
|
||||
//! Decode,
|
||||
//!
|
||||
//! #[error("Invalid key")]
|
||||
//! Key,
|
||||
//! }
|
||||
//!
|
||||
//! impl ConfigGenerator for Cfg {
|
||||
//! fn config() -> Config {
|
||||
//! Config::new().require_header("accept")
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! #[async_trait::async_trait(?Send)]
|
||||
//! impl VerifyKey for Key {
|
||||
//! type Error = VerifyError;
|
||||
//!
|
||||
//! async fn init(
|
||||
//! _: &HttpRequest,
|
||||
//! key_id: &str,
|
||||
//! algorithm: Option<&Algorithm>,
|
||||
//! ) -> Result<Self, Self::Error> {
|
||||
//! match algorithm {
|
||||
//! Some(Algorithm::Hs2019 | Algorithm::Deprecated(DeprecatedAlgorithm::RsaSha256)) => (),
|
||||
//! _ => return Err(VerifyError::Algorithm),
|
||||
//! };
|
||||
//!
|
||||
//! if key_id != "my-key-id" {
|
||||
//! return Err(VerifyError::Key);
|
||||
//! }
|
||||
//!
|
||||
//! Ok(Key)
|
||||
//! }
|
||||
//!
|
||||
//! fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error> {
|
||||
//! use subtle::ConstantTimeEq;
|
||||
//!
|
||||
//! let decoded = base64::decode(&signature).map_err(|_| VerifyError::Decode)?;
|
||||
//!
|
||||
//! Ok(decoded.ct_eq(signing_string.as_bytes()).into())
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! impl ResponseError for VerifyError {
|
||||
//! fn status_code(&self) -> StatusCode {
|
||||
//! StatusCode::BAD_REQUEST
|
||||
//! }
|
||||
//!
|
||||
//! fn error_response(&self) -> HttpResponse {
|
||||
//! HttpResponse::BadRequest().finish()
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
pub use actix_web_lab::extract::RequestSignature;
|
||||
pub use http_signature_normalization::{
|
||||
verify::{Algorithm, DeprecatedAlgorithm},
|
||||
Config, PrepareVerifyError,
|
||||
};
|
||||
|
||||
/// An alias to simplify extracting a signed request
|
||||
/// ```rust,ignore
|
||||
/// async fn protected(_: Signed<String, (), (), Key>) -> &'static str {
|
||||
/// "hewwo, mr obama"
|
||||
/// }
|
||||
/// ```
|
||||
pub type Signed<Extractor, Config, Digest, VerifyKey> =
|
||||
RequestSignature<Extractor, SignedRequest<Config, Digest, VerifyKey>>;
|
||||
|
||||
#[cfg(feature = "sha-2")]
|
||||
mod sha2_digest;
|
||||
|
||||
#[derive(Debug)]
|
||||
/// Errors produced by the Extractor
|
||||
pub enum Error {
|
||||
/// The provided Digest header was invalid
|
||||
Digest,
|
||||
|
||||
/// The provided Signature or Authorization header was invalid
|
||||
Signature,
|
||||
|
||||
/// Another header required for verifying the signature is invalid
|
||||
InvalidHeaderValue,
|
||||
|
||||
/// There was an error preparing for verification
|
||||
PrepareVerify(PrepareVerifyError),
|
||||
}
|
||||
|
||||
/// The SignedRequest Signature scheme
|
||||
///
|
||||
/// This implements SignatureScheme to allow extracing a signed request
|
||||
pub struct SignedRequest<C, D, K> {
|
||||
config_generator: std::marker::PhantomData<C>,
|
||||
key: std::marker::PhantomData<K>,
|
||||
digest_verifier: Option<D>,
|
||||
unverified: http_signature_normalization::verify::Unverified,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// A parsed part of a Digest header
|
||||
pub struct DigestPart {
|
||||
/// The Algorithm this digest was computed with
|
||||
pub algorithm: String,
|
||||
|
||||
/// The base64-encoded digest
|
||||
pub digest: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// All the required pieces for validating a request signature
|
||||
pub struct Signature<D, K> {
|
||||
key: K,
|
||||
unverified: http_signature_normalization::verify::Unverified,
|
||||
digest_verifier: D,
|
||||
digest_parts: Option<Vec<DigestPart>>,
|
||||
}
|
||||
|
||||
/// Injects a customized [`Config`] type for signature verification
|
||||
///
|
||||
/// If you don't need to customize the `Config`, you can use `()`
|
||||
///
|
||||
/// ```rust
|
||||
/// use http_signature_normalization_actix_extractor::{Config, ConfigGenerator};
|
||||
///
|
||||
/// struct Gen;
|
||||
///
|
||||
/// impl ConfigGenerator for Gen {
|
||||
/// fn config() -> Config {
|
||||
/// Config::new()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait ConfigGenerator {
|
||||
/// Produce a new `Config`
|
||||
fn config() -> Config;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait(?Send)]
|
||||
/// Extracts a key from the request
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::{http::StatusCode, web::Data, HttpRequest, HttpResponse, ResponseError};
|
||||
/// use http_signature_normalization_actix_extractor::{Algorithm, DeprecatedAlgorithm, VerifyKey};
|
||||
/// use openssl::{hash::MessageDigest, pkey::{PKey, Public}, sign::Verifier};
|
||||
///
|
||||
/// pub struct OpenSSLPublicKey(PKey<Public>);
|
||||
///
|
||||
/// #[async_trait::async_trait(?Send)]
|
||||
/// impl VerifyKey for OpenSSLPublicKey {
|
||||
/// type Error = VerifyError;
|
||||
///
|
||||
/// async fn init(
|
||||
/// req: &HttpRequest,
|
||||
/// key_id: &str,
|
||||
/// algorithm: Option<&Algorithm>,
|
||||
/// ) -> Result<Self, Self::Error> {
|
||||
/// match algorithm {
|
||||
/// Some(Algorithm::Hs2019 | Algorithm::Deprecated(DeprecatedAlgorithm::RsaSha256)) => (),
|
||||
/// _ => return Err(VerifyError::Algorithm),
|
||||
/// };
|
||||
///
|
||||
/// if key_id != "my-key-id" {
|
||||
/// return Err(VerifyError::Key);
|
||||
/// }
|
||||
///
|
||||
/// let key = req.app_data::<Data<PKey<Public>>>().expect("Key loaded").as_ref().clone();
|
||||
///
|
||||
/// Ok(OpenSSLPublicKey(key))
|
||||
/// }
|
||||
///
|
||||
/// fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error> {
|
||||
/// let decoded = openssl::base64::decode_block(&signature).map_err(|_| VerifyError::Decode)?;
|
||||
///
|
||||
/// let verifier = Verifier::new(MessageDigest::sha256(), &self.0).map_err(|_| VerifyError::Verifier)?;
|
||||
///
|
||||
/// verifier.verify(&decoded).map_err(|_| VerifyError::Verify)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// #[derive(Debug, thiserror::Error)]
|
||||
/// pub enum VerifyError {
|
||||
/// #[error("Unsupported algorithm")]
|
||||
/// Algorithm,
|
||||
///
|
||||
/// #[error("Couldn't decode signature")]
|
||||
/// Decode,
|
||||
///
|
||||
/// #[error("Invalid key")]
|
||||
/// Key,
|
||||
///
|
||||
/// #[error("Failed to create Verifier from key")]
|
||||
/// Verifier,
|
||||
///
|
||||
/// #[error("Failed to verify signature")]
|
||||
/// Verify,
|
||||
/// }
|
||||
///
|
||||
/// impl ResponseError for VerifyError {
|
||||
/// fn status_code(&self) -> StatusCode {
|
||||
/// StatusCode::BAD_REQUEST
|
||||
/// }
|
||||
///
|
||||
/// fn error_response(&self) -> HttpResponse {
|
||||
/// HttpResponse::BadRequest().finish()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait VerifyKey: Sized + Send {
|
||||
/// Errors that can happen when extracting keys or verifying the signature
|
||||
type Error: Into<actix_web::Error>;
|
||||
|
||||
/// Extract the key from the request, given the key_id and algorithm
|
||||
async fn init(
|
||||
req: &actix_web::HttpRequest,
|
||||
key_id: &str,
|
||||
algorithm: Option<&Algorithm>,
|
||||
) -> Result<Self, Self::Error>;
|
||||
|
||||
/// Verify the signature with the given signing string
|
||||
fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error>;
|
||||
}
|
||||
|
||||
/// Verifies the Digest header from the request
|
||||
///
|
||||
/// For endpoints that do not accept request bodies, `()` can be used as the verifier
|
||||
///
|
||||
/// ### Example:
|
||||
/// ```rust
|
||||
/// use http_signature_normalization_actix_extractor::{DigestPart, VerifyDigest};
|
||||
/// use openssl::sha::Sha256;
|
||||
///
|
||||
/// struct OpenSSLSha256(Option<Sha256>);
|
||||
///
|
||||
/// impl Default for OpenSSLSha256 {
|
||||
/// fn default() -> Self {
|
||||
/// Self::new()
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl OpenSSLSha256 {
|
||||
/// fn new() -> Self {
|
||||
/// Self(Some(Sha256::new()))
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl VerifyDigest for OpenSSLSha256 {
|
||||
/// fn update(&mut self, bytes: &[u8]) {
|
||||
/// self.0.as_mut().expect("Update called after verify").update(bytes);
|
||||
/// }
|
||||
///
|
||||
/// fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
/// if let Some(decoded) = parts.iter().find_map(|p| {
|
||||
/// if p.algorithm.to_lowercase() == "sha-256" {
|
||||
/// openssl::base64::decode_block(&p.digest).ok()
|
||||
/// } else {
|
||||
/// None
|
||||
/// }
|
||||
/// }) {
|
||||
/// return openssl::memcmp::eq(
|
||||
/// &self.0.take().expect("verify called more than once").finish(),
|
||||
/// &decoded,
|
||||
/// );
|
||||
/// }
|
||||
///
|
||||
/// false
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait VerifyDigest: Default + Send + 'static {
|
||||
/// Whether to run this verifier
|
||||
const REQUIRED: bool = true;
|
||||
|
||||
/// Update the verifier with th eprovided bytes
|
||||
fn update(&mut self, bytes: &[u8]);
|
||||
|
||||
/// Given a slice of parts, verify that the one matching the current verifier is valid
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool;
|
||||
}
|
||||
|
||||
trait DigestName {
|
||||
const NAME: &'static str;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait(?Send)]
|
||||
impl<C, D, K> actix_web_lab::extract::RequestSignatureScheme for SignedRequest<C, D, K>
|
||||
where
|
||||
C: ConfigGenerator,
|
||||
D: VerifyDigest,
|
||||
K: VerifyKey,
|
||||
{
|
||||
type Signature = Signature<D, K>;
|
||||
|
||||
type Error = actix_web::Error;
|
||||
|
||||
async fn init(req: &actix_web::HttpRequest) -> Result<Self, Self::Error> {
|
||||
let config = C::config();
|
||||
|
||||
let unverified = begin_verify(
|
||||
&config,
|
||||
req.method(),
|
||||
req.uri().path_and_query(),
|
||||
req.headers(),
|
||||
)?;
|
||||
|
||||
Ok(SignedRequest {
|
||||
config_generator: std::marker::PhantomData,
|
||||
key: std::marker::PhantomData,
|
||||
digest_verifier: Some(D::default()),
|
||||
unverified,
|
||||
})
|
||||
}
|
||||
|
||||
async fn consume_chunk(
|
||||
&mut self,
|
||||
_: &actix_web::HttpRequest,
|
||||
chunk: actix_web::web::Bytes,
|
||||
) -> Result<(), Self::Error> {
|
||||
if D::REQUIRED {
|
||||
let mut verifier = self
|
||||
.digest_verifier
|
||||
.take()
|
||||
.expect("consume_chunk polled concurrently");
|
||||
|
||||
self.digest_verifier = Some(
|
||||
actix_web::web::block(move || {
|
||||
verifier.update(&chunk);
|
||||
verifier
|
||||
})
|
||||
.await
|
||||
.expect("Panic in verifier update"),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn finalize(
|
||||
mut self,
|
||||
req: &actix_web::HttpRequest,
|
||||
) -> Result<Self::Signature, Self::Error> {
|
||||
let key = K::init(req, self.unverified.key_id(), self.unverified.algorithm())
|
||||
.await
|
||||
.map_err(Into::into)?;
|
||||
|
||||
let digest_parts = if D::REQUIRED {
|
||||
req.headers().get("digest").and_then(parse_digest)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(Signature {
|
||||
key,
|
||||
unverified: self.unverified,
|
||||
digest_verifier: self
|
||||
.digest_verifier
|
||||
.take()
|
||||
.expect("finalize called more than once"),
|
||||
digest_parts,
|
||||
})
|
||||
}
|
||||
|
||||
fn verify(
|
||||
signature: Self::Signature,
|
||||
_: &actix_web::HttpRequest,
|
||||
) -> Result<Self::Signature, Self::Error> {
|
||||
let Signature {
|
||||
mut key,
|
||||
unverified,
|
||||
mut digest_verifier,
|
||||
digest_parts,
|
||||
} = signature;
|
||||
|
||||
if !unverified
|
||||
.verify(|sig, signing_string| key.verify(sig, signing_string))
|
||||
.map_err(Into::into)?
|
||||
{
|
||||
return Err(Error::Signature.into());
|
||||
}
|
||||
|
||||
if D::REQUIRED && !digest_verifier.verify(digest_parts.as_deref().unwrap_or(&[])) {
|
||||
return Err(Error::Digest.into());
|
||||
}
|
||||
|
||||
let signature = Signature {
|
||||
key,
|
||||
unverified,
|
||||
digest_verifier,
|
||||
digest_parts,
|
||||
};
|
||||
|
||||
Ok(signature)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_digest(h: &actix_web::http::header::HeaderValue) -> Option<Vec<DigestPart>> {
|
||||
let h = h.to_str().ok()?.split(';').next()?;
|
||||
let v: Vec<_> = h
|
||||
.split(',')
|
||||
.filter_map(|p| {
|
||||
let mut iter = p.splitn(2, '=');
|
||||
iter.next()
|
||||
.and_then(|alg| iter.next().map(|value| (alg, value)))
|
||||
})
|
||||
.map(|(alg, value)| DigestPart {
|
||||
algorithm: alg.to_owned(),
|
||||
digest: value.to_owned(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
if v.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(v)
|
||||
}
|
||||
}
|
||||
|
||||
fn begin_verify(
|
||||
config: &Config,
|
||||
method: &actix_web::http::Method,
|
||||
path_and_query: Option<&actix_web::http::uri::PathAndQuery>,
|
||||
headers: &actix_web::http::header::HeaderMap,
|
||||
) -> Result<http_signature_normalization::verify::Unverified, Error> {
|
||||
let headers = headers
|
||||
.iter()
|
||||
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
|
||||
.collect::<Result<std::collections::BTreeMap<_, _>, actix_web::http::header::ToStrError>>(
|
||||
)?;
|
||||
|
||||
let path_and_query = path_and_query
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or_else(|| "/".to_string());
|
||||
|
||||
let unverified = config.begin_verify(method.as_ref(), &path_and_query, headers)?;
|
||||
|
||||
Ok(unverified)
|
||||
}
|
||||
|
||||
impl ConfigGenerator for () {
|
||||
fn config() -> Config {
|
||||
Config::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl VerifyDigest for () {
|
||||
const REQUIRED: bool = false;
|
||||
fn update(&mut self, _: &[u8]) {}
|
||||
fn verify(&mut self, _: &[DigestPart]) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Digest => write!(f, "Digest is inavlid"),
|
||||
Self::Signature => write!(f, "Signature is invalid"),
|
||||
Self::InvalidHeaderValue => write!(f, "Invalid header value"),
|
||||
Self::PrepareVerify(_) => write!(f, "Error preparint verification"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::PrepareVerify(ref e) => Some(e),
|
||||
Self::Digest => None,
|
||||
Self::Signature => None,
|
||||
Self::InvalidHeaderValue => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl actix_web::ResponseError for Error {
|
||||
fn status_code(&self) -> actix_web::http::StatusCode {
|
||||
actix_web::http::StatusCode::BAD_REQUEST
|
||||
}
|
||||
|
||||
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
|
||||
actix_web::HttpResponse::build(self.status_code()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PrepareVerifyError> for Error {
|
||||
fn from(e: PrepareVerifyError) -> Self {
|
||||
Error::PrepareVerify(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<actix_web::http::header::ToStrError> for Error {
|
||||
fn from(_: actix_web::http::header::ToStrError) -> Self {
|
||||
Error::InvalidHeaderValue
|
||||
}
|
||||
}
|
78
actix-extractor/src/sha2_digest.rs
Normal file
78
actix-extractor/src/sha2_digest.rs
Normal file
|
@ -0,0 +1,78 @@
|
|||
use crate::{DigestName, DigestPart, VerifyDigest};
|
||||
use sha2::{Sha224, Sha256, Sha384, Sha512};
|
||||
|
||||
impl DigestName for Sha224 {
|
||||
const NAME: &'static str = "SHA-244";
|
||||
}
|
||||
|
||||
impl DigestName for Sha256 {
|
||||
const NAME: &'static str = "SHA-256";
|
||||
}
|
||||
|
||||
impl DigestName for Sha384 {
|
||||
const NAME: &'static str = "SHA-384";
|
||||
}
|
||||
|
||||
impl DigestName for Sha512 {
|
||||
const NAME: &'static str = "SHA-512";
|
||||
}
|
||||
|
||||
fn verify<D: sha2::Digest + sha2::digest::FixedOutputReset>(
|
||||
digest: &mut D,
|
||||
name: &str,
|
||||
parts: &[DigestPart],
|
||||
) -> bool {
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
if let Some(decoded) = parts.iter().find_map(|p| {
|
||||
if p.algorithm.to_lowercase() == name.to_lowercase() {
|
||||
base64::decode(&p.digest).ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}) {
|
||||
return digest.finalize_reset().ct_eq(&decoded).into();
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
impl VerifyDigest for Sha224 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl VerifyDigest for Sha256 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl VerifyDigest for Sha384 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl VerifyDigest for Sha512 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
54
actix/Cargo.toml
Normal file
54
actix/Cargo.toml
Normal file
|
@ -0,0 +1,54 @@
|
|||
[package]
|
||||
name = "http-signature-normalization-actix"
|
||||
description = "An HTTP Signatures library that leaves the signing to you"
|
||||
version = "0.11.1"
|
||||
authors = ["asonix <asonix@asonix.dog>"]
|
||||
license = "AGPL-3.0"
|
||||
readme = "README.md"
|
||||
repository = "https://git.asonix.dog/Aardwolf/http-signature-normalization"
|
||||
keywords = ["http", "signatures", "digest", "actix"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[features]
|
||||
default = ["server", "sha-2", "sha-3"]
|
||||
client = ["dep:awc"]
|
||||
digest = ["dep:base64"]
|
||||
server = ["dep:actix-web"]
|
||||
sha-2 = ["digest", "dep:sha2"]
|
||||
sha-3 = ["digest", "dep:sha3"]
|
||||
ring = ["digest", "dep:ring"]
|
||||
|
||||
[[example]]
|
||||
name = "server"
|
||||
required-features = ["server", "ring"]
|
||||
|
||||
[[example]]
|
||||
name = "client"
|
||||
required-features = ["client", "ring"]
|
||||
|
||||
[dependencies]
|
||||
actix-http = { version = "3.0.2", default-features = false }
|
||||
actix-rt = "2.6.0"
|
||||
actix-web = { version = "4.0.0", default-features = false, optional = true }
|
||||
awc = { version = "3.0.0", default-features = false, optional = true }
|
||||
base64 = { version = "0.22", optional = true }
|
||||
futures-core = "0.3.28"
|
||||
http-signature-normalization = { version = "0.7.0", path = ".." }
|
||||
ring = { version = "0.17.5", optional = true }
|
||||
sha2 = { version = "0.10", optional = true }
|
||||
sha3 = { version = "0.10", optional = true }
|
||||
streem = "0.2.0"
|
||||
thiserror = "1.0"
|
||||
tokio = { version = "1", default-features = false, features = ["sync"] }
|
||||
tracing = "0.1"
|
||||
tracing-error = "0.2"
|
||||
tracing-futures = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "2.6.0"
|
||||
tracing-actix-web = { version = "0.7.0" }
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
661
actix/LICENSE
Normal file
661
actix/LICENSE
Normal file
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
167
actix/README.md
Normal file
167
actix/README.md
Normal file
|
@ -0,0 +1,167 @@
|
|||
# HTTP Signature Normalization Actix
|
||||
_An HTTP Signatures library that leaves the signing to you_
|
||||
|
||||
- [crates.io](https://crates.io/crates/http-signature-normalization-actix)
|
||||
- [docs.rs](https://docs.rs/http-signature-normalization-actix)
|
||||
- [Hit me up on Mastodon](https://asonix.dog/@asonix)
|
||||
|
||||
Http Signature Normalization is a minimal-dependency crate for producing HTTP Signatures with user-provided signing and verification. The API is simple; there's a series of steps for creation and verification with types that ensure reasonable usage.
|
||||
|
||||
## Usage
|
||||
|
||||
This crate provides extensions the ClientRequest type from Actix Web, and provides middlewares for verifying HTTP Signatures, and optionally, Digest headers
|
||||
|
||||
#### First, add this crate to your dependencies
|
||||
```toml
|
||||
actix-rt = "2.6.0"
|
||||
actix-web = "4.0.0"
|
||||
thiserror = "0.1"
|
||||
http-signature-normalization-actix = { version = "0.8.0", default-features = false, features = ["sha-2"] }
|
||||
sha2 = "0.9"
|
||||
```
|
||||
|
||||
#### Then, use it in your client
|
||||
|
||||
```rust
|
||||
async fn request(config: Config) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let digest = Sha256::new();
|
||||
|
||||
let mut response = Client::default()
|
||||
.post("http://127.0.0.1:8010/")
|
||||
.append_header(("User-Agent", "Actix Web"))
|
||||
.append_header(("Accept", "text/plain"))
|
||||
.insert_header(actix_web::http::header::Date(SystemTime::now().into()))
|
||||
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
||||
info!("Signing String\n{}", s);
|
||||
Ok(base64::encode(s)) as Result<_, MyError>
|
||||
})
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Error, {}", e);
|
||||
MyError::SendRequest
|
||||
})?;
|
||||
|
||||
let body = response.body().await.map_err(|e| {
|
||||
error!("Error, {}", e);
|
||||
MyError::Body
|
||||
})?;
|
||||
|
||||
info!("{:?}", body);
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
#### Or, use it in your server
|
||||
|
||||
```rust
|
||||
#[derive(Clone, Debug)]
|
||||
struct MyVerify;
|
||||
|
||||
impl SignatureVerify for MyVerify {
|
||||
type Error = MyError;
|
||||
type Future = Ready<Result<bool, Self::Error>>;
|
||||
|
||||
fn signature_verify(
|
||||
&mut self,
|
||||
algorithm: Option<Algorithm>,
|
||||
key_id: String,
|
||||
signature: String,
|
||||
signing_string: String,
|
||||
) -> Self::Future {
|
||||
match algorithm {
|
||||
Some(Algorithm::Hs2019) => (),
|
||||
_ => return ready(Err(MyError::Algorithm)),
|
||||
};
|
||||
|
||||
if key_id != "my-key-id" {
|
||||
return ready(Err(MyError::Key));
|
||||
}
|
||||
|
||||
let decoded = match base64::decode(&signature) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(_) => return ready(Err(MyError::Decode)),
|
||||
};
|
||||
|
||||
info!("Signing String\n{}", signing_string);
|
||||
|
||||
ready(Ok(decoded == signing_string.as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
async fn index(
|
||||
_: DigestVerified,
|
||||
sig_verified: SignatureVerified,
|
||||
req: HttpRequest,
|
||||
_body: web::Bytes,
|
||||
) -> &'static str {
|
||||
info!("Verified request for {}", sig_verified.key_id());
|
||||
info!("{:?}", req);
|
||||
"Eyyyyup"
|
||||
}
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
|
||||
let subscriber = tracing_subscriber::Registry::default()
|
||||
.with(env_filter)
|
||||
.with(ErrorLayer::default())
|
||||
.with(tracing_subscriber::fmt::layer());
|
||||
|
||||
tracing::subscriber::set_global_default(subscriber)?;
|
||||
|
||||
let config = Config::default().require_header("accept").require_digest();
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.wrap(VerifyDigest::new(Sha256::new()).optional())
|
||||
.wrap(VerifySignature::new(MyVerify, config.clone()))
|
||||
.wrap(TracingLogger::default())
|
||||
.route("/", web::post().to(index))
|
||||
})
|
||||
.bind("127.0.0.1:8010")?
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum MyError {
|
||||
#[error("Failed to verify, {0}")]
|
||||
Verify(#[from] PrepareVerifyError),
|
||||
|
||||
#[error("Unsupported algorithm")]
|
||||
Algorithm,
|
||||
|
||||
#[error("Couldn't decode signature")]
|
||||
Decode,
|
||||
|
||||
#[error("Invalid key")]
|
||||
Key,
|
||||
}
|
||||
|
||||
impl ResponseError for MyError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
HttpResponse::BadRequest().finish()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Contributing
|
||||
Feel free to open issues for anything you find an issue with. Please note that any contributed code will be licensed under the AGPLv3.
|
||||
|
||||
### License
|
||||
Copyright © 2022 Riley Trautman
|
||||
|
||||
HTTP Signature Normalization Actix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
HTTP Signature Normalization Actix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. This file is part of HTTP Signature Normalization Actix.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with HTTP Signature Normalization Actix. If not, see [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/).
|
|
@ -1,8 +1,7 @@
|
|||
use actix_web::error::BlockingError;
|
||||
use actix_rt::task::JoinError;
|
||||
use awc::Client;
|
||||
use http_signature_normalization_actix::prelude::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::time::SystemTime;
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use http_signature_normalization_actix::{digest::ring::Sha256, prelude::*, Canceled};
|
||||
use tracing::{error, info};
|
||||
use tracing_error::ErrorLayer;
|
||||
use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
|
||||
|
@ -14,10 +13,9 @@ async fn request(config: Config) -> Result<(), Box<dyn std::error::Error>> {
|
|||
.post("http://127.0.0.1:8010/")
|
||||
.append_header(("User-Agent", "Actix Web"))
|
||||
.append_header(("Accept", "text/plain"))
|
||||
.insert_header(actix_web::http::header::Date(SystemTime::now().into()))
|
||||
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
||||
info!("Signing String\n{}", s);
|
||||
Ok(base64::encode(s)) as Result<_, MyError>
|
||||
Ok(STANDARD.encode(s)) as Result<_, MyError>
|
||||
})
|
||||
.await?
|
||||
.send()
|
||||
|
@ -47,7 +45,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
|
||||
tracing::subscriber::set_global_default(subscriber)?;
|
||||
|
||||
let config = Config::default().require_header("accept").require_digest();
|
||||
let config = Config::new().require_header("accept").require_digest();
|
||||
|
||||
request(config.clone()).await?;
|
||||
request(config.mastodon_compat()).await?;
|
||||
|
@ -72,8 +70,14 @@ pub enum MyError {
|
|||
Canceled,
|
||||
}
|
||||
|
||||
impl From<BlockingError> for MyError {
|
||||
fn from(_: BlockingError) -> Self {
|
||||
impl From<JoinError> for MyError {
|
||||
fn from(_: JoinError) -> Self {
|
||||
MyError::Canceled
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Canceled> for MyError {
|
||||
fn from(_: Canceled) -> Self {
|
||||
MyError::Canceled
|
||||
}
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
|
||||
use http_signature_normalization_actix::prelude::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use http_signature_normalization_actix::{digest::ring::Sha256, prelude::*};
|
||||
use std::future::{ready, Ready};
|
||||
use tracing::info;
|
||||
use tracing_actix_web::TracingLogger;
|
||||
|
@ -30,7 +30,7 @@ impl SignatureVerify for MyVerify {
|
|||
return ready(Err(MyError::Key));
|
||||
}
|
||||
|
||||
let decoded = match base64::decode(&signature) {
|
||||
let decoded = match STANDARD.decode(&signature) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(_) => return ready(Err(MyError::Decode)),
|
||||
};
|
||||
|
@ -42,7 +42,8 @@ impl SignatureVerify for MyVerify {
|
|||
}
|
||||
|
||||
async fn index(
|
||||
(_, sig_verified): (DigestVerified, SignatureVerified),
|
||||
_: DigestVerified,
|
||||
sig_verified: SignatureVerified,
|
||||
req: HttpRequest,
|
||||
_body: web::Bytes,
|
||||
) -> &'static str {
|
||||
|
@ -62,12 +63,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
|
||||
tracing::subscriber::set_global_default(subscriber)?;
|
||||
|
||||
let config = Config::default().require_header("accept").require_digest();
|
||||
let config = Config::new().require_header("accept").require_digest();
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.wrap(VerifyDigest::new(Sha256::new()).optional())
|
||||
.wrap(VerifySignature::new(MyVerify, config.clone()).optional())
|
||||
.wrap(VerifySignature::new(MyVerify, config.clone()))
|
||||
.wrap(TracingLogger::default())
|
||||
.route("/", web::post().to(index))
|
||||
})
|
|
@ -1,8 +1,6 @@
|
|||
//! Types for signing requests with Actix Web
|
||||
|
||||
use actix_web::http::header::{
|
||||
HeaderMap, HeaderName, HeaderValue, InvalidHeaderValue, AUTHORIZATION,
|
||||
};
|
||||
use actix_http::header::{HeaderMap, HeaderName, HeaderValue, InvalidHeaderValue, AUTHORIZATION};
|
||||
|
||||
/// A thin wrapper around the underlying library's Signed type
|
||||
///
|
|
@ -1,22 +1,23 @@
|
|||
//! Types for setting up Digest middleware verification
|
||||
|
||||
use crate::{Canceled, DefaultSpawner, Spawn};
|
||||
|
||||
use super::{DigestPart, DigestVerify};
|
||||
use actix_web::{
|
||||
dev::{MessageBody, Payload, Service, ServiceRequest, ServiceResponse, Transform},
|
||||
body::MessageBody,
|
||||
dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},
|
||||
error::PayloadError,
|
||||
http::{header::HeaderValue, StatusCode},
|
||||
web, FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
|
||||
};
|
||||
use futures_util::{
|
||||
future::LocalBoxFuture,
|
||||
stream::{Stream, StreamExt},
|
||||
};
|
||||
use futures_core::{future::LocalBoxFuture, Stream};
|
||||
use std::{
|
||||
future::{ready, Ready},
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
use streem::{from_fn::Yielder, IntoStreamer};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::{debug, Span};
|
||||
use tracing_error::SpanTrace;
|
||||
|
||||
|
@ -41,23 +42,23 @@ pub struct DigestVerified;
|
|||
/// .route("/unprotected", web::post().to(|| "No verification required"))
|
||||
/// })
|
||||
/// ```
|
||||
pub struct VerifyDigest<T>(bool, T);
|
||||
pub struct VerifyDigest<T, Spawner = DefaultSpawner>(Spawner, bool, T);
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct VerifyMiddleware<T, S>(S, bool, T);
|
||||
pub struct VerifyMiddleware<T, Spawner, S>(S, Spawner, bool, T);
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Error verifying digest")]
|
||||
#[doc(hidden)]
|
||||
pub struct VerifyError {
|
||||
context: SpanTrace,
|
||||
context: String,
|
||||
kind: VerifyErrorKind,
|
||||
}
|
||||
|
||||
impl VerifyError {
|
||||
fn new(span: &Span, kind: VerifyErrorKind) -> Self {
|
||||
span.in_scope(|| VerifyError {
|
||||
context: SpanTrace::capture(),
|
||||
context: SpanTrace::capture().to_string(),
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
@ -84,10 +85,10 @@ enum VerifyErrorKind {
|
|||
struct RxStream<T>(mpsc::Receiver<T>);
|
||||
|
||||
impl<T> Stream for RxStream<T> {
|
||||
type Item = T;
|
||||
type Item = Result<T, PayloadError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
Pin::new(&mut self.0).poll_recv(cx)
|
||||
Pin::new(&mut self.0).poll_recv(cx).map(|opt| opt.map(Ok))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -97,7 +98,22 @@ where
|
|||
{
|
||||
/// Produce a new VerifyDigest with a user-provided [`Digestverify`] type
|
||||
pub fn new(verify_digest: T) -> Self {
|
||||
VerifyDigest(true, verify_digest)
|
||||
VerifyDigest(DefaultSpawner, true, verify_digest)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Spawner> VerifyDigest<T, Spawner>
|
||||
where
|
||||
T: DigestVerify + Clone,
|
||||
{
|
||||
/// Set the spawner used for verifying bytes in the request
|
||||
///
|
||||
/// By default this value uses `actix_web::web::block`
|
||||
pub fn spawner<NewSpawner>(self, spawner: NewSpawner) -> VerifyDigest<T, NewSpawner>
|
||||
where
|
||||
NewSpawner: Spawn,
|
||||
{
|
||||
VerifyDigest(spawner, self.1, self.2)
|
||||
}
|
||||
|
||||
/// Mark verifying the Digest as optional
|
||||
|
@ -105,54 +121,68 @@ where
|
|||
/// If a digest is present in the request, it will be verified, but it is not required to be
|
||||
/// present
|
||||
pub fn optional(self) -> Self {
|
||||
VerifyDigest(false, self.1)
|
||||
VerifyDigest(self.0, false, self.2)
|
||||
}
|
||||
}
|
||||
|
||||
struct VerifiedReceiver {
|
||||
rx: Option<oneshot::Receiver<()>>,
|
||||
}
|
||||
|
||||
impl FromRequest for DigestVerified {
|
||||
type Error = VerifyError;
|
||||
type Future = Ready<Result<Self, Self::Error>>;
|
||||
type Config = ();
|
||||
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
|
||||
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
let res = req
|
||||
.extensions()
|
||||
.get::<Self>()
|
||||
.copied()
|
||||
.extensions_mut()
|
||||
.get_mut::<VerifiedReceiver>()
|
||||
.and_then(|r| r.rx.take())
|
||||
.ok_or_else(|| VerifyError::new(&Span::current(), VerifyErrorKind::Extension));
|
||||
|
||||
if res.is_err() {
|
||||
debug!("Failed to fetch DigestVerified from request");
|
||||
}
|
||||
|
||||
ready(res)
|
||||
Box::pin(async move {
|
||||
res?.await
|
||||
.map_err(|_| VerifyError::new(&Span::current(), VerifyErrorKind::Dropped))
|
||||
.map(|()| DigestVerified)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, B> Transform<S, ServiceRequest> for VerifyDigest<T>
|
||||
impl<T, Spawner, S, B> Transform<S, ServiceRequest> for VerifyDigest<T, Spawner>
|
||||
where
|
||||
T: DigestVerify + Clone + Send + 'static,
|
||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
||||
S::Error: 'static,
|
||||
B: MessageBody + 'static,
|
||||
Spawner: Spawn + Clone + 'static,
|
||||
{
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = actix_web::Error;
|
||||
type Transform = VerifyMiddleware<T, S>;
|
||||
type Transform = VerifyMiddleware<T, Spawner, S>;
|
||||
type InitError = ();
|
||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ready(Ok(VerifyMiddleware(service, self.0, self.1.clone())))
|
||||
ready(Ok(VerifyMiddleware(
|
||||
service,
|
||||
self.0.clone(),
|
||||
self.1,
|
||||
self.2.clone(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, B> Service<ServiceRequest> for VerifyMiddleware<T, S>
|
||||
impl<T, Spawner, S, B> Service<ServiceRequest> for VerifyMiddleware<T, Spawner, S>
|
||||
where
|
||||
T: DigestVerify + Clone + Send + 'static,
|
||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
||||
S::Error: 'static,
|
||||
B: MessageBody + 'static,
|
||||
Spawner: Spawn + Clone + 'static,
|
||||
{
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = actix_web::Error;
|
||||
|
@ -165,7 +195,7 @@ where
|
|||
fn call(&self, mut req: ServiceRequest) -> Self::Future {
|
||||
let span = tracing::info_span!(
|
||||
"Verify digest",
|
||||
digest.required = tracing::field::display(&self.1),
|
||||
digest.required = tracing::field::display(&self.2),
|
||||
);
|
||||
|
||||
if let Some(digest) = req.headers().get("Digest") {
|
||||
|
@ -177,23 +207,24 @@ where
|
|||
)));
|
||||
}
|
||||
};
|
||||
|
||||
let spawner = self.1.clone();
|
||||
let digest = self.3.clone();
|
||||
let (verify_tx, verify_rx) = oneshot::channel();
|
||||
|
||||
let payload = req.take_payload();
|
||||
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
let f1 = span.in_scope(|| verify_payload(vec, self.2.clone(), payload, tx));
|
||||
|
||||
let payload: Pin<Box<dyn Stream<Item = Result<web::Bytes, PayloadError>> + 'static>> =
|
||||
Box::pin(RxStream(rx).map(Ok));
|
||||
Box::pin(streem::try_from_fn(|yielder| async move {
|
||||
verify_payload(yielder, spawner, vec, digest, payload, verify_tx).await
|
||||
}));
|
||||
req.set_payload(payload.into());
|
||||
req.extensions_mut().insert(DigestVerified);
|
||||
|
||||
let f2 = self.0.call(req);
|
||||
req.extensions_mut().insert(VerifiedReceiver {
|
||||
rx: Some(verify_rx),
|
||||
});
|
||||
|
||||
Box::pin(async move {
|
||||
let (_, res) = futures_util::future::join(f1, f2).await;
|
||||
res
|
||||
})
|
||||
} else if self.1 {
|
||||
Box::pin(self.0.call(req))
|
||||
} else if self.2 {
|
||||
Box::pin(ready(Err(VerifyError::new(
|
||||
&span,
|
||||
VerifyErrorKind::MissingDigest,
|
||||
|
@ -205,37 +236,79 @@ where
|
|||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "Verify Payload", skip(verify_digest, payload, tx))]
|
||||
async fn verify_payload<T>(
|
||||
fn canceled_error(error: Canceled) -> PayloadError {
|
||||
PayloadError::Io(std::io::Error::new(std::io::ErrorKind::Other, error))
|
||||
}
|
||||
|
||||
fn verified_error(error: VerifyError) -> PayloadError {
|
||||
PayloadError::Io(std::io::Error::new(std::io::ErrorKind::Other, error))
|
||||
}
|
||||
|
||||
async fn verify_payload<T, Spawner>(
|
||||
yielder: Yielder<Result<web::Bytes, PayloadError>>,
|
||||
spawner: Spawner,
|
||||
vec: Vec<DigestPart>,
|
||||
mut verify_digest: T,
|
||||
mut payload: Payload,
|
||||
tx: mpsc::Sender<web::Bytes>,
|
||||
) -> Result<(), actix_web::Error>
|
||||
payload: Payload,
|
||||
verify_tx: oneshot::Sender<()>,
|
||||
) -> Result<(), PayloadError>
|
||||
where
|
||||
T: DigestVerify + Clone + Send + 'static,
|
||||
Spawner: Spawn,
|
||||
{
|
||||
while let Some(res) = payload.next().await {
|
||||
let bytes = res?;
|
||||
let bytes2 = bytes.clone();
|
||||
verify_digest = web::block(move || {
|
||||
verify_digest.update(bytes2.as_ref());
|
||||
Ok(verify_digest) as Result<T, VerifyError>
|
||||
})
|
||||
.await??;
|
||||
let mut payload = payload.into_streamer();
|
||||
|
||||
tx.send(bytes)
|
||||
.await
|
||||
.map_err(|_| VerifyError::new(&Span::current(), VerifyErrorKind::Dropped))?;
|
||||
let mut error = None;
|
||||
|
||||
while let Some(bytes) = payload.try_next().await? {
|
||||
if error.is_none() {
|
||||
let bytes2 = bytes.clone();
|
||||
let mut verify_digest2 = verify_digest.clone();
|
||||
|
||||
let task = spawner.spawn_blocking(move || {
|
||||
verify_digest2.update(bytes2.as_ref());
|
||||
Ok(verify_digest2) as Result<T, VerifyError>
|
||||
});
|
||||
|
||||
yielder.yield_ok(bytes).await;
|
||||
|
||||
match task.await {
|
||||
Ok(Ok(digest)) => {
|
||||
verify_digest = digest;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
error = Some(verified_error(e));
|
||||
}
|
||||
Err(e) => {
|
||||
error = Some(canceled_error(e));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
yielder.yield_ok(bytes).await;
|
||||
}
|
||||
}
|
||||
|
||||
let verified =
|
||||
web::block(move || Ok(verify_digest.verify(&vec)) as Result<_, VerifyError>).await??;
|
||||
if let Some(error) = error {
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
let verified = spawner
|
||||
.spawn_blocking(move || Ok(verify_digest.verify(&vec)) as Result<_, VerifyError>)
|
||||
.await
|
||||
.map_err(canceled_error)?
|
||||
.map_err(verified_error)?;
|
||||
|
||||
if verified {
|
||||
if verify_tx.send(()).is_err() {
|
||||
debug!("handler dropped");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(VerifyError::new(&Span::current(), VerifyErrorKind::Verify).into())
|
||||
Err(verified_error(VerifyError::new(
|
||||
&Span::current(),
|
||||
VerifyErrorKind::Verify,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
156
actix/src/digest/mod.rs
Normal file
156
actix/src/digest/mod.rs
Normal file
|
@ -0,0 +1,156 @@
|
|||
//! Types and Traits for creating and verifying Digest headers
|
||||
//!
|
||||
//! Digest headers are commonly used in conjunction with HTTP Signatures to verify the whole
|
||||
//! request when request bodies are present
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub mod middleware;
|
||||
#[cfg(feature = "ring")]
|
||||
pub mod ring;
|
||||
#[cfg(feature = "sha-2")]
|
||||
mod sha2;
|
||||
#[cfg(feature = "sha-3")]
|
||||
mod sha3;
|
||||
#[cfg(feature = "client")]
|
||||
mod sign;
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
pub use self::client::{DigestClient, DigestCreate, SignExt};
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub use self::server::{DigestPart, DigestVerify};
|
||||
|
||||
/// Giving names to Digest implementations
|
||||
pub trait DigestName {
|
||||
/// The name of the digest algorithm
|
||||
const NAME: &'static str;
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
mod client {
|
||||
use crate::{Config, PrepareSignError, Sign, Spawn};
|
||||
use actix_http::header::InvalidHeaderValue;
|
||||
use actix_rt::task::JoinError;
|
||||
use awc::{ClientRequest, SendClientRequest};
|
||||
use std::{fmt::Display, future::Future, pin::Pin};
|
||||
|
||||
use super::DigestName;
|
||||
|
||||
/// A trait for creating digests of an array of bytes
|
||||
pub trait DigestCreate: DigestName {
|
||||
/// Compute the digest of the input bytes
|
||||
fn compute(&mut self, input: &[u8]) -> String;
|
||||
}
|
||||
|
||||
/// Extend the Sign trait with support for adding Digest Headers to the request
|
||||
///
|
||||
/// It generates HTTP Signatures after the Digest header has been added, in order to have
|
||||
/// verification that the body has not been tampered with, or that the request can't be replayed by
|
||||
/// a malicious entity
|
||||
pub trait SignExt: Sign {
|
||||
/// Set the Digest and Authorization headers on the request
|
||||
fn authorization_signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized;
|
||||
|
||||
/// Set the Digest and Signature headers on the request
|
||||
fn signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
/// An intermediate type between setting the Digest and Signature or Authorization headers, and
|
||||
/// actually sending the request
|
||||
///
|
||||
/// This exists so that the return type for the [`SignExt`] trait can be named
|
||||
pub struct DigestClient<V> {
|
||||
req: ClientRequest,
|
||||
body: V,
|
||||
}
|
||||
|
||||
impl<V> DigestClient<V>
|
||||
where
|
||||
V: AsRef<[u8]>,
|
||||
{
|
||||
pub(super) fn new(req: ClientRequest, body: V) -> Self {
|
||||
DigestClient { req, body }
|
||||
}
|
||||
|
||||
/// Send the request
|
||||
///
|
||||
/// This is analogous to `ClientRequest::send_body` and uses the body provided when producing
|
||||
/// the digest
|
||||
pub fn send(self) -> SendClientRequest {
|
||||
self.req.send_body(self.body.as_ref().to_vec())
|
||||
}
|
||||
|
||||
/// Split the parts of the request
|
||||
///
|
||||
/// In case the caller needs to interrogate the ClientRequest before sending
|
||||
pub fn split(self) -> (ClientRequest, V) {
|
||||
(self.req, self.body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
mod server {
|
||||
use super::DigestName;
|
||||
|
||||
/// A trait for verifying digests
|
||||
pub trait DigestVerify: DigestName {
|
||||
/// Update the verifier with bytes from the request body
|
||||
fn update(&mut self, part: &[u8]);
|
||||
|
||||
/// Verify the request body against the digests from the request headers
|
||||
fn verify(&mut self, digests: &[DigestPart]) -> bool;
|
||||
}
|
||||
|
||||
/// A parsed digest from the request
|
||||
#[derive(Debug)]
|
||||
pub struct DigestPart {
|
||||
/// The alrogithm used to produce the digest
|
||||
pub algorithm: String,
|
||||
|
||||
/// The digest itself
|
||||
pub digest: String,
|
||||
}
|
||||
}
|
198
actix/src/digest/ring.rs
Normal file
198
actix/src/digest/ring.rs
Normal file
|
@ -0,0 +1,198 @@
|
|||
//! Types for creating digests with the `ring` cryptography library
|
||||
|
||||
use crate::digest::DigestName;
|
||||
|
||||
/// A Sha256 digest backed by ring
|
||||
#[derive(Clone)]
|
||||
pub struct Sha256 {
|
||||
ctx: ring::digest::Context,
|
||||
}
|
||||
|
||||
/// A Sha384 digest backed by ring
|
||||
#[derive(Clone)]
|
||||
pub struct Sha384 {
|
||||
ctx: ring::digest::Context,
|
||||
}
|
||||
|
||||
/// A Sha512 digest backed by ring
|
||||
#[derive(Clone)]
|
||||
pub struct Sha512 {
|
||||
ctx: ring::digest::Context,
|
||||
}
|
||||
|
||||
impl Sha256 {
|
||||
/// Create a new empty digest
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Extract the context
|
||||
pub fn into_inner(self) -> ring::digest::Context {
|
||||
self.ctx
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Sha256 {
|
||||
fn default() -> Self {
|
||||
Sha256 {
|
||||
ctx: ring::digest::Context::new(&ring::digest::SHA256),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sha384 {
|
||||
/// Create a new empty digest
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Extract the context
|
||||
pub fn into_inner(self) -> ring::digest::Context {
|
||||
self.ctx
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Sha384 {
|
||||
fn default() -> Self {
|
||||
Sha384 {
|
||||
ctx: ring::digest::Context::new(&ring::digest::SHA384),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sha512 {
|
||||
/// Create a new empty digest
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Extract the context
|
||||
pub fn into_inner(self) -> ring::digest::Context {
|
||||
self.ctx
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Sha512 {
|
||||
fn default() -> Self {
|
||||
Sha512 {
|
||||
ctx: ring::digest::Context::new(&ring::digest::SHA512),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestName for Sha256 {
|
||||
const NAME: &'static str = "SHA-256";
|
||||
}
|
||||
|
||||
impl DigestName for Sha384 {
|
||||
const NAME: &'static str = "SHA-384";
|
||||
}
|
||||
|
||||
impl DigestName for Sha512 {
|
||||
const NAME: &'static str = "SHA-512";
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
mod client {
|
||||
use super::*;
|
||||
use crate::digest::DigestCreate;
|
||||
use base64::prelude::*;
|
||||
|
||||
fn create(mut context: ring::digest::Context, input: &[u8]) -> String {
|
||||
context.update(input);
|
||||
let digest = context.finish();
|
||||
BASE64_STANDARD.encode(digest.as_ref())
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha256 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self.ctx.clone(), input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha384 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self.ctx.clone(), input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha512 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self.ctx.clone(), input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
mod server {
|
||||
use super::*;
|
||||
use crate::digest::{DigestPart, DigestVerify};
|
||||
use base64::prelude::*;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
fn verify(context: ring::digest::Context, name: &str, parts: &[DigestPart]) -> bool {
|
||||
if let Some(part) = parts
|
||||
.iter()
|
||||
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
||||
{
|
||||
debug!("Verifying digest type, {}", name);
|
||||
let digest = context.finish();
|
||||
let encoded = BASE64_STANDARD.encode(digest.as_ref());
|
||||
|
||||
return part.digest == encoded;
|
||||
}
|
||||
warn!("No matching digest algorithm found for {}", name);
|
||||
warn!(
|
||||
"Provided: [{}]",
|
||||
parts.iter().fold(String::new(), |mut acc, item| {
|
||||
if acc.is_empty() {
|
||||
} else {
|
||||
acc.push_str(", ");
|
||||
}
|
||||
acc.push_str(&item.algorithm);
|
||||
acc
|
||||
})
|
||||
);
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha256 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
self.ctx.update(part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
let alg = self.ctx.algorithm();
|
||||
let ctx = std::mem::replace(&mut self.ctx, ring::digest::Context::new(alg));
|
||||
|
||||
verify(ctx, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha384 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
self.ctx.update(part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
let alg = self.ctx.algorithm();
|
||||
let ctx = std::mem::replace(&mut self.ctx, ring::digest::Context::new(alg));
|
||||
|
||||
verify(ctx, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha512 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
self.ctx.update(part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
let alg = self.ctx.algorithm();
|
||||
let ctx = std::mem::replace(&mut self.ctx, ring::digest::Context::new(alg));
|
||||
|
||||
verify(ctx, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
}
|
135
actix/src/digest/sha2.rs
Normal file
135
actix/src/digest/sha2.rs
Normal file
|
@ -0,0 +1,135 @@
|
|||
use crate::digest::DigestName;
|
||||
use sha2::{Sha224, Sha256, Sha384, Sha512};
|
||||
|
||||
impl DigestName for Sha224 {
|
||||
const NAME: &'static str = "SHA-244";
|
||||
}
|
||||
|
||||
impl DigestName for Sha256 {
|
||||
const NAME: &'static str = "SHA-256";
|
||||
}
|
||||
|
||||
impl DigestName for Sha384 {
|
||||
const NAME: &'static str = "SHA-384";
|
||||
}
|
||||
|
||||
impl DigestName for Sha512 {
|
||||
const NAME: &'static str = "SHA-512";
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
mod client {
|
||||
use super::*;
|
||||
use crate::digest::DigestCreate;
|
||||
use base64::prelude::*;
|
||||
|
||||
fn create<D: sha2::Digest + sha2::digest::FixedOutputReset>(
|
||||
digest: &mut D,
|
||||
input: &[u8],
|
||||
) -> String {
|
||||
sha2::Digest::update(digest, input);
|
||||
BASE64_STANDARD.encode(&digest.finalize_reset())
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha224 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha256 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha384 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha512 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
mod server {
|
||||
use super::*;
|
||||
use crate::digest::{DigestPart, DigestVerify};
|
||||
use base64::prelude::*;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
fn verify<D: sha2::Digest + sha2::digest::FixedOutputReset>(
|
||||
digest: &mut D,
|
||||
name: &str,
|
||||
parts: &[DigestPart],
|
||||
) -> bool {
|
||||
if let Some(part) = parts
|
||||
.iter()
|
||||
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
||||
{
|
||||
debug!("Verifying digest type, {}", name);
|
||||
let encoded = BASE64_STANDARD.encode(&digest.finalize_reset());
|
||||
|
||||
return part.digest == encoded;
|
||||
}
|
||||
warn!("No matching digest algorithm found for {}", name);
|
||||
warn!(
|
||||
"Provided: [{}]",
|
||||
parts.iter().fold(String::new(), |mut acc, item| {
|
||||
if acc.is_empty() {
|
||||
} else {
|
||||
acc.push_str(", ");
|
||||
}
|
||||
acc.push_str(&item.algorithm);
|
||||
acc
|
||||
})
|
||||
);
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha224 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha256 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha384 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha512 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
}
|
238
actix/src/digest/sha3.rs
Normal file
238
actix/src/digest/sha3.rs
Normal file
|
@ -0,0 +1,238 @@
|
|||
use crate::digest::DigestName;
|
||||
use sha3::{
|
||||
Keccak224, Keccak256, Keccak256Full, Keccak384, Keccak512, Sha3_224, Sha3_256, Sha3_384,
|
||||
Sha3_512,
|
||||
};
|
||||
|
||||
impl DigestName for Keccak224 {
|
||||
const NAME: &'static str = "keccak-224";
|
||||
}
|
||||
|
||||
impl DigestName for Keccak256 {
|
||||
const NAME: &'static str = "keccak-256";
|
||||
}
|
||||
|
||||
impl DigestName for Keccak256Full {
|
||||
const NAME: &'static str = "keccak-256-full";
|
||||
}
|
||||
|
||||
impl DigestName for Keccak384 {
|
||||
const NAME: &'static str = "keccak-384";
|
||||
}
|
||||
|
||||
impl DigestName for Keccak512 {
|
||||
const NAME: &'static str = "keccak-512";
|
||||
}
|
||||
|
||||
impl DigestName for Sha3_224 {
|
||||
const NAME: &'static str = "SHA3-224";
|
||||
}
|
||||
|
||||
impl DigestName for Sha3_256 {
|
||||
const NAME: &'static str = "SHA3-256";
|
||||
}
|
||||
|
||||
impl DigestName for Sha3_384 {
|
||||
const NAME: &'static str = "SHA3-384";
|
||||
}
|
||||
|
||||
impl DigestName for Sha3_512 {
|
||||
const NAME: &'static str = "SHA3-512";
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
mod client {
|
||||
use super::*;
|
||||
use crate::digest::DigestCreate;
|
||||
use base64::prelude::*;
|
||||
|
||||
fn create<D: sha3::Digest + sha3::digest::FixedOutputReset>(
|
||||
digest: &mut D,
|
||||
input: &[u8],
|
||||
) -> String {
|
||||
sha3::Digest::update(digest, input);
|
||||
BASE64_STANDARD.encode(&digest.finalize_reset())
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha3_224 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha3_256 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha3_384 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha3_512 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak224 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak256 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak256Full {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak384 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak512 {
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
mod server {
|
||||
use super::*;
|
||||
use crate::digest::{DigestPart, DigestVerify};
|
||||
use base64::prelude::*;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
fn verify<D: sha3::Digest + sha3::digest::FixedOutputReset>(
|
||||
digest: &mut D,
|
||||
name: &str,
|
||||
parts: &[DigestPart],
|
||||
) -> bool {
|
||||
if let Some(part) = parts
|
||||
.iter()
|
||||
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
||||
{
|
||||
debug!("Verifying digest type, {}", name);
|
||||
let encoded = BASE64_STANDARD.encode(&digest.finalize_reset());
|
||||
|
||||
return part.digest == encoded;
|
||||
}
|
||||
warn!("No matching digest algorithm found for {}", name);
|
||||
warn!(
|
||||
"Provided: [{}]",
|
||||
parts.iter().fold(String::new(), |mut acc, item| {
|
||||
if acc.is_empty() {
|
||||
} else {
|
||||
acc.push_str(", ");
|
||||
}
|
||||
acc.push_str(&item.algorithm);
|
||||
acc
|
||||
})
|
||||
);
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha3_224 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha3_256 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha3_384 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha3_512 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak224 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak256 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak256Full {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak384 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak512 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, Self::NAME, parts)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,16 +1,17 @@
|
|||
use actix_web::{error::BlockingError, http::header::InvalidHeaderValue, web};
|
||||
use actix_http::header::InvalidHeaderValue;
|
||||
use actix_rt::task::JoinError;
|
||||
use awc::ClientRequest;
|
||||
use std::{fmt::Display, future::Future, pin::Pin};
|
||||
|
||||
use crate::{
|
||||
digest::{DigestClient, DigestCreate, SignExt},
|
||||
Config, PrepareSignError, Sign,
|
||||
Config, PrepareSignError, Sign, Spawn,
|
||||
};
|
||||
|
||||
impl SignExt for ClientRequest {
|
||||
fn authorization_signature_with_digest<F, E, K, D, V>(
|
||||
fn authorization_signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
mut digest: D,
|
||||
v: V,
|
||||
|
@ -18,23 +19,27 @@ impl SignExt for ClientRequest {
|
|||
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<BlockingError>
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (d, v) = web::block(move || {
|
||||
let d = digest.compute(v.as_ref());
|
||||
Ok((d, v)) as Result<(String, V), E>
|
||||
})
|
||||
.await??;
|
||||
let (d, v) = config
|
||||
.spawner
|
||||
.spawn_blocking(move || {
|
||||
let d = digest.compute(v.as_ref());
|
||||
Ok((d, v)) as Result<(String, V), E>
|
||||
})
|
||||
.await??;
|
||||
|
||||
let c = self
|
||||
.insert_header(("Digest", format!("{}={}", D::NAME, d)))
|
||||
|
@ -45,9 +50,9 @@ impl SignExt for ClientRequest {
|
|||
})
|
||||
}
|
||||
|
||||
fn signature_with_digest<F, E, K, D, V>(
|
||||
fn signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
mut digest: D,
|
||||
v: V,
|
||||
|
@ -55,23 +60,27 @@ impl SignExt for ClientRequest {
|
|||
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<BlockingError>
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (d, v) = web::block(move || {
|
||||
let d = digest.compute(v.as_ref());
|
||||
Ok((d, v)) as Result<(String, V), E>
|
||||
})
|
||||
.await??;
|
||||
let (d, v) = config
|
||||
.spawner
|
||||
.spawn_blocking(move || {
|
||||
let d = digest.compute(v.as_ref());
|
||||
Ok((d, v)) as Result<(String, V), E>
|
||||
})
|
||||
.await??;
|
||||
|
||||
let c = self
|
||||
.insert_header(("Digest", format!("{}={}", D::NAME, d)))
|
642
actix/src/lib.rs
Normal file
642
actix/src/lib.rs
Normal file
|
@ -0,0 +1,642 @@
|
|||
#![deny(missing_docs)]
|
||||
|
||||
//! # Integration of Http Signature Normalization with Actix Web
|
||||
//!
|
||||
//! This library provides middlewares for verifying HTTP Signature headers and, optionally, Digest
|
||||
//! headers with the `digest` feature enabled. It also extends awc's ClientRequest type to
|
||||
//! add signatures and digests to the request
|
||||
//!
|
||||
//! ### Use it in a server
|
||||
//! ```rust,ignore
|
||||
//! use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
|
||||
//! use http_signature_normalization_actix::prelude::*;
|
||||
//! use sha2::{Digest, Sha256};
|
||||
//! use std::future::{ready, Ready};
|
||||
//! use tracing::info;
|
||||
//! use tracing_actix_web::TracingLogger;
|
||||
//! use tracing_error::ErrorLayer;
|
||||
//! use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
|
||||
//!
|
||||
//! #[derive(Clone, Debug)]
|
||||
//! struct MyVerify;
|
||||
//!
|
||||
//! impl SignatureVerify for MyVerify {
|
||||
//! type Error = MyError;
|
||||
//! type Future = Ready<Result<bool, Self::Error>>;
|
||||
//!
|
||||
//! fn signature_verify(
|
||||
//! &mut self,
|
||||
//! algorithm: Option<Algorithm>,
|
||||
//! key_id: String,
|
||||
//! signature: String,
|
||||
//! signing_string: String,
|
||||
//! ) -> Self::Future {
|
||||
//! match algorithm {
|
||||
//! Some(Algorithm::Hs2019) => (),
|
||||
//! _ => return ready(Err(MyError::Algorithm)),
|
||||
//! };
|
||||
//!
|
||||
//! if key_id != "my-key-id" {
|
||||
//! return ready(Err(MyError::Key));
|
||||
//! }
|
||||
//!
|
||||
//! let decoded = match base64::decode(&signature) {
|
||||
//! Ok(decoded) => decoded,
|
||||
//! Err(_) => return ready(Err(MyError::Decode)),
|
||||
//! };
|
||||
//!
|
||||
//! info!("Signing String\n{}", signing_string);
|
||||
//!
|
||||
//! ready(Ok(decoded == signing_string.as_bytes()))
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! async fn index(
|
||||
//! (_, sig_verified): (DigestVerified, SignatureVerified),
|
||||
//! req: HttpRequest,
|
||||
//! _body: web::Bytes,
|
||||
//! ) -> &'static str {
|
||||
//! info!("Verified request for {}", sig_verified.key_id());
|
||||
//! info!("{:?}", req);
|
||||
//! "Eyyyyup"
|
||||
//! }
|
||||
//!
|
||||
//! #[actix_rt::main]
|
||||
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
//!
|
||||
//! let subscriber = tracing_subscriber::Registry::default()
|
||||
//! .with(env_filter)
|
||||
//! .with(ErrorLayer::default())
|
||||
//! .with(tracing_subscriber::fmt::layer());
|
||||
//!
|
||||
//! tracing::subscriber::set_global_default(subscriber)?;
|
||||
//!
|
||||
//! let config = Config::default().require_header("accept").require_digest();
|
||||
//!
|
||||
//! HttpServer::new(move || {
|
||||
//! App::new()
|
||||
//! .wrap(VerifyDigest::new(Sha256::new()).optional())
|
||||
//! .wrap(VerifySignature::new(MyVerify, config.clone()).optional())
|
||||
//! .wrap(TracingLogger::default())
|
||||
//! .route("/", web::post().to(index))
|
||||
//! })
|
||||
//! .bind("127.0.0.1:8010")?
|
||||
//! .run()
|
||||
//! .await?;
|
||||
//!
|
||||
//! Ok(())
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Debug, thiserror::Error)]
|
||||
//! enum MyError {
|
||||
//! #[error("Failed to verify, {0}")]
|
||||
//! Verify(#[from] PrepareVerifyError),
|
||||
//!
|
||||
//! #[error("Unsupported algorithm")]
|
||||
//! Algorithm,
|
||||
//!
|
||||
//! #[error("Couldn't decode signature")]
|
||||
//! Decode,
|
||||
//!
|
||||
//! #[error("Invalid key")]
|
||||
//! Key,
|
||||
//! }
|
||||
//!
|
||||
//! impl ResponseError for MyError {
|
||||
//! fn status_code(&self) -> StatusCode {
|
||||
//! StatusCode::BAD_REQUEST
|
||||
//! }
|
||||
//!
|
||||
//! fn error_response(&self) -> HttpResponse {
|
||||
//! HttpResponse::BadRequest().finish()
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ### Use it in a client
|
||||
//! ```rust,ignore
|
||||
//! use actix_rt::task::JoinError;
|
||||
//! use awc::Client;
|
||||
//! use http_signature_normalization_actix::prelude::*;
|
||||
//! use sha2::{Digest, Sha256};
|
||||
//! use std::time::SystemTime;
|
||||
//! use tracing::{error, info};
|
||||
//! use tracing_error::ErrorLayer;
|
||||
//! use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
|
||||
//!
|
||||
//! async fn request(config: Config) -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let digest = Sha256::new();
|
||||
//!
|
||||
//! let mut response = Client::default()
|
||||
//! .post("http://127.0.0.1:8010/")
|
||||
//! .append_header(("User-Agent", "Actix Web"))
|
||||
//! .append_header(("Accept", "text/plain"))
|
||||
//! .insert_header(actix_web::http::header::Date(SystemTime::now().into()))
|
||||
//! .signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
||||
//! info!("Signing String\n{}", s);
|
||||
//! Ok(base64::encode(s)) as Result<_, MyError>
|
||||
//! })
|
||||
//! .await?
|
||||
//! .send()
|
||||
//! .await
|
||||
//! .map_err(|e| {
|
||||
//! error!("Error, {}", e);
|
||||
//! MyError::SendRequest
|
||||
//! })?;
|
||||
//!
|
||||
//! let body = response.body().await.map_err(|e| {
|
||||
//! error!("Error, {}", e);
|
||||
//! MyError::Body
|
||||
//! })?;
|
||||
//!
|
||||
//! info!("{:?}", body);
|
||||
//! Ok(())
|
||||
//! }
|
||||
//!
|
||||
//! #[actix_rt::main]
|
||||
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
//!
|
||||
//! let subscriber = tracing_subscriber::Registry::default()
|
||||
//! .with(env_filter)
|
||||
//! .with(ErrorLayer::default())
|
||||
//! .with(tracing_subscriber::fmt::layer());
|
||||
//!
|
||||
//! tracing::subscriber::set_global_default(subscriber)?;
|
||||
//!
|
||||
//! let config = Config::default().require_header("accept").require_digest();
|
||||
//!
|
||||
//! request(config.clone()).await?;
|
||||
//! request(config.mastodon_compat()).await?;
|
||||
//! Ok(())
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Debug, thiserror::Error)]
|
||||
//! pub enum MyError {
|
||||
//! #[error("Failed to create signing string, {0}")]
|
||||
//! Convert(#[from] PrepareSignError),
|
||||
//!
|
||||
//! #[error("Failed to create header, {0}")]
|
||||
//! Header(#[from] InvalidHeaderValue),
|
||||
//!
|
||||
//! #[error("Failed to send request")]
|
||||
//! SendRequest,
|
||||
//!
|
||||
//! #[error("Failed to retrieve request body")]
|
||||
//! Body,
|
||||
//!
|
||||
//! #[error("Blocking operation was canceled")]
|
||||
//! Canceled,
|
||||
//! }
|
||||
//!
|
||||
//! impl From<JoinError> for MyError {
|
||||
//! fn from(_: JoinError) -> Self {
|
||||
//! MyError::Canceled
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(any(feature = "client", feature = "server"))]
|
||||
use actix_http::{
|
||||
header::{HeaderMap, ToStrError},
|
||||
uri::PathAndQuery,
|
||||
Method,
|
||||
};
|
||||
#[cfg(any(feature = "client", feature = "server"))]
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
mod sign;
|
||||
|
||||
#[cfg(feature = "digest")]
|
||||
pub mod digest;
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
pub mod create;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod middleware;
|
||||
|
||||
pub use http_signature_normalization::RequiredError;
|
||||
|
||||
/// Useful types and traits for using this library in Actix Web
|
||||
pub mod prelude {
|
||||
pub use crate::{Config, RequiredError};
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
pub use crate::{PrepareSignError, Sign};
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub use crate::{
|
||||
middleware::{SignatureVerified, VerifySignature},
|
||||
verify::{Algorithm, DeprecatedAlgorithm, Unverified},
|
||||
PrepareVerifyError, SignatureVerify,
|
||||
};
|
||||
|
||||
#[cfg(all(feature = "digest", feature = "client"))]
|
||||
pub use crate::digest::{DigestClient, DigestCreate, SignExt};
|
||||
|
||||
#[cfg(all(feature = "digest", feature = "server"))]
|
||||
pub use crate::digest::{
|
||||
middleware::{DigestVerified, VerifyDigest},
|
||||
DigestPart, DigestVerify,
|
||||
};
|
||||
|
||||
pub use actix_http::header::{InvalidHeaderValue, ToStrError};
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
/// Types for Verifying an HTTP Signature
|
||||
pub mod verify {
|
||||
pub use http_signature_normalization::verify::{
|
||||
Algorithm, DeprecatedAlgorithm, ParseSignatureError, ParsedHeader, Unvalidated, Unverified,
|
||||
ValidateError,
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
pub use self::client::{PrepareSignError, Sign};
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub use self::server::{PrepareVerifyError, SignatureVerify};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// Configuration for signing and verifying signatures
|
||||
///
|
||||
/// By default, the config is set up to create and verify signatures that expire after 10
|
||||
/// seconds, and use the `(created)` and `(expires)` fields that were introduced in draft 11
|
||||
pub struct Config<Spawner = DefaultSpawner> {
|
||||
/// The inner config type
|
||||
config: http_signature_normalization::Config,
|
||||
|
||||
/// Whether to set the Host header
|
||||
set_host: bool,
|
||||
|
||||
/// Whether to set the Date header
|
||||
set_date: bool,
|
||||
|
||||
/// The spawner used to create blocking operations
|
||||
spawner: Spawner,
|
||||
}
|
||||
|
||||
/// A default implementation of Spawner for spawning blocking operations
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct DefaultSpawner;
|
||||
|
||||
/// An error that indicates a blocking operation panicked and cannot return a response
|
||||
#[derive(Debug)]
|
||||
pub struct Canceled;
|
||||
|
||||
impl std::fmt::Display for Canceled {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Operation was canceled")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Canceled {}
|
||||
|
||||
/// A trait dictating how to spawn a future onto a blocking threadpool. By default,
|
||||
/// http-signature-normalization-actix will use actix_rt's built-in blocking threadpool, but this
|
||||
/// can be customized
|
||||
pub trait Spawn {
|
||||
/// The future type returned by spawn_blocking
|
||||
type Future<T>: std::future::Future<Output = Result<T, Canceled>>;
|
||||
|
||||
/// Spawn the blocking function onto the threadpool
|
||||
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
||||
where
|
||||
Func: FnOnce() -> Out + Send + 'static,
|
||||
Out: Send + 'static;
|
||||
}
|
||||
|
||||
/// The future returned by DefaultSpawner when spawning blocking operations on the actix_rt
|
||||
/// blocking threadpool
|
||||
pub struct DefaultSpawnerFuture<Out> {
|
||||
inner: actix_rt::task::JoinHandle<Out>,
|
||||
}
|
||||
|
||||
impl Spawn for DefaultSpawner {
|
||||
type Future<T> = DefaultSpawnerFuture<T>;
|
||||
|
||||
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
||||
where
|
||||
Func: FnOnce() -> Out + Send + 'static,
|
||||
Out: Send + 'static,
|
||||
{
|
||||
DefaultSpawnerFuture {
|
||||
inner: actix_rt::task::spawn_blocking(func),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Out> std::future::Future for DefaultSpawnerFuture<Out> {
|
||||
type Output = Result<Out, Canceled>;
|
||||
|
||||
fn poll(
|
||||
mut self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Self::Output> {
|
||||
let res = std::task::ready!(std::pin::Pin::new(&mut self.inner).poll(cx));
|
||||
|
||||
std::task::Poll::Ready(res.map_err(|_| Canceled))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
mod client {
|
||||
use super::{Config, RequiredError, Spawn};
|
||||
use actix_http::header::{InvalidHeaderValue, ToStrError};
|
||||
use actix_rt::task::JoinError;
|
||||
use std::{fmt::Display, future::Future, pin::Pin};
|
||||
|
||||
/// A trait implemented by the awc ClientRequest type to add an HTTP signature to the request
|
||||
pub trait Sign {
|
||||
/// Add an Authorization Signature to the request
|
||||
fn authorization_signature<F, E, K, S>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
Self: Sized;
|
||||
|
||||
/// Add a Signature to the request
|
||||
fn signature<F, E, K, S>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
/// An error when preparing to sign a request
|
||||
pub enum PrepareSignError {
|
||||
#[error("Failed to read header")]
|
||||
/// An error occurred when reading the request's headers
|
||||
Header(#[from] ToStrError),
|
||||
|
||||
#[error("Missing required header")]
|
||||
/// Some headers were marked as required, but are missing
|
||||
RequiredError(#[from] RequiredError),
|
||||
|
||||
#[error("No host provided for URL, {0}")]
|
||||
/// Missing host
|
||||
Host(String),
|
||||
|
||||
#[error("Failed to set header")]
|
||||
/// Invalid Date header
|
||||
InvalidHeader(#[from] actix_http::header::InvalidHeaderValue),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
mod server {
|
||||
use super::RequiredError;
|
||||
use actix_http::header::ToStrError;
|
||||
use std::future::Future;
|
||||
|
||||
/// A trait for verifying signatures
|
||||
pub trait SignatureVerify {
|
||||
/// An error produced while attempting to verify the signature. This can be anything
|
||||
/// implementing ResponseError
|
||||
type Error: actix_web::ResponseError;
|
||||
|
||||
/// The future that resolves to the verification state of the signature
|
||||
type Future: Future<Output = Result<bool, Self::Error>>;
|
||||
|
||||
/// Given the algorithm, key_id, signature, and signing_string, produce a future that resulves
|
||||
/// to a the verification status
|
||||
fn signature_verify(
|
||||
&mut self,
|
||||
algorithm: Option<super::verify::Algorithm>,
|
||||
key_id: String,
|
||||
signature: String,
|
||||
signing_string: String,
|
||||
) -> Self::Future;
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
/// An error when preparing to verify a request
|
||||
pub enum PrepareVerifyError {
|
||||
#[error("Header is missing")]
|
||||
/// Header is missing
|
||||
Missing,
|
||||
|
||||
#[error("{0}")]
|
||||
/// Header is expired
|
||||
Expired(String),
|
||||
|
||||
#[error("Couldn't parse required field, {0}")]
|
||||
/// Couldn't parse required field
|
||||
ParseField(&'static str),
|
||||
|
||||
#[error("Failed to read header, {0}")]
|
||||
/// An error converting the header to a string for validation
|
||||
Header(#[from] ToStrError),
|
||||
|
||||
#[error("{0}")]
|
||||
/// Required headers were missing from request
|
||||
Required(#[from] RequiredError),
|
||||
}
|
||||
|
||||
impl From<http_signature_normalization::PrepareVerifyError> for PrepareVerifyError {
|
||||
fn from(e: http_signature_normalization::PrepareVerifyError) -> Self {
|
||||
use http_signature_normalization as hsn;
|
||||
|
||||
match e {
|
||||
hsn::PrepareVerifyError::Parse(parse_error) => {
|
||||
PrepareVerifyError::ParseField(parse_error.missing_field())
|
||||
}
|
||||
hsn::PrepareVerifyError::Validate(validate_error) => match validate_error {
|
||||
hsn::verify::ValidateError::Missing => PrepareVerifyError::Missing,
|
||||
e @ hsn::verify::ValidateError::Expired { .. } => {
|
||||
PrepareVerifyError::Expired(e.to_string())
|
||||
}
|
||||
},
|
||||
hsn::PrepareVerifyError::Required(required_error) => {
|
||||
PrepareVerifyError::Required(required_error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl actix_web::ResponseError for super::Canceled {
|
||||
fn status_code(&self) -> actix_http::StatusCode {
|
||||
actix_http::StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
fn error_response(&self) -> actix_web::HttpResponse<actix_http::body::BoxBody> {
|
||||
actix_web::HttpResponse::new(self.status_code())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Create a new Config with a default expiration of 10 seconds
|
||||
pub fn new() -> Self {
|
||||
Config::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Spawner> Config<Spawner> {
|
||||
/// Since manually setting the Host header doesn't work so well in AWC, you can use this method
|
||||
/// to enable setting the Host header for signing requests without breaking client
|
||||
/// functionality
|
||||
pub fn set_host_header(self) -> Self {
|
||||
Config {
|
||||
config: self.config,
|
||||
set_host: true,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
/// Set the spawner for spawning blocking tasks
|
||||
///
|
||||
/// http-signature-normalization-actix offloads signing messages and generating hashes to a
|
||||
/// blocking threadpool, which can be configured by providing a custom spawner.
|
||||
pub fn spawner<S>(self, spawner: S) -> Config<S>
|
||||
where
|
||||
S: Spawn,
|
||||
{
|
||||
Config {
|
||||
config: self.config,
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Enable mastodon compatibility
|
||||
///
|
||||
/// This is the same as disabling the use of `(created)` and `(expires)` signature fields,
|
||||
/// requiring the Date header, and requiring the Host header
|
||||
pub fn mastodon_compat(self) -> Self {
|
||||
Config {
|
||||
config: self.config.mastodon_compat(),
|
||||
set_host: true,
|
||||
set_date: true,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Require the Digest header be set
|
||||
///
|
||||
/// This is useful for POST, PUT, and PATCH requests, but doesn't make sense for GET or DELETE.
|
||||
pub fn require_digest(self) -> Self {
|
||||
Config {
|
||||
config: self.config.require_digest(),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opt out of using the (created) and (expires) fields introduced in draft 11
|
||||
///
|
||||
/// Note that by enabling this, the Date header becomes required on requests. This is to
|
||||
/// prevent replay attacks
|
||||
pub fn dont_use_created_field(self) -> Self {
|
||||
Config {
|
||||
config: self.config.dont_use_created_field(),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the expiration to a custom duration
|
||||
pub fn set_expiration(self, expires_after: Duration) -> Self {
|
||||
Config {
|
||||
config: self.config.set_expiration(expires_after),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Require a header on signed and verified requests
|
||||
pub fn require_header(self, header: &str) -> Self {
|
||||
Config {
|
||||
config: self.config.require_header(header),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
/// Begin the process of singing a request
|
||||
pub fn begin_sign(
|
||||
&self,
|
||||
method: &Method,
|
||||
path_and_query: Option<&PathAndQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<self::create::Unsigned, PrepareSignError> {
|
||||
let headers = headers
|
||||
.iter()
|
||||
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
|
||||
.collect::<Result<BTreeMap<_, _>, ToStrError>>()?;
|
||||
|
||||
let path_and_query = path_and_query
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or_else(|| "/".to_string());
|
||||
|
||||
let unsigned = self
|
||||
.config
|
||||
.begin_sign(method.as_ref(), &path_and_query, headers)?;
|
||||
|
||||
Ok(self::create::Unsigned { unsigned })
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
/// Begin the proess of verifying a request
|
||||
pub fn begin_verify(
|
||||
&self,
|
||||
method: &Method,
|
||||
path_and_query: Option<&PathAndQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<self::verify::Unverified, PrepareVerifyError> {
|
||||
let headers = headers
|
||||
.iter()
|
||||
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
|
||||
.collect::<Result<BTreeMap<_, _>, ToStrError>>()?;
|
||||
|
||||
let path_and_query = path_and_query
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or_else(|| "/".to_string());
|
||||
|
||||
let unverified = self
|
||||
.config
|
||||
.begin_verify(method.as_ref(), &path_and_query, headers)?;
|
||||
|
||||
Ok(unverified)
|
||||
}
|
||||
}
|
|
@ -1,15 +1,17 @@
|
|||
//! Types for verifying requests with Actix Web
|
||||
|
||||
use crate::{Config, PrepareVerifyError, SignatureVerify};
|
||||
use crate::{Config, PrepareVerifyError, SignatureVerify, Spawn};
|
||||
use actix_web::{
|
||||
dev::{MessageBody, Payload, Service, ServiceRequest, ServiceResponse, Transform},
|
||||
body::MessageBody,
|
||||
dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},
|
||||
http::StatusCode,
|
||||
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
|
||||
};
|
||||
use futures_util::future::LocalBoxFuture;
|
||||
use futures_core::future::LocalBoxFuture;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
future::{ready, Ready},
|
||||
rc::Rc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tracing::{debug, Span};
|
||||
|
@ -17,8 +19,7 @@ use tracing_error::SpanTrace;
|
|||
use tracing_futures::Instrument;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
/// A marker type that can be used to guard routes when the signature middleware is set to
|
||||
/// 'optional'
|
||||
/// A marker type that is used to guard routes
|
||||
pub struct SignatureVerified(String);
|
||||
|
||||
impl SignatureVerified {
|
||||
|
@ -35,9 +36,7 @@ impl SignatureVerified {
|
|||
/// The Verify signature middleware
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let middleware = VerifySignature::new(MyVerifier::new(), Config::default())
|
||||
/// .authorization()
|
||||
/// .optional();
|
||||
/// let middleware = VerifySignature::new(MyVerifier::new(), Config::default()).authorization();
|
||||
///
|
||||
/// HttpServer::new(move || {
|
||||
/// App::new()
|
||||
|
@ -46,11 +45,11 @@ impl SignatureVerified {
|
|||
/// .route("/unprotected", web::post().to(|| "No verification required"))
|
||||
/// })
|
||||
/// ```
|
||||
pub struct VerifySignature<T>(T, Config, HeaderKind, bool);
|
||||
pub struct VerifySignature<T, Spawner>(T, Config<Spawner>, HeaderKind);
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Debug)]
|
||||
#[doc(hidden)]
|
||||
pub struct VerifyMiddleware<T, S>(S, Config, HeaderKind, bool, T);
|
||||
pub struct VerifyMiddleware<T, Spawner, S>(Rc<S>, Config<Spawner>, HeaderKind, T);
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
enum HeaderKind {
|
||||
|
@ -71,21 +70,39 @@ impl std::fmt::Display for HeaderKind {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, thiserror::Error)]
|
||||
#[error("Failed to verify http signature, {kind}")]
|
||||
#[derive(Clone)]
|
||||
#[doc(hidden)]
|
||||
pub struct VerifyError {
|
||||
context: SpanTrace,
|
||||
context: String,
|
||||
kind: VerifyErrorKind,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for VerifyError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
writeln!(f, "{:?}", self.kind)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for VerifyError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
writeln!(f, "{}", self.kind)?;
|
||||
std::fmt::Display::fmt(&self.context, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for VerifyError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
self.kind.source()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, thiserror::Error)]
|
||||
enum VerifyErrorKind {
|
||||
#[error("Signature or Authorization header is missing")]
|
||||
MissingSignature,
|
||||
|
||||
#[error("Signature is expired")]
|
||||
ExpiredSignature,
|
||||
#[error("{0}")]
|
||||
ExpiredSignature(String),
|
||||
|
||||
#[error("Signature field could not be parsed")]
|
||||
ParseField(&'static str),
|
||||
|
@ -93,9 +110,6 @@ enum VerifyErrorKind {
|
|||
#[error("Signature is not a valid string")]
|
||||
ParseSignature,
|
||||
|
||||
#[error("Signature is invalid")]
|
||||
Validate,
|
||||
|
||||
#[error("Request extension not present")]
|
||||
Extension,
|
||||
|
||||
|
@ -106,13 +120,13 @@ enum VerifyErrorKind {
|
|||
impl VerifyError {
|
||||
fn new(span: &Span, kind: VerifyErrorKind) -> Self {
|
||||
span.in_scope(|| VerifyError {
|
||||
context: SpanTrace::capture(),
|
||||
context: SpanTrace::capture().to_string(),
|
||||
kind,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> VerifySignature<T>
|
||||
impl<T, Spawner> VerifySignature<T, Spawner>
|
||||
where
|
||||
T: SignatureVerify,
|
||||
{
|
||||
|
@ -121,26 +135,20 @@ where
|
|||
///
|
||||
/// By default, this middleware expects to verify Signature headers, and requires the presence
|
||||
/// of the header
|
||||
pub fn new(verify_signature: T, config: Config) -> Self {
|
||||
VerifySignature(verify_signature, config, HeaderKind::Signature, false)
|
||||
pub fn new(verify_signature: T, config: Config<Spawner>) -> Self
|
||||
where
|
||||
Spawner: Spawn,
|
||||
{
|
||||
VerifySignature(verify_signature, config, HeaderKind::Signature)
|
||||
}
|
||||
|
||||
/// Verify Authorization headers instead of Signature headers
|
||||
pub fn authorization(self) -> Self {
|
||||
VerifySignature(self.0, self.1, HeaderKind::Authorization, self.3)
|
||||
}
|
||||
|
||||
/// Mark the presence of a Signature or Authorization header as optional
|
||||
///
|
||||
/// If a header is present, it will be verified, but if there is not one present, the request
|
||||
/// is passed through. This can be used to set a global middleware, and then guard each route
|
||||
/// handler with the [`SignatureVerified`] type.
|
||||
pub fn optional(self) -> Self {
|
||||
VerifySignature(self.0, self.1, self.2, true)
|
||||
VerifySignature(self.0, self.1, HeaderKind::Authorization)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, B> VerifyMiddleware<T, S>
|
||||
impl<T, Spawner, S, B> VerifyMiddleware<T, Spawner, S>
|
||||
where
|
||||
T: SignatureVerify + Clone + 'static,
|
||||
T::Future: 'static,
|
||||
|
@ -160,10 +168,10 @@ where
|
|||
|
||||
let unverified = match res {
|
||||
Ok(unverified) => unverified,
|
||||
Err(PrepareVerifyError::Expired) => {
|
||||
Err(PrepareVerifyError::Expired(reason)) => {
|
||||
return Box::pin(ready(Err(VerifyError::new(
|
||||
&span,
|
||||
VerifyErrorKind::ExpiredSignature,
|
||||
VerifyErrorKind::ExpiredSignature(reason),
|
||||
)
|
||||
.into())));
|
||||
}
|
||||
|
@ -200,31 +208,25 @@ where
|
|||
let algorithm = unverified.algorithm().cloned();
|
||||
let key_id = unverified.key_id().to_owned();
|
||||
|
||||
let f1 = unverified.verify(|signature, signing_string| {
|
||||
let fut = span.in_scope(|| {
|
||||
self.4.clone().signature_verify(
|
||||
let verify_fut = unverified.verify(|signature, signing_string| {
|
||||
span.in_scope(|| {
|
||||
self.3.clone().signature_verify(
|
||||
algorithm,
|
||||
key_id.clone(),
|
||||
signature.to_string(),
|
||||
signing_string.to_string(),
|
||||
)
|
||||
});
|
||||
|
||||
fut.instrument(span.clone())
|
||||
})
|
||||
});
|
||||
|
||||
req.extensions_mut().insert(SignatureVerified(key_id));
|
||||
|
||||
let f2 = self.0.call(req);
|
||||
let service = Rc::clone(&self.0);
|
||||
|
||||
Box::pin(async move {
|
||||
let span = span;
|
||||
|
||||
if f1.await? {
|
||||
f2.await
|
||||
} else {
|
||||
Err(VerifyError::new(&span, VerifyErrorKind::Validate).into())
|
||||
if verify_fut.instrument(span).await? {
|
||||
req.extensions_mut().insert(SignatureVerified(key_id));
|
||||
}
|
||||
|
||||
service.call(req).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -242,7 +244,6 @@ impl HeaderKind {
|
|||
impl FromRequest for SignatureVerified {
|
||||
type Error = VerifyError;
|
||||
type Future = Ready<Result<Self, Self::Error>>;
|
||||
type Config = ();
|
||||
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
let res = req
|
||||
|
@ -259,31 +260,31 @@ impl FromRequest for SignatureVerified {
|
|||
}
|
||||
}
|
||||
|
||||
impl<T, S, B> Transform<S, ServiceRequest> for VerifySignature<T>
|
||||
impl<T, Spawner, S, B> Transform<S, ServiceRequest> for VerifySignature<T, Spawner>
|
||||
where
|
||||
T: SignatureVerify + Clone + 'static,
|
||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
||||
S::Error: 'static,
|
||||
B: MessageBody + 'static,
|
||||
Spawner: Clone,
|
||||
{
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = actix_web::Error;
|
||||
type Transform = VerifyMiddleware<T, S>;
|
||||
type Transform = VerifyMiddleware<T, Spawner, S>;
|
||||
type InitError = ();
|
||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ready(Ok(VerifyMiddleware(
|
||||
service,
|
||||
Rc::new(service),
|
||||
self.1.clone(),
|
||||
self.2,
|
||||
self.3,
|
||||
self.0.clone(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, B> Service<ServiceRequest> for VerifyMiddleware<T, S>
|
||||
impl<T, Spawner, S, B> Service<ServiceRequest> for VerifyMiddleware<T, Spawner, S>
|
||||
where
|
||||
T: SignatureVerify + Clone + 'static,
|
||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
||||
|
@ -303,7 +304,6 @@ where
|
|||
"Signature Verification",
|
||||
signature.kind = tracing::field::Empty,
|
||||
signature.expected_kind = tracing::field::display(&self.2),
|
||||
signature.optional = tracing::field::display(&self.3),
|
||||
);
|
||||
let authorization = req.headers().get("Authorization").is_some();
|
||||
let signature = req.headers().get("Signature").is_some();
|
||||
|
@ -322,17 +322,9 @@ where
|
|||
}
|
||||
} else {
|
||||
span.record("signature.kind", &tracing::field::display("None"));
|
||||
|
||||
if self.3 {
|
||||
return Box::pin(self.0.call(req));
|
||||
}
|
||||
}
|
||||
|
||||
Box::pin(ready(Err(VerifyError::new(
|
||||
&span,
|
||||
VerifyErrorKind::MissingSignature,
|
||||
)
|
||||
.into())))
|
||||
Box::pin(self.0.call(req))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,70 +1,91 @@
|
|||
use actix_web::{error::BlockingError, http::header::InvalidHeaderValue, web};
|
||||
use awc::ClientRequest;
|
||||
use std::{fmt::Display, future::Future, pin::Pin};
|
||||
|
||||
use crate::{create::Signed, Config, PrepareSignError, Sign};
|
||||
use crate::{create::Signed, Config, PrepareSignError, Sign, Spawn};
|
||||
use actix_rt::task::JoinError;
|
||||
use awc::{
|
||||
http::header::{HttpDate, InvalidHeaderValue, TryIntoHeaderValue},
|
||||
ClientRequest,
|
||||
};
|
||||
use std::{fmt::Display, future::Future, pin::Pin, time::SystemTime};
|
||||
|
||||
impl Sign for ClientRequest {
|
||||
fn authorization_signature<F, E, K>(
|
||||
fn authorization_signature<F, E, K, S>(
|
||||
mut self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<BlockingError>
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let signed = prepare(&self, &config, key_id, f).await?;
|
||||
let signed = prepare(&mut self, &config, key_id, f).await?;
|
||||
signed.authorization_header(self.headers_mut())?;
|
||||
Ok(self)
|
||||
})
|
||||
}
|
||||
|
||||
fn signature<F, E, K>(
|
||||
fn signature<F, E, K, S>(
|
||||
mut self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<BlockingError>
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ From<crate::Canceled>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let signed = prepare(&self, &config, key_id, f).await?;
|
||||
let signed = prepare(&mut self, &config, key_id, f).await?;
|
||||
signed.signature_header(self.headers_mut())?;
|
||||
Ok(self)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn prepare<F, E, K>(
|
||||
request: &ClientRequest,
|
||||
config: &Config,
|
||||
async fn prepare<F, E, K, S>(
|
||||
request: &mut ClientRequest,
|
||||
config: &Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Result<Signed, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<BlockingError> + From<PrepareSignError> + std::fmt::Debug + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display,
|
||||
S: Spawn + 'static,
|
||||
{
|
||||
if config.set_date && !request.headers().contains_key("date") {
|
||||
request.headers_mut().insert(
|
||||
actix_http::header::DATE,
|
||||
HttpDate::from(SystemTime::now())
|
||||
.try_into_value()
|
||||
.expect("Date is valid"),
|
||||
);
|
||||
}
|
||||
|
||||
let mut headers = request.headers().clone();
|
||||
if config.set_host {
|
||||
let header_string = request
|
||||
|
@ -92,7 +113,10 @@ where
|
|||
|
||||
let key_id = key_id.to_string();
|
||||
|
||||
let signed = web::block(move || unsigned.sign(key_id, f)).await??;
|
||||
let signed = config
|
||||
.spawner
|
||||
.spawn_blocking(move || unsigned.sign(key_id, f))
|
||||
.await??;
|
||||
|
||||
Ok(signed)
|
||||
}
|
61
flake.lock
Normal file
61
flake.lock
Normal file
|
@ -0,0 +1,61 @@
|
|||
{
|
||||
"nodes": {
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1694529238,
|
||||
"narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1700794826,
|
||||
"narHash": "sha256-RyJTnTNKhO0yqRpDISk03I/4A67/dp96YRxc86YOPgU=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "5a09cb4b393d58f9ed0d9ca1555016a8543c2ac8",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
25
flake.nix
Normal file
25
flake.nix
Normal file
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
description = "http-signature-normalization";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, flake-utils }:
|
||||
flake-utils.lib.eachDefaultSystem (system:
|
||||
let
|
||||
pkgs = import nixpkgs {
|
||||
inherit system;
|
||||
};
|
||||
in
|
||||
{
|
||||
packages.default = pkgs.hello;
|
||||
|
||||
devShell = with pkgs; mkShell {
|
||||
nativeBuildInputs = [ cargo cargo-expand cargo-outdated cargo-zigbuild clippy gcc protobuf rust-analyzer rustc rustfmt ];
|
||||
|
||||
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
|
||||
};
|
||||
});
|
||||
}
|
|
@ -1,45 +0,0 @@
|
|||
[package]
|
||||
name = "http-signature-normalization-actix"
|
||||
description = "An HTTP Signatures library that leaves the signing to you"
|
||||
version = "0.5.0-beta.9"
|
||||
authors = ["asonix <asonix@asonix.dog>"]
|
||||
license-file = "LICENSE"
|
||||
readme = "README.md"
|
||||
repository = "https://git.asonix.dog/Aardwolf/http-signature-normalization"
|
||||
keywords = ["http", "signatures", "digest", "actix"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[features]
|
||||
default = ["sha-2", "sha-3"]
|
||||
digest = ["base64"]
|
||||
sha-2 = ["digest", "sha2"]
|
||||
sha-3 = ["digest", "sha3"]
|
||||
|
||||
[[example]]
|
||||
name = "server"
|
||||
required-features = ["sha-2"]
|
||||
|
||||
[[example]]
|
||||
name = "client"
|
||||
required-features = ["sha-2"]
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "4.0.0-beta.8", default-features = false }
|
||||
awc = { version = "3.0.0-beta.7", default-features = false }
|
||||
base64 = { version = "0.13", optional = true }
|
||||
chrono = "0.4.6"
|
||||
futures-util = { version = "0.3", default-features = false }
|
||||
http-signature-normalization = { version = "0.5.1", path = ".." }
|
||||
sha2 = { version = "0.9", optional = true }
|
||||
sha3 = { version = "0.9", optional = true }
|
||||
thiserror = "1.0"
|
||||
tokio = { version = "1", default-features = false, features = ["sync"] }
|
||||
tracing = "0.1"
|
||||
tracing-error = "0.1"
|
||||
tracing-futures = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "2.1.0"
|
||||
tracing-actix-web = { version = "0.4.0-beta.13" }
|
||||
tracing-subscriber = { version = "0.2", features = ["fmt"] }
|
|
@ -1,417 +0,0 @@
|
|||
Http Signature Normalization
|
||||
Copyright Riley Trautman 2019
|
||||
|
||||
COOPERATIVE SOFTWARE LICENSE
|
||||
|
||||
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS
|
||||
COPYFARLEFT PUBLIC LICENSE ("LICENSE"). THE WORK IS PROTECTED BY
|
||||
COPYRIGHT AND ALL OTHER APPLICABLE LAWS. ANY USE OF THE WORK OTHER THAN
|
||||
AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY
|
||||
EXERCISING ANY RIGHTS TO THE WORK PROVIDED IN THIS LICENSE, YOU AGREE
|
||||
TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE
|
||||
MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
|
||||
CONTAINED HERE IN AS CONSIDERATION FOR ACCEPTING THE TERMS AND
|
||||
CONDITIONS OF THIS LICENSE AND FOR AGREEING TO BE BOUND BY THE TERMS
|
||||
AND CONDITIONS OF THIS LICENSE.
|
||||
|
||||
1. DEFINITIONS
|
||||
|
||||
a. "Adaptation" means a work based upon the Work, or upon the
|
||||
Work and other pre-existing works, such as a translation,
|
||||
adaptation, derivative work, arrangement of music or other
|
||||
alterations of a literary or artistic work, or phonogram or
|
||||
performance and includes cinematographic adaptations or any
|
||||
other form in which the Work may be recast, transformed, or
|
||||
adapted including in any form recognizably derived from the
|
||||
original, except that a work that constitutes a Collection will
|
||||
not be considered an Adaptation for the purpose of this License.
|
||||
For the avoidance of doubt, where the Work is a musical work,
|
||||
performance or phonogram, the synchronization of the Work in
|
||||
timed-relation with a moving image ("synching") will be
|
||||
considered an Adaptation for the purpose of this License.
|
||||
|
||||
b. "Collection" means a collection of literary or artistic
|
||||
works, such as encyclopedias and anthologies, or performances,
|
||||
phonograms or broadcasts, or other works or subject matter other
|
||||
than works listed in Section 1(f) below, which, by reason of the
|
||||
selection and arrangement of their contents, constitute
|
||||
intellectual creations, in which the Work is included in its
|
||||
entirety in unmodified form along with one or more other
|
||||
contributions, each constituting separate and independent works
|
||||
in themselves, which together are assembled into a collective
|
||||
whole. A work that constitutes a Collection will not be
|
||||
considered an Adaptation (as defined above) for the purposes of
|
||||
this License.
|
||||
|
||||
c. "Distribute" means to make available to the public the
|
||||
original and copies of the Work or Adaptation, as appropriate,
|
||||
through sale, gift or any other transfer of possession or
|
||||
ownership.
|
||||
|
||||
d. "Licensor" means the individual, individuals, entity or
|
||||
entities that offer(s) the Work under the terms of this License.
|
||||
|
||||
e. "Original Author" means, in the case of a literary or
|
||||
artistic work, the individual, individuals, entity or entities
|
||||
who created the Work or if no individual or entity can be
|
||||
identified, the publisher; and in addition (i) in the case of a
|
||||
performance the actors, singers, musicians, dancers, and other
|
||||
persons who act, sing, deliver, declaim, play in, interpret or
|
||||
otherwise perform literary or artistic works or expressions of
|
||||
folklore; (ii) in the case of a phonogram the producer being the
|
||||
person or legal entity who first fixes the sounds of a
|
||||
performance or other sounds; and, (iii) in the case of
|
||||
broadcasts, the organization that transmits the broadcast.
|
||||
|
||||
f. "Work" means the literary and/or artistic work offered under
|
||||
the terms of this License including without limitation any
|
||||
production in the literary, scientific and artistic domain,
|
||||
whatever may be the mode or form of its expression including
|
||||
digital form, such as a book, pamphlet and other writing; a
|
||||
lecture, address, sermon or other work of the same nature; a
|
||||
dramatic or dramatico-musical work; a choreographic work or
|
||||
entertainment in dumb show; a musical composition with or
|
||||
without words; a cinematographic work to which are assimilated
|
||||
works expressed by a process analogous to cinematography; a work
|
||||
of drawing, painting, architecture, sculpture, engraving or
|
||||
lithography; a photographic work to which are assimilated works
|
||||
expressed by a process analogous to photography; a work of
|
||||
applied art; an illustration, map, plan, sketch or
|
||||
three-dimensional work relative to geography, topography,
|
||||
architecture or science; a performance; a broadcast; a
|
||||
phonogram; a compilation of data to the extent it is protected
|
||||
as a copyrightable work; or a work performed by a variety or
|
||||
circus performer to the extent it is not otherwise considered a
|
||||
literary or artistic work.
|
||||
|
||||
g. "You" means an individual or entity exercising rights under
|
||||
this License who has not previously violated the terms of this
|
||||
License with respect to the Work, or who has received express
|
||||
permission from the Licensor to exercise rights under this
|
||||
License despite a previous violation.
|
||||
|
||||
h. "Publicly Perform" means to perform public recitations of the
|
||||
Work and to communicate to the public those public recitations,
|
||||
by any means or process, including by wire or wireless means or
|
||||
public digital performances; to make available to the public
|
||||
Works in such a way that members of the public may access these
|
||||
Works from a place and at a place individually chosen by them;
|
||||
to perform the Work to the public by any means or process and
|
||||
the communication to the public of the performances of the Work,
|
||||
including by public digital performance; to broadcast and
|
||||
rebroadcast the Work by any means including signs, sounds or
|
||||
images.
|
||||
|
||||
i. "Reproduce" means to make copies of the Work by any means
|
||||
including without limitation by sound or visual recordings and
|
||||
the right of fixation and reproducing fixations of the Work,
|
||||
including storage of a protected performance or phonogram in
|
||||
digital form or other electronic medium.
|
||||
|
||||
j. "Software" means any digital Work which, through use of a
|
||||
third-party piece of Software or through the direct usage of
|
||||
itself on a computer system, the memory of the computer is
|
||||
modified dynamically or semi-dynamically. "Software",
|
||||
secondly, processes or interprets information.
|
||||
|
||||
k. "Source Code" means the human-readable form of Software
|
||||
through which the Original Author and/or Distributor originally
|
||||
created, derived, and/or modified it.
|
||||
|
||||
l. "Web Service" means the use of a piece of Software to
|
||||
interpret or modify information that is subsequently and directly
|
||||
served to users over the Internet.
|
||||
|
||||
2. FAIR DEALING RIGHTS
|
||||
|
||||
Nothing in this License is intended to reduce, limit, or restrict any
|
||||
uses free from copyright or rights arising from limitations or
|
||||
exceptions that are provided for in connection with the copyright
|
||||
protection under copyright law or other applicable laws.
|
||||
|
||||
3. LICENSE GRANT
|
||||
|
||||
Subject to the terms and conditions of this License, Licensor hereby
|
||||
grants You a worldwide, royalty-free, non-exclusive, perpetual (for the
|
||||
duration of the applicable copyright) license to exercise the rights in
|
||||
the Work as stated below:
|
||||
|
||||
a. to Reproduce the Work, to incorporate the Work into one or
|
||||
more Collections, and to Reproduce the Work as incorporated in
|
||||
the Collections;
|
||||
|
||||
b. to create and Reproduce Adaptations provided that any such
|
||||
Adaptation, including any translation in any medium, takes
|
||||
reasonable steps to clearly label, demarcate or otherwise
|
||||
identify that changes were made to the original Work. For
|
||||
example, a translation could be marked "The original work was
|
||||
translated from English to Spanish," or a modification could
|
||||
indicate "The original work has been modified.";
|
||||
|
||||
c. to Distribute and Publicly Perform the Work including as
|
||||
incorporated in Collections; and,
|
||||
|
||||
d. to Distribute and Publicly Perform Adaptations. The above
|
||||
rights may be exercised in all media and formats whether now
|
||||
known or hereafter devised. The above rights include the right
|
||||
to make such modifications as are technically necessary to
|
||||
exercise the rights in other media and formats. Subject to
|
||||
Section 8(g), all rights not expressly granted by Licensor are
|
||||
hereby reserved, including but not limited to the rights set
|
||||
forth in Section 4(h).
|
||||
|
||||
4. RESTRICTIONS
|
||||
|
||||
The license granted in Section 3 above is expressly made subject to and
|
||||
limited by the following restrictions:
|
||||
|
||||
a. You may Distribute or Publicly Perform the Work only under
|
||||
the terms of this License. You must include a copy of, or the
|
||||
Uniform Resource Identifier (URI) for, this License with every
|
||||
copy of the Work You Distribute or Publicly Perform. You may not
|
||||
offer or impose any terms on the Work that restrict the terms of
|
||||
this License or the ability of the recipient of the Work to
|
||||
exercise the rights granted to that recipient under the terms of
|
||||
the License. You may not sublicense the Work. You must keep
|
||||
intact all notices that refer to this License and to the
|
||||
disclaimer of warranties with every copy of the Work You
|
||||
Distribute or Publicly Perform. When You Distribute or Publicly
|
||||
Perform the Work, You may not impose any effective technological
|
||||
measures on the Work that restrict the ability of a recipient of
|
||||
the Work from You to exercise the rights granted to that
|
||||
recipient under the terms of the License. This Section 4(a)
|
||||
applies to the Work as incorporated in a Collection, but this
|
||||
does not require the Collection apart from the Work itself to be
|
||||
made subject to the terms of this License. If You create a
|
||||
Collection, upon notice from any Licensor You must, to the
|
||||
extent practicable, remove from the Collection any credit as
|
||||
required by Section 4(f), as requested. If You create an
|
||||
Adaptation, upon notice from any Licensor You must, to the
|
||||
extent practicable, remove from the Adaptation any credit as
|
||||
required by Section 4(f), as requested.
|
||||
|
||||
b. Subject to the exception in Section 4(e), you may not
|
||||
exercise any of the rights granted to You in Section 3 above in
|
||||
any manner that is primarily intended for or directed toward
|
||||
commercial advantage or private monetary compensation. The
|
||||
exchange of the Work for other copyrighted works by means of
|
||||
digital file-sharing or otherwise shall not be considered to be
|
||||
intended for or directed toward commercial advantage or private
|
||||
monetary compensation, provided there is no payment of any
|
||||
monetary compensation in connection with the exchange of
|
||||
copyrighted works.
|
||||
|
||||
c. If the Work meets the definition of Software, You may exercise
|
||||
the rights granted in Section 3 only if You provide a copy of the
|
||||
corresponding Source Code from which the Work was derived in digital
|
||||
form, or You provide a URI for the corresponding Source Code of
|
||||
the Work, to any recipients upon request.
|
||||
|
||||
d. If the Work is used as or for a Web Service, You may exercise
|
||||
the rights granted in Section 3 only if You provide a copy of the
|
||||
corresponding Source Code from which the Work was derived in digital
|
||||
form, or You provide a URI for the corresponding Source Code to the
|
||||
Work, to any recipients of the data served or modified by the Web
|
||||
Service.
|
||||
|
||||
e. You may exercise the rights granted in Section 3 for
|
||||
commercial purposes only if you satisfy any of the following:
|
||||
|
||||
i. You are a worker-owned business or worker-owned
|
||||
collective; and
|
||||
ii. after tax, all financial gain, surplus, profits and
|
||||
benefits produced by the business or collective are
|
||||
distributed among the worker-owners
|
||||
iii. You are not using such rights on behalf of a business
|
||||
other than those specified in 4(e.i) and elaborated upon in
|
||||
4(e.ii), nor are using such rights as a proxy on behalf of a
|
||||
business with the intent to circumvent the aforementioned
|
||||
restrictions on such a business.
|
||||
|
||||
f. Any use by a business that is privately owned and managed,
|
||||
and that seeks to generate profit from the labor of employees
|
||||
paid by salary or other wages, is not permitted under this
|
||||
license.
|
||||
|
||||
g. If You Distribute, or Publicly Perform the Work or any
|
||||
Adaptations or Collections, You must, unless a request has been
|
||||
made pursuant to Section 4(a), keep intact all copyright notices
|
||||
for the Work and provide, reasonable to the medium or means You
|
||||
are utilizing: (i) the name of the Original Author (or
|
||||
pseudonym, if applicable) if supplied, and/or if the Original
|
||||
Author and/or Licensor designate another party or parties (e.g.,
|
||||
a sponsor institute, publishing entity, journal) for attribution
|
||||
("Attribution Parties") in Licensor!s copyright notice, terms of
|
||||
service or by other reasonable means, the name of such party or
|
||||
parties; (ii) the title of the Work if supplied; (iii) to the
|
||||
extent reasonably practicable, the URI, if any, that Licensor
|
||||
specifies to be associated with the Work, unless such URI does
|
||||
not refer to the copyright notice or licensing information for
|
||||
the Work; and, (iv) consistent with Section 3(b), in the case of
|
||||
an Adaptation, a credit identifying the use of the Work in the
|
||||
Adaptation (e.g., "French translation of the Work by Original
|
||||
Author," or "Screenplay based on original Work by Original
|
||||
Author"). The credit required by this Section 4(f) may be
|
||||
implemented in any reasonable manner; provided, however, that in
|
||||
the case of a Adaptation or Collection, at a minimum such credit
|
||||
will appear, if a credit for all contributing authors of the
|
||||
Adaptation or Collection appears, then as part of these credits
|
||||
and in a manner at least as prominent as the credits for the
|
||||
other contributing authors. For the avoidance of doubt, You may
|
||||
only use the credit required by this Section for the purpose of
|
||||
attribution in the manner set out above and, by exercising Your
|
||||
rights under this License, You may not implicitly or explicitly
|
||||
assert or imply any connection with, sponsorship or endorsement
|
||||
by the Original Author, Licensor and/or Attribution Parties, as
|
||||
appropriate, of You or Your use of the Work, without the
|
||||
separate, express prior written permission of the Original
|
||||
Author, Licensor and/or Attribution Parties.
|
||||
|
||||
h. For the avoidance of doubt:
|
||||
|
||||
i. Non-waivable Compulsory License Schemes. In those
|
||||
jurisdictions in which the right to collect royalties
|
||||
through any statutory or compulsory licensing scheme
|
||||
cannot be waived, the Licensor reserves the exclusive
|
||||
right to collect such royalties for any exercise by You of
|
||||
the rights granted under this License;
|
||||
|
||||
ii. Waivable Compulsory License Schemes. In those
|
||||
jurisdictions in which the right to collect royalties
|
||||
through any statutory or compulsory licensing scheme can
|
||||
be waived, the Licensor reserves the exclusive right to
|
||||
collect such royalties for any exercise by You of the
|
||||
rights granted under this License if Your exercise of such
|
||||
rights is for a purpose or use which is otherwise than
|
||||
noncommercial as permitted under Section 4(b) and
|
||||
otherwise waives the right to collect royalties through
|
||||
any statutory or compulsory licensing scheme; and,
|
||||
iii.Voluntary License Schemes. The Licensor reserves the
|
||||
right to collect royalties, whether individually or, in
|
||||
the event that the Licensor is a member of a collecting
|
||||
society that administers voluntary licensing schemes, via
|
||||
that society, from any exercise by You of the rights
|
||||
granted under this License that is for a purpose or use
|
||||
which is otherwise than noncommercial as permitted under
|
||||
Section 4(b).
|
||||
|
||||
i. Except as otherwise agreed in writing by the Licensor or as
|
||||
may be otherwise permitted by applicable law, if You Reproduce,
|
||||
Distribute or Publicly Perform the Work either by itself or as
|
||||
part of any Adaptations or Collections, You must not distort,
|
||||
mutilate, modify or take other derogatory action in relation to
|
||||
the Work which would be prejudicial to the Original Author's
|
||||
honor or reputation. Licensor agrees that in those jurisdictions
|
||||
(e.g. Japan), in which any exercise of the right granted in
|
||||
Section 3(b) of this License (the right to make Adaptations)
|
||||
would be deemed to be a distortion, mutilation, modification or
|
||||
other derogatory action prejudicial to the Original Author's
|
||||
honor and reputation, the Licensor will waive or not assert, as
|
||||
appropriate, this Section, to the fullest extent permitted by
|
||||
the applicable national law, to enable You to reasonably
|
||||
exercise Your right under Section 3(b) of this License (right to
|
||||
make Adaptations) but not otherwise.
|
||||
|
||||
5. REPRESENTATIONS, WARRANTIES AND DISCLAIMER
|
||||
|
||||
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
|
||||
OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
|
||||
KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
|
||||
INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
|
||||
LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF
|
||||
ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW
|
||||
THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO
|
||||
YOU.
|
||||
|
||||
6. LIMITATION ON LIABILITY
|
||||
|
||||
EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL
|
||||
LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF
|
||||
THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED
|
||||
OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
7. TERMINATION
|
||||
|
||||
a. This License and the rights granted hereunder will terminate
|
||||
automatically upon any breach by You of the terms of this
|
||||
License. Individuals or entities who have received Adaptations
|
||||
or Collections from You under this License, however, will not
|
||||
have their licenses terminated provided such individuals or
|
||||
entities remain in full compliance with those licenses. Sections
|
||||
1, 2, 5, 6, 7, and 8 will survive any termination of this
|
||||
License.
|
||||
|
||||
b. Subject to the above terms and conditions, the license
|
||||
granted here is perpetual (for the duration of the applicable
|
||||
copyright in the Work). Notwithstanding the above, Licensor
|
||||
reserves the right to release the Work under different license
|
||||
terms or to stop distributing the Work at any time; provided,
|
||||
however that any such election will not serve to withdraw this
|
||||
License (or any other license that has been, or is required to
|
||||
be, granted under the terms of this License), and this License
|
||||
will continue in full force and effect unless terminated as
|
||||
stated above.
|
||||
|
||||
8. MISCELLANEOUS
|
||||
|
||||
a. Each time You Distribute or Publicly Perform the Work or a
|
||||
Collection, the Licensor offers to the recipient a license to
|
||||
the Work on the same terms and conditions as the license granted
|
||||
to You under this License.
|
||||
|
||||
b. Each time You Distribute or Publicly Perform an Adaptation,
|
||||
Licensor offers to the recipient a license to the original Work
|
||||
on the same terms and conditions as the license granted to You
|
||||
under this License.
|
||||
|
||||
c. If the Work is classified as Software, each time You Distribute
|
||||
or Publicly Perform an Adaptation, Licensor offers to the recipient
|
||||
a copy and/or URI of the corresponding Source Code on the same
|
||||
terms and conditions as the license granted to You under this License.
|
||||
|
||||
d. If the Work is used as a Web Service, each time You Distribute
|
||||
or Publicly Perform an Adaptation, or serve data derived from the
|
||||
Software, the Licensor offers to any recipients of the data a copy
|
||||
and/or URI of the corresponding Source Code on the same terms and
|
||||
conditions as the license granted to You under this License.
|
||||
|
||||
e. If any provision of this License is invalid or unenforceable
|
||||
under applicable law, it shall not affect the validity or
|
||||
enforceability of the remainder of the terms of this License,
|
||||
and without further action by the parties to this agreement,
|
||||
such provision shall be reformed to the minimum extent necessary
|
||||
to make such provision valid and enforceable.
|
||||
|
||||
f. No term or provision of this License shall be deemed waived
|
||||
and no breach consented to unless such waiver or consent shall
|
||||
be in writing and signed by the party to be charged with such
|
||||
waiver or consent.
|
||||
|
||||
g. This License constitutes the entire agreement between the
|
||||
parties with respect to the Work licensed here. There are no
|
||||
understandings, agreements or representations with respect to
|
||||
the Work not specified here. Licensor shall not be bound by any
|
||||
additional provisions that may appear in any communication from
|
||||
You. This License may not be modified without the mutual written
|
||||
agreement of the Licensor and You.
|
||||
|
||||
h. The rights granted under, and the subject matter referenced,
|
||||
in this License were drafted utilizing the terminology of the
|
||||
Berne Convention for the Protection of Literary and Artistic
|
||||
Works (as amended on September 28, 1979), the Rome Convention of
|
||||
1961, the WIPO Copyright Treaty of 1996, the WIPO Performances
|
||||
and Phonograms Treaty of 1996 and the Universal Copyright
|
||||
Convention (as revised on July 24, 1971). These rights and
|
||||
subject matter take effect in the relevant jurisdiction in which
|
||||
the License terms are sought to be enforced according to the
|
||||
corresponding provisions of the implementation of those treaty
|
||||
provisions in the applicable national law. If the standard suite
|
||||
of rights granted under applicable copyright law includes
|
||||
additional rights not granted under this License, such
|
||||
additional rights are deemed to be included in the License; this
|
||||
License is not intended to restrict the license of any rights
|
||||
under applicable law.
|
||||
|
||||
|
|
@ -1,182 +0,0 @@
|
|||
# HTTP Signature Normaliztion Actix
|
||||
_An HTTP Signatures library that leaves the signing to you_
|
||||
|
||||
- [crates.io](https://crates.io/crates/http-signature-normalization-actix)
|
||||
- [docs.rs](https://docs.rs/http-signature-normalization-actix)
|
||||
- [Hit me up on Mastodon](https://asonix.dog/@asonix)
|
||||
|
||||
Http Signature Normalization is a minimal-dependency crate for producing HTTP Signatures with user-provided signing and verification. The API is simple; there's a series of steps for creation and verification with types that ensure reasonable usage.
|
||||
|
||||
## Usage
|
||||
|
||||
This crate provides extensions the ClientRequest type from Actix Web, and provides middlewares for verifying HTTP Signatures, and optionally, Digest headers
|
||||
|
||||
#### First, add this crate to your dependencies
|
||||
```toml
|
||||
actix-rt = "2.0.2"
|
||||
actix-web = "4.0.0-beta.3"
|
||||
thiserror = "0.1"
|
||||
http-signature-normalization-actix = { version = "0.5.0-beta.2", default-features = false, features = ["sha-2"] }
|
||||
sha2 = "0.9"
|
||||
```
|
||||
|
||||
#### Then, use it in your client
|
||||
|
||||
```rust
|
||||
use actix_web::client::Client;
|
||||
use http_signature_normalization_actix::prelude::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let config = Config::default();
|
||||
let mut digest = Sha256::new();
|
||||
|
||||
let mut response = Client::default()
|
||||
.post("http://127.0.0.1:8010/")
|
||||
.header("User-Agent", "Actix Web")
|
||||
.authorization_signature_with_digest(&config, "my-key-id", &mut digest, "My request body", |s| {
|
||||
Ok(base64::encode(s)) as Result<_, MyError>
|
||||
})?
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error, {}", e);
|
||||
MyError::SendRequest
|
||||
})?;
|
||||
|
||||
let body = response.body().await.map_err(|e| {
|
||||
eprintln!("Error, {}", e);
|
||||
MyError::Body
|
||||
})?;
|
||||
|
||||
println!("{:?}", body);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MyError {
|
||||
#[error("Failed to read header, {0}")]
|
||||
Convert(#[from] ToStrError),
|
||||
|
||||
#[error("Failed to create header, {0}")]
|
||||
Header(#[from] InvalidHeaderValue),
|
||||
|
||||
#[error("Failed to send request")]
|
||||
SendRequest,
|
||||
|
||||
#[error("Failed to retrieve request body")]
|
||||
Body,
|
||||
}
|
||||
```
|
||||
|
||||
#### Or, use it in your server
|
||||
|
||||
```rust
|
||||
use actix_web::{http::StatusCode, web, App, HttpResponse, HttpServer, ResponseError};
|
||||
use futures::future::{err, ok, Ready};
|
||||
use http_signature_normalization_actix::prelude::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct MyVerify;
|
||||
|
||||
impl SignatureVerify for MyVerify {
|
||||
type Error = MyError;
|
||||
type Future = Ready<Result<bool, Self::Error>>;
|
||||
|
||||
fn signature_verify(
|
||||
&mut self,
|
||||
algorithm: Option<Algorithm>,
|
||||
key_id: String,
|
||||
signature: String,
|
||||
signing_string: String,
|
||||
) -> Self::Future {
|
||||
match algorithm {
|
||||
Some(Algorithm::Hs2019) => (),
|
||||
_ => return err(MyError::Algorithm),
|
||||
};
|
||||
|
||||
if key_id != "my-key-id" {
|
||||
return err(MyError::Key);
|
||||
}
|
||||
|
||||
let decoded = match base64::decode(&signature) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(_) => return err(MyError::Decode),
|
||||
};
|
||||
|
||||
ok(decoded == signing_string.as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
async fn index((_, sig_verified): (DigestVerified, SignatureVerified)) -> &'static str {
|
||||
println!("Signature verified for {}", sig_verified.key_id());
|
||||
"Eyyyyup"
|
||||
}
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let config = Config::default();
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.wrap(VerifyDigest::new(Sha256::new()).optional())
|
||||
.wrap(
|
||||
VerifySignature::new(MyVerify, config.clone())
|
||||
.authorization()
|
||||
.optional(),
|
||||
)
|
||||
.route("/", web::post().to(index))
|
||||
})
|
||||
.bind("127.0.0.1:8010")?
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum MyError {
|
||||
#[error("Failed to verify, {}", _0)]
|
||||
Verify(#[from] PrepareVerifyError),
|
||||
|
||||
#[error("Unsupported algorithm")]
|
||||
Algorithm,
|
||||
|
||||
#[error("Couldn't decode signature")]
|
||||
Decode,
|
||||
|
||||
#[error("Invalid key")]
|
||||
Key,
|
||||
}
|
||||
|
||||
impl ResponseError for MyError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
HttpResponse::BadRequest().finish()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Contributing
|
||||
Unless otherwise stated, all contributions to this project will be licensed under the CSL with
|
||||
the exceptions listed in the License section of this file.
|
||||
|
||||
### License
|
||||
This work is licensed under the Cooperative Software License. This is not a Free Software
|
||||
License, but may be considered a "source-available License." For most hobbyists, self-employed
|
||||
developers, worker-owned companies, and cooperatives, this software can be used in most
|
||||
projects so long as this software is distributed under the terms of the CSL. For more
|
||||
information, see the provided LICENSE file. If none exists, the license can be found online
|
||||
[here](https://lynnesbian.space/csl/). If you are a free software project and wish to use this
|
||||
software under the terms of the GNU Affero General Public License, please contact me at
|
||||
[asonix@asonix.dog](mailto:asonix@asonix.dog) and we can sort that out. If you wish to use this
|
||||
project under any other license, especially in proprietary software, the answer is likely no.
|
||||
|
||||
Http Signature Normalization Actix is currently licensed under the AGPL to the Lemmy project, found
|
||||
at [github.com/LemmyNet/lemmy](https://github.com/LemmyNet/lemmy)
|
|
@ -1,130 +0,0 @@
|
|||
//! Types and Traits for creating and verifying Digest headers
|
||||
//!
|
||||
//! Digest headers are commonly used in conjunction with HTTP Signatures to verify the whole
|
||||
//! request when request bodies are present
|
||||
|
||||
use actix_web::{error::BlockingError, http::header::InvalidHeaderValue};
|
||||
use awc::{ClientRequest, SendClientRequest};
|
||||
use std::{fmt::Display, future::Future, pin::Pin};
|
||||
|
||||
use crate::{Config, PrepareSignError, Sign};
|
||||
|
||||
pub mod middleware;
|
||||
#[cfg(feature = "sha-2")]
|
||||
mod sha2;
|
||||
#[cfg(feature = "sha-3")]
|
||||
mod sha3;
|
||||
|
||||
mod sign;
|
||||
|
||||
/// A trait for creating digests of an array of bytes
|
||||
pub trait DigestCreate {
|
||||
/// The name of the digest algorithm
|
||||
const NAME: &'static str;
|
||||
|
||||
/// Compute the digest of the input bytes
|
||||
fn compute(&mut self, input: &[u8]) -> String;
|
||||
}
|
||||
|
||||
/// A trait for verifying digests
|
||||
pub trait DigestVerify {
|
||||
/// Update the verifier with bytes from the request body
|
||||
fn update(&mut self, part: &[u8]);
|
||||
|
||||
/// Verify the request body against the digests from the request headers
|
||||
fn verify(&mut self, digests: &[DigestPart]) -> bool;
|
||||
}
|
||||
|
||||
/// Extend the Sign trait with support for adding Digest Headers to the request
|
||||
///
|
||||
/// It generates HTTP Signatures after the Digest header has been added, in order to have
|
||||
/// verification that the body has not been tampered with, or that the request can't be replayed by
|
||||
/// a malicious entity
|
||||
pub trait SignExt: Sign {
|
||||
/// Set the Digest and Authorization headers on the request
|
||||
fn authorization_signature_with_digest<F, E, K, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<BlockingError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized;
|
||||
|
||||
/// Set the Digest and Signature headers on the request
|
||||
fn signature_with_digest<F, E, K, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<BlockingError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
/// A parsed digest from the request
|
||||
#[derive(Debug)]
|
||||
pub struct DigestPart {
|
||||
/// The alrogithm used to produce the digest
|
||||
pub algorithm: String,
|
||||
|
||||
/// The digest itself
|
||||
pub digest: String,
|
||||
}
|
||||
|
||||
/// An intermediate type between setting the Digest and Signature or Authorization headers, and
|
||||
/// actually sending the request
|
||||
///
|
||||
/// This exists so that the return type for the [`SignExt`] trait can be named
|
||||
pub struct DigestClient<V> {
|
||||
req: ClientRequest,
|
||||
body: V,
|
||||
}
|
||||
|
||||
impl<V> DigestClient<V>
|
||||
where
|
||||
V: AsRef<[u8]>,
|
||||
{
|
||||
fn new(req: ClientRequest, body: V) -> Self {
|
||||
DigestClient { req, body }
|
||||
}
|
||||
|
||||
/// Send the request
|
||||
///
|
||||
/// This is analogous to `ClientRequest::send_body` and uses the body provided when producing
|
||||
/// the digest
|
||||
pub fn send(self) -> SendClientRequest {
|
||||
self.req.send_body(self.body.as_ref().to_vec())
|
||||
}
|
||||
|
||||
/// Split the parts of the request
|
||||
///
|
||||
/// In case the caller needs to interrogate the ClientRequest before sending
|
||||
pub fn split(self) -> (ClientRequest, V) {
|
||||
(self.req, self.body)
|
||||
}
|
||||
}
|
|
@ -1,143 +0,0 @@
|
|||
use sha2::{Sha224, Sha256, Sha384, Sha512, Sha512Trunc224, Sha512Trunc256};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::{DigestCreate, DigestPart, DigestVerify};
|
||||
|
||||
fn create(digest: &mut impl sha2::Digest, input: &[u8]) -> String {
|
||||
digest.update(input);
|
||||
base64::encode(&digest.finalize_reset())
|
||||
}
|
||||
|
||||
fn verify(digest: &mut impl sha2::Digest, name: &str, parts: &[DigestPart]) -> bool {
|
||||
if let Some(part) = parts
|
||||
.iter()
|
||||
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
||||
{
|
||||
debug!("Verifying digest type, {}", name);
|
||||
let encoded = base64::encode(&digest.finalize_reset());
|
||||
|
||||
return part.digest == encoded;
|
||||
}
|
||||
warn!("No matching digest algorithm found for {}", name);
|
||||
warn!(
|
||||
"Provided: [{}]",
|
||||
parts.iter().fold(String::new(), |mut acc, item| {
|
||||
if acc.is_empty() {
|
||||
} else {
|
||||
acc.push_str(", ");
|
||||
}
|
||||
acc.push_str(&item.algorithm);
|
||||
acc
|
||||
})
|
||||
);
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha224 {
|
||||
const NAME: &'static str = "SHA-224";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha224 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha256 {
|
||||
const NAME: &'static str = "SHA-256";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha256 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha384 {
|
||||
const NAME: &'static str = "SHA-384";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha384 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha512 {
|
||||
const NAME: &'static str = "SHA-512";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha512 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha512Trunc224 {
|
||||
const NAME: &'static str = "SHA-512-224";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha512Trunc224 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha512Trunc256 {
|
||||
const NAME: &'static str = "SHA-512-256";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha512Trunc256 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha2::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
|
@ -1,200 +0,0 @@
|
|||
use sha3::{
|
||||
Keccak224, Keccak256, Keccak256Full, Keccak384, Keccak512, Sha3_224, Sha3_256, Sha3_384,
|
||||
Sha3_512,
|
||||
};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::{DigestCreate, DigestPart, DigestVerify};
|
||||
|
||||
fn create(digest: &mut impl sha3::Digest, input: &[u8]) -> String {
|
||||
digest.update(input);
|
||||
base64::encode(&digest.finalize_reset())
|
||||
}
|
||||
|
||||
fn verify(digest: &mut impl sha3::Digest, name: &str, parts: &[DigestPart]) -> bool {
|
||||
if let Some(part) = parts
|
||||
.iter()
|
||||
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
||||
{
|
||||
debug!("Verifying digest type, {}", name);
|
||||
let encoded = base64::encode(&digest.finalize_reset());
|
||||
|
||||
return part.digest == encoded;
|
||||
}
|
||||
warn!("No matching digest algorithm found for {}", name);
|
||||
warn!(
|
||||
"Provided: [{}]",
|
||||
parts.iter().fold(String::new(), |mut acc, item| {
|
||||
if acc.is_empty() {
|
||||
} else {
|
||||
acc.push_str(", ");
|
||||
}
|
||||
acc.push_str(&item.algorithm);
|
||||
acc
|
||||
})
|
||||
);
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha3_224 {
|
||||
const NAME: &'static str = "SHA3-224";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha3_224 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha3_256 {
|
||||
const NAME: &'static str = "SHA3-256";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha3_256 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha3_384 {
|
||||
const NAME: &'static str = "SHA3-384";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha3_384 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha3_512 {
|
||||
const NAME: &'static str = "SHA3-512";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Sha3_512 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak224 {
|
||||
const NAME: &'static str = "keccak-224";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak224 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak256 {
|
||||
const NAME: &'static str = "keccak-256";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak256 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak256Full {
|
||||
const NAME: &'static str = "keccak-256-full";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak256Full {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak384 {
|
||||
const NAME: &'static str = "keccak-384";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak384 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Keccak512 {
|
||||
const NAME: &'static str = "keccak-512";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestVerify for Keccak512 {
|
||||
fn update(&mut self, part: &[u8]) {
|
||||
sha3::Digest::update(self, part);
|
||||
}
|
||||
|
||||
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||
verify(self, <Self as DigestCreate>::NAME, parts)
|
||||
}
|
||||
}
|
|
@ -1,453 +0,0 @@
|
|||
#![deny(missing_docs)]
|
||||
|
||||
//! # Integration of Http Signature Normalization with Actix Web
|
||||
//!
|
||||
//! This library provides middlewares for verifying HTTP Signature headers and, optionally, Digest
|
||||
//! headers with the `digest` feature enabled. It also extends awc's ClientRequest type to
|
||||
//! add signatures and digests to the request
|
||||
//!
|
||||
//! ### Use it in a server
|
||||
//! ```rust,ignore
|
||||
//! use actix_web::{http::StatusCode, web, App, HttpResponse, HttpServer, ResponseError};
|
||||
//! use http_signature_normalization_actix::prelude::*;
|
||||
//! use sha2::{Digest, Sha256};
|
||||
//! use std::future::{ready, Ready};
|
||||
//!
|
||||
//! #[derive(Clone, Debug)]
|
||||
//! struct MyVerify;
|
||||
//!
|
||||
//! impl SignatureVerify for MyVerify {
|
||||
//! type Error = MyError;
|
||||
//! type Future = Ready<Result<bool, Self::Error>>;
|
||||
//!
|
||||
//! fn signature_verify(
|
||||
//! &mut self,
|
||||
//! algorithm: Option<Algorithm>,
|
||||
//! key_id: String,
|
||||
//! signature: String,
|
||||
//! signing_string: String,
|
||||
//! ) -> Self::Future {
|
||||
//! match algorithm {
|
||||
//! Some(Algorithm::Hs2019) => (),
|
||||
//! _ => return ready(Err(MyError::Algorithm)),
|
||||
//! };
|
||||
//!
|
||||
//! if key_id != "my-key-id" {
|
||||
//! return ready(Err(MyError::Key));
|
||||
//! }
|
||||
//!
|
||||
//! let decoded = match base64::decode(&signature) {
|
||||
//! Ok(decoded) => decoded,
|
||||
//! Err(_) => return ready(Err(MyError::Decode)),
|
||||
//! };
|
||||
//!
|
||||
//! ready(Ok(decoded == signing_string.as_bytes()))
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! async fn index((_, sig_verified): (DigestVerified, SignatureVerified)) -> &'static str {
|
||||
//! println!("Signature verified for {}", sig_verified.key_id());
|
||||
//! "Eyyyyup"
|
||||
//! }
|
||||
//!
|
||||
//! #[actix_rt::main]
|
||||
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let config = Config::default();
|
||||
//!
|
||||
//! HttpServer::new(move || {
|
||||
//! App::new()
|
||||
//! .wrap(VerifyDigest::new(Sha256::new()).optional())
|
||||
//! .wrap(
|
||||
//! VerifySignature::new(MyVerify, config.clone())
|
||||
//! .authorization()
|
||||
//! .optional(),
|
||||
//! )
|
||||
//! .route("/", web::post().to(index))
|
||||
//! })
|
||||
//! .bind("127.0.0.1:8010")?
|
||||
//! .run()
|
||||
//! .await?;
|
||||
//!
|
||||
//! Ok(())
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Debug, thiserror::Error)]
|
||||
//! enum MyError {
|
||||
//! #[error("Failed to verify, {}", _0)]
|
||||
//! Verify(#[from] PrepareVerifyError),
|
||||
//!
|
||||
//! #[error("Unsupported algorithm")]
|
||||
//! Algorithm,
|
||||
//!
|
||||
//! #[error("Couldn't decode signature")]
|
||||
//! Decode,
|
||||
//!
|
||||
//! #[error("Invalid key")]
|
||||
//! Key,
|
||||
//! }
|
||||
//!
|
||||
//! impl ResponseError for MyError {
|
||||
//! fn status_code(&self) -> StatusCode {
|
||||
//! StatusCode::BAD_REQUEST
|
||||
//! }
|
||||
//!
|
||||
//! fn error_response(&self) -> HttpResponse {
|
||||
//! HttpResponse::BadRequest().finish()
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ### Use it in a client
|
||||
//! ```rust,ignore
|
||||
//! use actix_web::error::BlockingError;
|
||||
//! use awc::Client;
|
||||
//! use http_signature_normalization_actix::prelude::*;
|
||||
//! use sha2::{Digest, Sha256};
|
||||
//!
|
||||
//! #[actix_rt::main]
|
||||
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let config = Config::default();
|
||||
//! let digest = Sha256::new();
|
||||
//!
|
||||
//! let mut response = Client::default()
|
||||
//! .post("http://127.0.0.1:8010/")
|
||||
//! .header("User-Agent", "Actix Web")
|
||||
//! .set(actix_web::http::header::Date(SystemTime::now().into()))
|
||||
//! .signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
||||
//! println!("Signing String\n{}", s);
|
||||
//! Ok(base64::encode(s)) as Result<_, MyError>
|
||||
//! })
|
||||
//! .await?
|
||||
//! .send()
|
||||
//! .await
|
||||
//! .map_err(|e| {
|
||||
//! eprintln!("Error, {}", e);
|
||||
//! MyError::SendRequest
|
||||
//! })?;
|
||||
//!
|
||||
//! let body = response.body().await.map_err(|e| {
|
||||
//! eprintln!("Error, {}", e);
|
||||
//! MyError::Body
|
||||
//! })?;
|
||||
//!
|
||||
//! println!("{:?}", body);
|
||||
//! Ok(())
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Debug, thiserror::Error)]
|
||||
//! pub enum MyError {
|
||||
//! #[error("Failed to create signing string, {0}")]
|
||||
//! Convert(#[from] PrepareSignError),
|
||||
//!
|
||||
//! #[error("Failed to create header, {0}")]
|
||||
//! Header(#[from] InvalidHeaderValue),
|
||||
//!
|
||||
//! #[error("Failed to send request")]
|
||||
//! SendRequest,
|
||||
//!
|
||||
//! #[error("Failed to retrieve request body")]
|
||||
//! Body,
|
||||
//!
|
||||
//! #[error("Blocking operation was canceled")]
|
||||
//! Canceled,
|
||||
//! }
|
||||
//!
|
||||
//! impl From<BlockingError> for MyError {
|
||||
//! fn from(_: BlockingError) -> Self {
|
||||
//! MyError::Canceled,
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use actix_web::{
|
||||
error::BlockingError,
|
||||
http::{
|
||||
header::{HeaderMap, InvalidHeaderValue, ToStrError},
|
||||
uri::PathAndQuery,
|
||||
Method,
|
||||
},
|
||||
};
|
||||
use chrono::Duration;
|
||||
use std::{collections::BTreeMap, fmt::Display, future::Future, pin::Pin};
|
||||
|
||||
mod sign;
|
||||
|
||||
#[cfg(feature = "digest")]
|
||||
pub mod digest;
|
||||
|
||||
pub mod create;
|
||||
pub mod middleware;
|
||||
|
||||
pub use http_signature_normalization::RequiredError;
|
||||
|
||||
/// Useful types and traits for using this library in Actix Web
|
||||
pub mod prelude {
|
||||
pub use crate::{
|
||||
middleware::{SignatureVerified, VerifySignature},
|
||||
verify::{Algorithm, DeprecatedAlgorithm, Unverified},
|
||||
Config, PrepareSignError, PrepareVerifyError, RequiredError, Sign, SignatureVerify,
|
||||
};
|
||||
|
||||
#[cfg(feature = "digest")]
|
||||
pub use crate::digest::{
|
||||
middleware::{DigestVerified, VerifyDigest},
|
||||
DigestClient, DigestCreate, DigestPart, DigestVerify, SignExt,
|
||||
};
|
||||
|
||||
pub use actix_web::http::header::{InvalidHeaderValue, ToStrError};
|
||||
}
|
||||
|
||||
/// Types for Verifying an HTTP Signature
|
||||
pub mod verify {
|
||||
pub use http_signature_normalization::verify::{
|
||||
Algorithm, DeprecatedAlgorithm, ParseSignatureError, ParsedHeader, Unvalidated, Unverified,
|
||||
ValidateError,
|
||||
};
|
||||
}
|
||||
|
||||
use self::{
|
||||
create::Unsigned,
|
||||
verify::{Algorithm, Unverified},
|
||||
};
|
||||
|
||||
/// A trait for verifying signatures
|
||||
pub trait SignatureVerify {
|
||||
/// An error produced while attempting to verify the signature. This can be anything
|
||||
/// implementing ResponseError
|
||||
type Error: actix_web::ResponseError;
|
||||
|
||||
/// The future that resolves to the verification state of the signature
|
||||
type Future: Future<Output = Result<bool, Self::Error>>;
|
||||
|
||||
/// Given the algorithm, key_id, signature, and signing_string, produce a future that resulves
|
||||
/// to a the verification status
|
||||
fn signature_verify(
|
||||
&mut self,
|
||||
algorithm: Option<Algorithm>,
|
||||
key_id: String,
|
||||
signature: String,
|
||||
signing_string: String,
|
||||
) -> Self::Future;
|
||||
}
|
||||
|
||||
/// A trait implemented by the awc ClientRequest type to add an HTTP signature to the request
|
||||
pub trait Sign {
|
||||
/// Add an Authorization Signature to the request
|
||||
fn authorization_signature<F, E, K>(
|
||||
self,
|
||||
config: Config,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<BlockingError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
Self: Sized;
|
||||
|
||||
/// Add a Signature to the request
|
||||
fn signature<F, E, K>(
|
||||
self,
|
||||
config: Config,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<BlockingError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// Configuration for signing and verifying signatures
|
||||
///
|
||||
/// By default, the config is set up to create and verify signatures that expire after 10
|
||||
/// seconds, and use the `(created)` and `(expires)` fields that were introduced in draft 11
|
||||
pub struct Config {
|
||||
/// The inner config type
|
||||
config: http_signature_normalization::Config,
|
||||
|
||||
/// Whether to set the Host header
|
||||
set_host: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
/// An error when preparing to verify a request
|
||||
pub enum PrepareVerifyError {
|
||||
#[error("Header is missing")]
|
||||
/// Header is missing
|
||||
Missing,
|
||||
|
||||
#[error("Header is expired")]
|
||||
/// Header is expired
|
||||
Expired,
|
||||
|
||||
#[error("Couldn't parse required field, {0}")]
|
||||
/// Couldn't parse required field
|
||||
ParseField(&'static str),
|
||||
|
||||
#[error("Failed to read header, {0}")]
|
||||
/// An error converting the header to a string for validation
|
||||
Header(#[from] ToStrError),
|
||||
|
||||
#[error("{0}")]
|
||||
/// Required headers were missing from request
|
||||
Required(#[from] RequiredError),
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
/// An error when preparing to sign a request
|
||||
pub enum PrepareSignError {
|
||||
#[error("Failed to read header, {0}")]
|
||||
/// An error occurred when reading the request's headers
|
||||
Header(#[from] ToStrError),
|
||||
|
||||
#[error("{0}")]
|
||||
/// Some headers were marked as required, but are missing
|
||||
RequiredError(#[from] RequiredError),
|
||||
|
||||
#[error("No host provided for URL, {0}")]
|
||||
/// Missing host
|
||||
Host(String),
|
||||
}
|
||||
|
||||
impl From<http_signature_normalization::PrepareVerifyError> for PrepareVerifyError {
|
||||
fn from(e: http_signature_normalization::PrepareVerifyError) -> Self {
|
||||
use http_signature_normalization as hsn;
|
||||
|
||||
match e {
|
||||
hsn::PrepareVerifyError::Parse(parse_error) => {
|
||||
PrepareVerifyError::ParseField(parse_error.missing_field())
|
||||
}
|
||||
hsn::PrepareVerifyError::Validate(validate_error) => match validate_error {
|
||||
hsn::verify::ValidateError::Missing => PrepareVerifyError::Missing,
|
||||
hsn::verify::ValidateError::Expired => PrepareVerifyError::Expired,
|
||||
},
|
||||
hsn::PrepareVerifyError::Required(required_error) => {
|
||||
PrepareVerifyError::Required(required_error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Create a new Config with a default expiration of 10 seconds
|
||||
pub fn new() -> Self {
|
||||
Config::default()
|
||||
}
|
||||
|
||||
/// Since manually setting the Host header doesn't work so well in AWC, you can use this method
|
||||
/// to enable setting the Host header for signing requests without breaking client
|
||||
/// functionality
|
||||
pub fn set_host_header(self) -> Self {
|
||||
Config {
|
||||
config: self.config,
|
||||
set_host: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Enable mastodon compatibility
|
||||
///
|
||||
/// This is the same as disabling the use of `(created)` and `(expires)` signature fields,
|
||||
/// requiring the Date header, and requiring the Host header
|
||||
pub fn mastodon_compat(self) -> Self {
|
||||
Config {
|
||||
config: self.config.mastodon_compat(),
|
||||
set_host: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Require the Digest header be set
|
||||
///
|
||||
/// This is useful for POST, PUT, and PATCH requests, but doesn't make sense for GET or DELETE.
|
||||
pub fn require_digest(self) -> Self {
|
||||
Config {
|
||||
config: self.config.require_digest(),
|
||||
set_host: self.set_host,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opt out of using the (created) and (expires) fields introduced in draft 11
|
||||
///
|
||||
/// Note that by enabling this, the Date header becomes required on requests. This is to
|
||||
/// prevent replay attacks
|
||||
pub fn dont_use_created_field(self) -> Self {
|
||||
Config {
|
||||
config: self.config.dont_use_created_field(),
|
||||
set_host: self.set_host,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the expiration to a custom duration
|
||||
pub fn set_expiration(self, expires_after: Duration) -> Self {
|
||||
Config {
|
||||
config: self.config.set_expiration(expires_after),
|
||||
set_host: self.set_host,
|
||||
}
|
||||
}
|
||||
|
||||
/// Require a header on signed and verified requests
|
||||
pub fn require_header(self, header: &str) -> Self {
|
||||
Config {
|
||||
config: self.config.require_header(header),
|
||||
set_host: self.set_host,
|
||||
}
|
||||
}
|
||||
|
||||
/// Begin the process of singing a request
|
||||
pub fn begin_sign(
|
||||
&self,
|
||||
method: &Method,
|
||||
path_and_query: Option<&PathAndQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Unsigned, PrepareSignError> {
|
||||
let headers = headers
|
||||
.iter()
|
||||
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
|
||||
.collect::<Result<BTreeMap<_, _>, ToStrError>>()?;
|
||||
|
||||
let path_and_query = path_and_query
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or_else(|| "/".to_string());
|
||||
|
||||
let unsigned = self
|
||||
.config
|
||||
.begin_sign(&method.to_string(), &path_and_query, headers)?;
|
||||
|
||||
Ok(Unsigned { unsigned })
|
||||
}
|
||||
|
||||
/// Begin the proess of verifying a request
|
||||
pub fn begin_verify(
|
||||
&self,
|
||||
method: &Method,
|
||||
path_and_query: Option<&PathAndQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Unverified, PrepareVerifyError> {
|
||||
let headers = headers
|
||||
.iter()
|
||||
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
|
||||
.collect::<Result<BTreeMap<_, _>, ToStrError>>()?;
|
||||
|
||||
let path_and_query = path_and_query
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or_else(|| "/".to_string());
|
||||
|
||||
let unverified = self
|
||||
.config
|
||||
.begin_verify(&method.to_string(), &path_and_query, headers)?;
|
||||
|
||||
Ok(unverified)
|
||||
}
|
||||
}
|
|
@ -1,39 +0,0 @@
|
|||
[package]
|
||||
name = "http-signature-normalization-reqwest"
|
||||
description = "An HTTP Signatures library that leaves the signing to you"
|
||||
version = "0.2.0"
|
||||
authors = ["asonix <asonix@asonix.dog>"]
|
||||
license-file = "LICENSE"
|
||||
readme = "README.md"
|
||||
repository = "https://git.asonix.dog/Aardwolf/http-signature-normalization"
|
||||
keywords = ["http", "signatures", "digest", "reqwest"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[features]
|
||||
default = ["sha-2", "sha-3"]
|
||||
digest = ["base64", "tokio"]
|
||||
sha-2 = ["digest", "sha2"]
|
||||
sha-3 = ["digest", "sha3"]
|
||||
|
||||
[[example]]
|
||||
name = "client"
|
||||
required-features = ["sha-2"]
|
||||
|
||||
[dependencies]
|
||||
base64 = { version = "0.13", optional = true }
|
||||
bytes = "1"
|
||||
futures = "0.3.1"
|
||||
chrono = "0.4.10"
|
||||
http = "0.2.0"
|
||||
http-signature-normalization = { version = "0.5.1", path = ".." }
|
||||
reqwest = "0.11"
|
||||
sha2 = { version = "0.9", optional = true }
|
||||
sha3 = { version = "0.9", optional = true }
|
||||
thiserror = "1.0"
|
||||
tokio = { version = "1", default-features = false, features = ["rt"], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_env_logger = "0.4"
|
||||
tokio = { version = "1", default-features = false, features = ["rt-multi-thread", "macros"] }
|
||||
time = "0.2"
|
|
@ -1,417 +0,0 @@
|
|||
Http Signature Normalization
|
||||
Copyright Riley Trautman 2019
|
||||
|
||||
COOPERATIVE SOFTWARE LICENSE
|
||||
|
||||
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS
|
||||
COPYFARLEFT PUBLIC LICENSE ("LICENSE"). THE WORK IS PROTECTED BY
|
||||
COPYRIGHT AND ALL OTHER APPLICABLE LAWS. ANY USE OF THE WORK OTHER THAN
|
||||
AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY
|
||||
EXERCISING ANY RIGHTS TO THE WORK PROVIDED IN THIS LICENSE, YOU AGREE
|
||||
TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE
|
||||
MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
|
||||
CONTAINED HERE IN AS CONSIDERATION FOR ACCEPTING THE TERMS AND
|
||||
CONDITIONS OF THIS LICENSE AND FOR AGREEING TO BE BOUND BY THE TERMS
|
||||
AND CONDITIONS OF THIS LICENSE.
|
||||
|
||||
1. DEFINITIONS
|
||||
|
||||
a. "Adaptation" means a work based upon the Work, or upon the
|
||||
Work and other pre-existing works, such as a translation,
|
||||
adaptation, derivative work, arrangement of music or other
|
||||
alterations of a literary or artistic work, or phonogram or
|
||||
performance and includes cinematographic adaptations or any
|
||||
other form in which the Work may be recast, transformed, or
|
||||
adapted including in any form recognizably derived from the
|
||||
original, except that a work that constitutes a Collection will
|
||||
not be considered an Adaptation for the purpose of this License.
|
||||
For the avoidance of doubt, where the Work is a musical work,
|
||||
performance or phonogram, the synchronization of the Work in
|
||||
timed-relation with a moving image ("synching") will be
|
||||
considered an Adaptation for the purpose of this License.
|
||||
|
||||
b. "Collection" means a collection of literary or artistic
|
||||
works, such as encyclopedias and anthologies, or performances,
|
||||
phonograms or broadcasts, or other works or subject matter other
|
||||
than works listed in Section 1(f) below, which, by reason of the
|
||||
selection and arrangement of their contents, constitute
|
||||
intellectual creations, in which the Work is included in its
|
||||
entirety in unmodified form along with one or more other
|
||||
contributions, each constituting separate and independent works
|
||||
in themselves, which together are assembled into a collective
|
||||
whole. A work that constitutes a Collection will not be
|
||||
considered an Adaptation (as defined above) for the purposes of
|
||||
this License.
|
||||
|
||||
c. "Distribute" means to make available to the public the
|
||||
original and copies of the Work or Adaptation, as appropriate,
|
||||
through sale, gift or any other transfer of possession or
|
||||
ownership.
|
||||
|
||||
d. "Licensor" means the individual, individuals, entity or
|
||||
entities that offer(s) the Work under the terms of this License.
|
||||
|
||||
e. "Original Author" means, in the case of a literary or
|
||||
artistic work, the individual, individuals, entity or entities
|
||||
who created the Work or if no individual or entity can be
|
||||
identified, the publisher; and in addition (i) in the case of a
|
||||
performance the actors, singers, musicians, dancers, and other
|
||||
persons who act, sing, deliver, declaim, play in, interpret or
|
||||
otherwise perform literary or artistic works or expressions of
|
||||
folklore; (ii) in the case of a phonogram the producer being the
|
||||
person or legal entity who first fixes the sounds of a
|
||||
performance or other sounds; and, (iii) in the case of
|
||||
broadcasts, the organization that transmits the broadcast.
|
||||
|
||||
f. "Work" means the literary and/or artistic work offered under
|
||||
the terms of this License including without limitation any
|
||||
production in the literary, scientific and artistic domain,
|
||||
whatever may be the mode or form of its expression including
|
||||
digital form, such as a book, pamphlet and other writing; a
|
||||
lecture, address, sermon or other work of the same nature; a
|
||||
dramatic or dramatico-musical work; a choreographic work or
|
||||
entertainment in dumb show; a musical composition with or
|
||||
without words; a cinematographic work to which are assimilated
|
||||
works expressed by a process analogous to cinematography; a work
|
||||
of drawing, painting, architecture, sculpture, engraving or
|
||||
lithography; a photographic work to which are assimilated works
|
||||
expressed by a process analogous to photography; a work of
|
||||
applied art; an illustration, map, plan, sketch or
|
||||
three-dimensional work relative to geography, topography,
|
||||
architecture or science; a performance; a broadcast; a
|
||||
phonogram; a compilation of data to the extent it is protected
|
||||
as a copyrightable work; or a work performed by a variety or
|
||||
circus performer to the extent it is not otherwise considered a
|
||||
literary or artistic work.
|
||||
|
||||
g. "You" means an individual or entity exercising rights under
|
||||
this License who has not previously violated the terms of this
|
||||
License with respect to the Work, or who has received express
|
||||
permission from the Licensor to exercise rights under this
|
||||
License despite a previous violation.
|
||||
|
||||
h. "Publicly Perform" means to perform public recitations of the
|
||||
Work and to communicate to the public those public recitations,
|
||||
by any means or process, including by wire or wireless means or
|
||||
public digital performances; to make available to the public
|
||||
Works in such a way that members of the public may access these
|
||||
Works from a place and at a place individually chosen by them;
|
||||
to perform the Work to the public by any means or process and
|
||||
the communication to the public of the performances of the Work,
|
||||
including by public digital performance; to broadcast and
|
||||
rebroadcast the Work by any means including signs, sounds or
|
||||
images.
|
||||
|
||||
i. "Reproduce" means to make copies of the Work by any means
|
||||
including without limitation by sound or visual recordings and
|
||||
the right of fixation and reproducing fixations of the Work,
|
||||
including storage of a protected performance or phonogram in
|
||||
digital form or other electronic medium.
|
||||
|
||||
j. "Software" means any digital Work which, through use of a
|
||||
third-party piece of Software or through the direct usage of
|
||||
itself on a computer system, the memory of the computer is
|
||||
modified dynamically or semi-dynamically. "Software",
|
||||
secondly, processes or interprets information.
|
||||
|
||||
k. "Source Code" means the human-readable form of Software
|
||||
through which the Original Author and/or Distributor originally
|
||||
created, derived, and/or modified it.
|
||||
|
||||
l. "Web Service" means the use of a piece of Software to
|
||||
interpret or modify information that is subsequently and directly
|
||||
served to users over the Internet.
|
||||
|
||||
2. FAIR DEALING RIGHTS
|
||||
|
||||
Nothing in this License is intended to reduce, limit, or restrict any
|
||||
uses free from copyright or rights arising from limitations or
|
||||
exceptions that are provided for in connection with the copyright
|
||||
protection under copyright law or other applicable laws.
|
||||
|
||||
3. LICENSE GRANT
|
||||
|
||||
Subject to the terms and conditions of this License, Licensor hereby
|
||||
grants You a worldwide, royalty-free, non-exclusive, perpetual (for the
|
||||
duration of the applicable copyright) license to exercise the rights in
|
||||
the Work as stated below:
|
||||
|
||||
a. to Reproduce the Work, to incorporate the Work into one or
|
||||
more Collections, and to Reproduce the Work as incorporated in
|
||||
the Collections;
|
||||
|
||||
b. to create and Reproduce Adaptations provided that any such
|
||||
Adaptation, including any translation in any medium, takes
|
||||
reasonable steps to clearly label, demarcate or otherwise
|
||||
identify that changes were made to the original Work. For
|
||||
example, a translation could be marked "The original work was
|
||||
translated from English to Spanish," or a modification could
|
||||
indicate "The original work has been modified.";
|
||||
|
||||
c. to Distribute and Publicly Perform the Work including as
|
||||
incorporated in Collections; and,
|
||||
|
||||
d. to Distribute and Publicly Perform Adaptations. The above
|
||||
rights may be exercised in all media and formats whether now
|
||||
known or hereafter devised. The above rights include the right
|
||||
to make such modifications as are technically necessary to
|
||||
exercise the rights in other media and formats. Subject to
|
||||
Section 8(g), all rights not expressly granted by Licensor are
|
||||
hereby reserved, including but not limited to the rights set
|
||||
forth in Section 4(h).
|
||||
|
||||
4. RESTRICTIONS
|
||||
|
||||
The license granted in Section 3 above is expressly made subject to and
|
||||
limited by the following restrictions:
|
||||
|
||||
a. You may Distribute or Publicly Perform the Work only under
|
||||
the terms of this License. You must include a copy of, or the
|
||||
Uniform Resource Identifier (URI) for, this License with every
|
||||
copy of the Work You Distribute or Publicly Perform. You may not
|
||||
offer or impose any terms on the Work that restrict the terms of
|
||||
this License or the ability of the recipient of the Work to
|
||||
exercise the rights granted to that recipient under the terms of
|
||||
the License. You may not sublicense the Work. You must keep
|
||||
intact all notices that refer to this License and to the
|
||||
disclaimer of warranties with every copy of the Work You
|
||||
Distribute or Publicly Perform. When You Distribute or Publicly
|
||||
Perform the Work, You may not impose any effective technological
|
||||
measures on the Work that restrict the ability of a recipient of
|
||||
the Work from You to exercise the rights granted to that
|
||||
recipient under the terms of the License. This Section 4(a)
|
||||
applies to the Work as incorporated in a Collection, but this
|
||||
does not require the Collection apart from the Work itself to be
|
||||
made subject to the terms of this License. If You create a
|
||||
Collection, upon notice from any Licensor You must, to the
|
||||
extent practicable, remove from the Collection any credit as
|
||||
required by Section 4(f), as requested. If You create an
|
||||
Adaptation, upon notice from any Licensor You must, to the
|
||||
extent practicable, remove from the Adaptation any credit as
|
||||
required by Section 4(f), as requested.
|
||||
|
||||
b. Subject to the exception in Section 4(e), you may not
|
||||
exercise any of the rights granted to You in Section 3 above in
|
||||
any manner that is primarily intended for or directed toward
|
||||
commercial advantage or private monetary compensation. The
|
||||
exchange of the Work for other copyrighted works by means of
|
||||
digital file-sharing or otherwise shall not be considered to be
|
||||
intended for or directed toward commercial advantage or private
|
||||
monetary compensation, provided there is no payment of any
|
||||
monetary compensation in connection with the exchange of
|
||||
copyrighted works.
|
||||
|
||||
c. If the Work meets the definition of Software, You may exercise
|
||||
the rights granted in Section 3 only if You provide a copy of the
|
||||
corresponding Source Code from which the Work was derived in digital
|
||||
form, or You provide a URI for the corresponding Source Code of
|
||||
the Work, to any recipients upon request.
|
||||
|
||||
d. If the Work is used as or for a Web Service, You may exercise
|
||||
the rights granted in Section 3 only if You provide a copy of the
|
||||
corresponding Source Code from which the Work was derived in digital
|
||||
form, or You provide a URI for the corresponding Source Code to the
|
||||
Work, to any recipients of the data served or modified by the Web
|
||||
Service.
|
||||
|
||||
e. You may exercise the rights granted in Section 3 for
|
||||
commercial purposes only if you satisfy any of the following:
|
||||
|
||||
i. You are a worker-owned business or worker-owned
|
||||
collective; and
|
||||
ii. after tax, all financial gain, surplus, profits and
|
||||
benefits produced by the business or collective are
|
||||
distributed among the worker-owners
|
||||
iii. You are not using such rights on behalf of a business
|
||||
other than those specified in 4(e.i) and elaborated upon in
|
||||
4(e.ii), nor are using such rights as a proxy on behalf of a
|
||||
business with the intent to circumvent the aforementioned
|
||||
restrictions on such a business.
|
||||
|
||||
f. Any use by a business that is privately owned and managed,
|
||||
and that seeks to generate profit from the labor of employees
|
||||
paid by salary or other wages, is not permitted under this
|
||||
license.
|
||||
|
||||
g. If You Distribute, or Publicly Perform the Work or any
|
||||
Adaptations or Collections, You must, unless a request has been
|
||||
made pursuant to Section 4(a), keep intact all copyright notices
|
||||
for the Work and provide, reasonable to the medium or means You
|
||||
are utilizing: (i) the name of the Original Author (or
|
||||
pseudonym, if applicable) if supplied, and/or if the Original
|
||||
Author and/or Licensor designate another party or parties (e.g.,
|
||||
a sponsor institute, publishing entity, journal) for attribution
|
||||
("Attribution Parties") in Licensor!s copyright notice, terms of
|
||||
service or by other reasonable means, the name of such party or
|
||||
parties; (ii) the title of the Work if supplied; (iii) to the
|
||||
extent reasonably practicable, the URI, if any, that Licensor
|
||||
specifies to be associated with the Work, unless such URI does
|
||||
not refer to the copyright notice or licensing information for
|
||||
the Work; and, (iv) consistent with Section 3(b), in the case of
|
||||
an Adaptation, a credit identifying the use of the Work in the
|
||||
Adaptation (e.g., "French translation of the Work by Original
|
||||
Author," or "Screenplay based on original Work by Original
|
||||
Author"). The credit required by this Section 4(f) may be
|
||||
implemented in any reasonable manner; provided, however, that in
|
||||
the case of a Adaptation or Collection, at a minimum such credit
|
||||
will appear, if a credit for all contributing authors of the
|
||||
Adaptation or Collection appears, then as part of these credits
|
||||
and in a manner at least as prominent as the credits for the
|
||||
other contributing authors. For the avoidance of doubt, You may
|
||||
only use the credit required by this Section for the purpose of
|
||||
attribution in the manner set out above and, by exercising Your
|
||||
rights under this License, You may not implicitly or explicitly
|
||||
assert or imply any connection with, sponsorship or endorsement
|
||||
by the Original Author, Licensor and/or Attribution Parties, as
|
||||
appropriate, of You or Your use of the Work, without the
|
||||
separate, express prior written permission of the Original
|
||||
Author, Licensor and/or Attribution Parties.
|
||||
|
||||
h. For the avoidance of doubt:
|
||||
|
||||
i. Non-waivable Compulsory License Schemes. In those
|
||||
jurisdictions in which the right to collect royalties
|
||||
through any statutory or compulsory licensing scheme
|
||||
cannot be waived, the Licensor reserves the exclusive
|
||||
right to collect such royalties for any exercise by You of
|
||||
the rights granted under this License;
|
||||
|
||||
ii. Waivable Compulsory License Schemes. In those
|
||||
jurisdictions in which the right to collect royalties
|
||||
through any statutory or compulsory licensing scheme can
|
||||
be waived, the Licensor reserves the exclusive right to
|
||||
collect such royalties for any exercise by You of the
|
||||
rights granted under this License if Your exercise of such
|
||||
rights is for a purpose or use which is otherwise than
|
||||
noncommercial as permitted under Section 4(b) and
|
||||
otherwise waives the right to collect royalties through
|
||||
any statutory or compulsory licensing scheme; and,
|
||||
iii.Voluntary License Schemes. The Licensor reserves the
|
||||
right to collect royalties, whether individually or, in
|
||||
the event that the Licensor is a member of a collecting
|
||||
society that administers voluntary licensing schemes, via
|
||||
that society, from any exercise by You of the rights
|
||||
granted under this License that is for a purpose or use
|
||||
which is otherwise than noncommercial as permitted under
|
||||
Section 4(b).
|
||||
|
||||
i. Except as otherwise agreed in writing by the Licensor or as
|
||||
may be otherwise permitted by applicable law, if You Reproduce,
|
||||
Distribute or Publicly Perform the Work either by itself or as
|
||||
part of any Adaptations or Collections, You must not distort,
|
||||
mutilate, modify or take other derogatory action in relation to
|
||||
the Work which would be prejudicial to the Original Author's
|
||||
honor or reputation. Licensor agrees that in those jurisdictions
|
||||
(e.g. Japan), in which any exercise of the right granted in
|
||||
Section 3(b) of this License (the right to make Adaptations)
|
||||
would be deemed to be a distortion, mutilation, modification or
|
||||
other derogatory action prejudicial to the Original Author's
|
||||
honor and reputation, the Licensor will waive or not assert, as
|
||||
appropriate, this Section, to the fullest extent permitted by
|
||||
the applicable national law, to enable You to reasonably
|
||||
exercise Your right under Section 3(b) of this License (right to
|
||||
make Adaptations) but not otherwise.
|
||||
|
||||
5. REPRESENTATIONS, WARRANTIES AND DISCLAIMER
|
||||
|
||||
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
|
||||
OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
|
||||
KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
|
||||
INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
|
||||
LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF
|
||||
ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW
|
||||
THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO
|
||||
YOU.
|
||||
|
||||
6. LIMITATION ON LIABILITY
|
||||
|
||||
EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL
|
||||
LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF
|
||||
THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED
|
||||
OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
7. TERMINATION
|
||||
|
||||
a. This License and the rights granted hereunder will terminate
|
||||
automatically upon any breach by You of the terms of this
|
||||
License. Individuals or entities who have received Adaptations
|
||||
or Collections from You under this License, however, will not
|
||||
have their licenses terminated provided such individuals or
|
||||
entities remain in full compliance with those licenses. Sections
|
||||
1, 2, 5, 6, 7, and 8 will survive any termination of this
|
||||
License.
|
||||
|
||||
b. Subject to the above terms and conditions, the license
|
||||
granted here is perpetual (for the duration of the applicable
|
||||
copyright in the Work). Notwithstanding the above, Licensor
|
||||
reserves the right to release the Work under different license
|
||||
terms or to stop distributing the Work at any time; provided,
|
||||
however that any such election will not serve to withdraw this
|
||||
License (or any other license that has been, or is required to
|
||||
be, granted under the terms of this License), and this License
|
||||
will continue in full force and effect unless terminated as
|
||||
stated above.
|
||||
|
||||
8. MISCELLANEOUS
|
||||
|
||||
a. Each time You Distribute or Publicly Perform the Work or a
|
||||
Collection, the Licensor offers to the recipient a license to
|
||||
the Work on the same terms and conditions as the license granted
|
||||
to You under this License.
|
||||
|
||||
b. Each time You Distribute or Publicly Perform an Adaptation,
|
||||
Licensor offers to the recipient a license to the original Work
|
||||
on the same terms and conditions as the license granted to You
|
||||
under this License.
|
||||
|
||||
c. If the Work is classified as Software, each time You Distribute
|
||||
or Publicly Perform an Adaptation, Licensor offers to the recipient
|
||||
a copy and/or URI of the corresponding Source Code on the same
|
||||
terms and conditions as the license granted to You under this License.
|
||||
|
||||
d. If the Work is used as a Web Service, each time You Distribute
|
||||
or Publicly Perform an Adaptation, or serve data derived from the
|
||||
Software, the Licensor offers to any recipients of the data a copy
|
||||
and/or URI of the corresponding Source Code on the same terms and
|
||||
conditions as the license granted to You under this License.
|
||||
|
||||
e. If any provision of this License is invalid or unenforceable
|
||||
under applicable law, it shall not affect the validity or
|
||||
enforceability of the remainder of the terms of this License,
|
||||
and without further action by the parties to this agreement,
|
||||
such provision shall be reformed to the minimum extent necessary
|
||||
to make such provision valid and enforceable.
|
||||
|
||||
f. No term or provision of this License shall be deemed waived
|
||||
and no breach consented to unless such waiver or consent shall
|
||||
be in writing and signed by the party to be charged with such
|
||||
waiver or consent.
|
||||
|
||||
g. This License constitutes the entire agreement between the
|
||||
parties with respect to the Work licensed here. There are no
|
||||
understandings, agreements or representations with respect to
|
||||
the Work not specified here. Licensor shall not be bound by any
|
||||
additional provisions that may appear in any communication from
|
||||
You. This License may not be modified without the mutual written
|
||||
agreement of the Licensor and You.
|
||||
|
||||
h. The rights granted under, and the subject matter referenced,
|
||||
in this License were drafted utilizing the terminology of the
|
||||
Berne Convention for the Protection of Literary and Artistic
|
||||
Works (as amended on September 28, 1979), the Rome Convention of
|
||||
1961, the WIPO Copyright Treaty of 1996, the WIPO Performances
|
||||
and Phonograms Treaty of 1996 and the Universal Copyright
|
||||
Convention (as revised on July 24, 1971). These rights and
|
||||
subject matter take effect in the relevant jurisdiction in which
|
||||
the License terms are sought to be enforced according to the
|
||||
corresponding provisions of the implementation of those treaty
|
||||
provisions in the applicable national law. If the standard suite
|
||||
of rights granted under applicable copyright law includes
|
||||
additional rights not granted under this License, such
|
||||
additional rights are deemed to be included in the License; this
|
||||
License is not intended to restrict the license of any rights
|
||||
under applicable law.
|
||||
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
use http_signature_normalization_reqwest::prelude::*;
|
||||
use reqwest::{header::DATE, Client};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
async fn request(config: Config) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let digest = Sha256::new();
|
||||
|
||||
let response = Client::new()
|
||||
.post("http://127.0.0.1:8010/")
|
||||
.header("User-Agent", "Reqwest")
|
||||
.header("Accept", "text/plain")
|
||||
.header(
|
||||
DATE,
|
||||
OffsetDateTime::now_utc().format("%a, %d %b %Y %H:%M:%S GMT"),
|
||||
)
|
||||
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
||||
println!("Signing String\n{}", s);
|
||||
Ok(base64::encode(s)) as Result<_, MyError>
|
||||
})
|
||||
.await?;
|
||||
|
||||
let body = response.bytes().await.map_err(MyError::Body)?;
|
||||
|
||||
println!("{:?}", body);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
std::env::set_var("RUST_LOG", "info");
|
||||
pretty_env_logger::init();
|
||||
|
||||
let config = Config::default().require_header("accept");
|
||||
|
||||
request(config.clone()).await?;
|
||||
request(config.mastodon_compat()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MyError {
|
||||
#[error("Failed to create signing string, {0}")]
|
||||
Convert(#[from] SignError),
|
||||
|
||||
#[error("Failed to send request")]
|
||||
SendRequest(#[from] reqwest::Error),
|
||||
|
||||
#[error("Failed to retrieve request body")]
|
||||
Body(reqwest::Error),
|
||||
}
|
|
@ -1,122 +0,0 @@
|
|||
use crate::{Config, Sign, SignError};
|
||||
use reqwest::{Body, RequestBuilder};
|
||||
use std::{fmt::Display, future::Future, pin::Pin};
|
||||
|
||||
#[cfg(feature = "sha-2")]
|
||||
mod sha2;
|
||||
#[cfg(feature = "sha-3")]
|
||||
mod sha3;
|
||||
|
||||
/// A trait for creating digests of an array of bytes
|
||||
pub trait DigestCreate {
|
||||
/// The name of the digest algorithm
|
||||
const NAME: &'static str;
|
||||
|
||||
/// Compute the digest of the input bytes
|
||||
fn compute(&mut self, input: &[u8]) -> String;
|
||||
}
|
||||
|
||||
/// Extend the Sign trait with support for adding Digest Headers to the request
|
||||
///
|
||||
/// It generates HTTP Signatures after the Digest header has been added, in order to have
|
||||
/// verification that the body has not been tampered with, or that the request can't be replayed by
|
||||
/// a malicious entity
|
||||
pub trait SignExt: Sign {
|
||||
fn authorization_signature_with_digest<F, E, K, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<reqwest::Response, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
Self: Sized;
|
||||
|
||||
fn signature_with_digest<F, E, K, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<reqwest::Response, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
impl SignExt for RequestBuilder {
|
||||
fn authorization_signature_with_digest<F, E, K, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
key_id: K,
|
||||
mut digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<reqwest::Response, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
||||
let digest = digest.compute(v.as_ref());
|
||||
(v, digest)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| SignError::Canceled)?;
|
||||
|
||||
let c = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.authorization_signature(&config, key_id, f)?;
|
||||
|
||||
c.body(v).send().await.map_err(E::from)
|
||||
})
|
||||
}
|
||||
|
||||
fn signature_with_digest<F, E, K, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
key_id: K,
|
||||
mut digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<reqwest::Response, E>>>>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
||||
let digest = digest.compute(v.as_ref());
|
||||
(v, digest)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| SignError::Canceled)?;
|
||||
|
||||
let c = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.signature(&config, key_id, f)?;
|
||||
|
||||
c.body(v).send().await.map_err(E::from)
|
||||
})
|
||||
}
|
||||
}
|
|
@ -1,216 +0,0 @@
|
|||
use chrono::Duration;
|
||||
use http_signature_normalization::create::Signed;
|
||||
use reqwest::{
|
||||
header::{InvalidHeaderValue, ToStrError},
|
||||
Request, RequestBuilder,
|
||||
};
|
||||
use std::fmt::Display;
|
||||
|
||||
pub use http_signature_normalization::RequiredError;
|
||||
|
||||
#[cfg(feature = "digest")]
|
||||
pub mod digest;
|
||||
|
||||
pub mod prelude {
|
||||
pub use crate::{Config, Sign, SignError};
|
||||
|
||||
#[cfg(feature = "digest")]
|
||||
pub use crate::digest::{DigestCreate, SignExt};
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// Configuration for signing and verifying signatures
|
||||
///
|
||||
/// By default, the config is set up to create and verify signatures that expire after 10 seconds,
|
||||
/// and use the `(created)` and `(expires)` fields that were introduced in draft 11
|
||||
pub struct Config {
|
||||
/// The inner config type
|
||||
config: http_signature_normalization::Config,
|
||||
|
||||
/// Whether to set the Host header
|
||||
set_host: bool,
|
||||
}
|
||||
|
||||
/// A trait implemented by the reqwest RequestBuilder type to add an HTTP Signature to the request
|
||||
pub trait Sign {
|
||||
/// Add an Authorization Signature to the request
|
||||
fn authorization_signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Self, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnOnce(&str) -> Result<String, E>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display;
|
||||
|
||||
/// Add a Signature to the request
|
||||
fn signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Self, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnOnce(&str) -> Result<String, E>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display;
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SignError {
|
||||
#[error("Failed to read header, {0}")]
|
||||
/// An error occurred when reading the request's headers
|
||||
Header(#[from] ToStrError),
|
||||
|
||||
#[error("Failed to write header, {0}")]
|
||||
/// An error occured when adding a new header
|
||||
NewHeader(#[from] InvalidHeaderValue),
|
||||
|
||||
#[error("{0}")]
|
||||
/// Some headers were marked as required, but are missing
|
||||
RequiredError(#[from] RequiredError),
|
||||
|
||||
#[error("No host provided for URL, {0}")]
|
||||
/// Missing host
|
||||
Host(String),
|
||||
|
||||
#[error("Cannot sign request with body already present")]
|
||||
BodyPresent,
|
||||
|
||||
#[error("Panic in spawn blocking")]
|
||||
Canceled,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// This method can be used to include the Host header in the HTTP Signature without
|
||||
/// interfering with Reqwest's built-in Host mechanisms
|
||||
pub fn set_host_header(self) -> Self {
|
||||
Config {
|
||||
config: self.config,
|
||||
set_host: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Enable mastodon compatibility
|
||||
///
|
||||
/// This is the same as disabling the use of `(created)` and `(expires)` signature fields,
|
||||
/// requiring the Date header, and requiring the Host header
|
||||
pub fn mastodon_compat(self) -> Self {
|
||||
Config {
|
||||
config: self.config.mastodon_compat(),
|
||||
set_host: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Require the Digest header be set
|
||||
///
|
||||
/// This is useful for POST, PUT, and PATCH requests, but doesn't make sense for GET or DELETE.
|
||||
pub fn require_digest(self) -> Self {
|
||||
Config {
|
||||
config: self.config.require_digest(),
|
||||
set_host: self.set_host,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opt out of using the (created) and (expires) fields introduced in draft 11
|
||||
///
|
||||
/// Note that by enabling this, the Date header becomes required on requests. This is to
|
||||
/// prevent replay attacks
|
||||
pub fn dont_use_created_field(self) -> Self {
|
||||
Config {
|
||||
config: self.config.dont_use_created_field(),
|
||||
set_host: self.set_host,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the expiration to a custom duration
|
||||
pub fn set_expiration(self, expiries_after: Duration) -> Self {
|
||||
Config {
|
||||
config: self.config.set_expiration(expiries_after),
|
||||
set_host: self.set_host,
|
||||
}
|
||||
}
|
||||
|
||||
/// Require a header on signed requests
|
||||
pub fn require_header(self, header: &str) -> Self {
|
||||
Config {
|
||||
config: self.config.require_header(header),
|
||||
set_host: self.set_host,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sign for RequestBuilder {
|
||||
fn authorization_signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Self, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display,
|
||||
{
|
||||
if let Some(builder) = self.try_clone() {
|
||||
let request = builder.build()?;
|
||||
let signed = prepare(&request, config, key_id, f)?;
|
||||
|
||||
let auth_header = signed.authorization_header();
|
||||
return Ok(self.header("Authorization", auth_header));
|
||||
}
|
||||
|
||||
Err(SignError::BodyPresent.into())
|
||||
}
|
||||
|
||||
fn signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Self, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display,
|
||||
{
|
||||
if let Some(builder) = self.try_clone() {
|
||||
let request = builder.build()?;
|
||||
let signed = prepare(&request, config, key_id, f)?;
|
||||
|
||||
let sig_header = signed.signature_header();
|
||||
return Ok(self.header("Signature", sig_header));
|
||||
}
|
||||
|
||||
Err(SignError::BodyPresent.into())
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare<F, E, K>(req: &Request, config: &Config, key_id: K, f: F) -> Result<Signed, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E>,
|
||||
E: From<SignError>,
|
||||
K: Display,
|
||||
{
|
||||
let mut bt = std::collections::BTreeMap::new();
|
||||
for (k, v) in req.headers().iter() {
|
||||
bt.insert(
|
||||
k.as_str().to_owned(),
|
||||
v.to_str().map_err(SignError::from)?.to_owned(),
|
||||
);
|
||||
}
|
||||
if config.set_host {
|
||||
let header_string = req
|
||||
.url()
|
||||
.host()
|
||||
.ok_or_else(|| SignError::Host(req.url().to_string()))?
|
||||
.to_string();
|
||||
|
||||
let header_string = match req.url().port() {
|
||||
None | Some(443) | Some(80) => header_string,
|
||||
Some(port) => format!("{}:{}", header_string, port),
|
||||
};
|
||||
|
||||
bt.insert("Host".to_string(), header_string);
|
||||
}
|
||||
let path_and_query = if let Some(query) = req.url().query() {
|
||||
format!("{}?{}", req.url().path(), query)
|
||||
} else {
|
||||
req.url().path().to_string()
|
||||
};
|
||||
let unsigned = config
|
||||
.config
|
||||
.begin_sign(req.method().as_str(), &path_and_query, bt)
|
||||
.map_err(SignError::from)?;
|
||||
|
||||
let signed = unsigned.sign(key_id.to_string(), f)?;
|
||||
Ok(signed)
|
||||
}
|
|
@ -1,9 +1,9 @@
|
|||
[package]
|
||||
name = "http-signature-normalization-http"
|
||||
description = "An HTTP Signatures library that leaves the signing to you"
|
||||
version = "0.3.0"
|
||||
version = "0.5.0"
|
||||
authors = ["asonix <asonix@asonix.dog>"]
|
||||
license-file = "../LICENSE"
|
||||
license = "AGPL-3.0"
|
||||
readme = "../README.md"
|
||||
repository = "https://git.asonix.dog/Aardwolf/http-signature-normalization"
|
||||
keywords = ["http", "signatures", "digest"]
|
||||
|
@ -13,4 +13,4 @@ edition = "2018"
|
|||
|
||||
[dependencies]
|
||||
http = "0.2"
|
||||
http-signature-normalization = { version = "0.5.0", path = ".." }
|
||||
http-signature-normalization = { version = "0.7.0", path = ".." }
|
661
http/LICENSE
Normal file
661
http/LICENSE
Normal file
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
|
@ -57,6 +57,15 @@ pub enum PrepareVerifyError {
|
|||
Header(ToStrError),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// Errors produced when preparing to sign an Http Signature
|
||||
pub enum PrepareSignError {
|
||||
/// There was an error in the underlying library
|
||||
Required(http_signature_normalization::RequiredError),
|
||||
/// There was an error producing a String from the HeaderValue
|
||||
Header(ToStrError),
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Begin the process of signing a request
|
||||
///
|
||||
|
@ -66,7 +75,7 @@ impl Config {
|
|||
method: &Method,
|
||||
path_and_query: Option<&PathAndQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Unsigned, ToStrError> {
|
||||
) -> Result<Unsigned, PrepareSignError> {
|
||||
let headers = headers
|
||||
.iter()
|
||||
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
|
||||
|
@ -74,11 +83,11 @@ impl Config {
|
|||
|
||||
let path_and_query = path_and_query
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or(String::from("/"));
|
||||
.unwrap_or_else(|| String::from("/"));
|
||||
|
||||
let unsigned = self
|
||||
.config
|
||||
.begin_sign(&method.to_string(), &path_and_query, headers);
|
||||
.begin_sign(method.as_ref(), &path_and_query, headers)?;
|
||||
|
||||
Ok(Unsigned { unsigned })
|
||||
}
|
||||
|
@ -99,11 +108,11 @@ impl Config {
|
|||
|
||||
let path_and_query = path_and_query
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or(String::from("/"));
|
||||
.unwrap_or_else(|| String::from("/"));
|
||||
|
||||
let unverified = self
|
||||
.config
|
||||
.begin_verify(&method.to_string(), &path_and_query, headers)?;
|
||||
.begin_verify(method.as_ref(), &path_and_query, headers)?;
|
||||
|
||||
Ok(unverified)
|
||||
}
|
||||
|
@ -118,14 +127,16 @@ impl fmt::Display for PrepareVerifyError {
|
|||
}
|
||||
}
|
||||
|
||||
impl Error for PrepareVerifyError {
|
||||
fn description(&self) -> &str {
|
||||
impl fmt::Display for PrepareSignError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
PrepareVerifyError::Sig(ref e) => e.description(),
|
||||
PrepareVerifyError::Header(ref e) => e.description(),
|
||||
PrepareSignError::Required(ref e) => write!(f, "Required error, {}", e),
|
||||
PrepareSignError::Header(ref e) => write!(f, "Header error, {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for PrepareVerifyError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match *self {
|
||||
PrepareVerifyError::Sig(ref e) => Some(e),
|
||||
|
@ -134,6 +145,15 @@ impl Error for PrepareVerifyError {
|
|||
}
|
||||
}
|
||||
|
||||
impl Error for PrepareSignError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match *self {
|
||||
PrepareSignError::Required(ref e) => Some(e),
|
||||
PrepareSignError::Header(ref e) => Some(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<http_signature_normalization::PrepareVerifyError> for PrepareVerifyError {
|
||||
fn from(e: http_signature_normalization::PrepareVerifyError) -> Self {
|
||||
PrepareVerifyError::Sig(e)
|
||||
|
@ -145,3 +165,15 @@ impl From<ToStrError> for PrepareVerifyError {
|
|||
PrepareVerifyError::Header(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<http_signature_normalization::RequiredError> for PrepareSignError {
|
||||
fn from(e: http_signature_normalization::RequiredError) -> Self {
|
||||
PrepareSignError::Required(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ToStrError> for PrepareSignError {
|
||||
fn from(e: ToStrError) -> Self {
|
||||
PrepareSignError::Header(e)
|
||||
}
|
||||
}
|
46
reqwest/Cargo.toml
Normal file
46
reqwest/Cargo.toml
Normal file
|
@ -0,0 +1,46 @@
|
|||
[package]
|
||||
name = "http-signature-normalization-reqwest"
|
||||
description = "An HTTP Signatures library that leaves the signing to you"
|
||||
version = "0.12.0"
|
||||
authors = ["asonix <asonix@asonix.dog>"]
|
||||
license = "AGPL-3.0"
|
||||
readme = "README.md"
|
||||
repository = "https://git.asonix.dog/Aardwolf/http-signature-normalization"
|
||||
keywords = ["http", "signatures", "digest", "reqwest"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[features]
|
||||
default = ["sha-2", "default-spawner"]
|
||||
middleware = ["dep:reqwest-middleware"]
|
||||
default-spawner = ["dep:tokio"]
|
||||
digest = ["dep:base64"]
|
||||
ring = ["digest", "dep:ring"]
|
||||
sha-2 = ["digest", "dep:sha2"]
|
||||
sha-3 = ["digest", "dep:sha3"]
|
||||
|
||||
[[example]]
|
||||
name = "client"
|
||||
required-features = ["default-spawner", "ring"]
|
||||
|
||||
[dependencies]
|
||||
async-trait = "0.1.71"
|
||||
base64 = { version = "0.22", optional = true }
|
||||
http-signature-normalization = { version = "0.7.0", path = ".." }
|
||||
httpdate = "1.0.2"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json"] }
|
||||
reqwest-middleware = { version = "0.3.0", optional = true }
|
||||
ring = { version = "0.17.5", optional = true }
|
||||
sha2 = { version = "0.10", optional = true }
|
||||
sha3 = { version = "0.10", optional = true }
|
||||
thiserror = "1.0"
|
||||
tokio = { version = "1", default-features = false, features = [
|
||||
"rt",
|
||||
], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_env_logger = "0.5"
|
||||
tokio = { version = "1", default-features = false, features = [
|
||||
"rt-multi-thread",
|
||||
"macros",
|
||||
] }
|
661
reqwest/LICENSE
Normal file
661
reqwest/LICENSE
Normal file
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
|
@ -63,20 +63,13 @@ pub enum MyError {
|
|||
```
|
||||
|
||||
### Contributing
|
||||
Unless otherwise stated, all contributions to this project will be licensed under the CSL with
|
||||
the exceptions listed in the License section of this file.
|
||||
Feel free to open issues for anything you find an issue with. Please note that any contributed code will be licensed under the AGPLv3.
|
||||
|
||||
### License
|
||||
This work is licensed under the Cooperative Software License. This is not a Free Software
|
||||
License, but may be considered a "source-available License." For most hobbyists, self-employed
|
||||
developers, worker-owned companies, and cooperatives, this software can be used in most
|
||||
projects so long as this software is distributed under the terms of the CSL. For more
|
||||
information, see the provided LICENSE file. If none exists, the license can be found online
|
||||
[here](https://lynnesbian.space/csl/). If you are a free software project and wish to use this
|
||||
software under the terms of the GNU Affero General Public License, please contact me at
|
||||
[asonix@asonix.dog](mailto:asonix@asonix.dog) and we can sort that out. If you wish to use this
|
||||
project under any other license, especially in proprietary software, the answer is likely no.
|
||||
Copyright © 2022 Riley Trautman
|
||||
|
||||
Http Signature Normalization Reqwest is currently licensed under the AGPL to the Lemmy project, found
|
||||
at [github.com/LemmyNet/lemmy](https://github.com/LemmyNet/lemmy)
|
||||
HTTP Signature Normalization Reqwest is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
HTTP Signature Normalization Reqwest is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. This file is part of HTTP Signature Normalization Reqwest.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with HTTP Signature Normalization Reqwest. If not, see [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/).
|
53
reqwest/examples/client.rs
Normal file
53
reqwest/examples/client.rs
Normal file
|
@ -0,0 +1,53 @@
|
|||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use http_signature_normalization_reqwest::{digest::ring::Sha256, prelude::*};
|
||||
use reqwest::{
|
||||
header::{ACCEPT, USER_AGENT},
|
||||
Client,
|
||||
};
|
||||
|
||||
async fn request(config: Config) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let digest = Sha256::new();
|
||||
|
||||
let client = Client::new();
|
||||
|
||||
let request = client
|
||||
.post("http://127.0.0.1:8010/")
|
||||
.header(USER_AGENT, "Reqwest")
|
||||
.header(ACCEPT, "text/plain")
|
||||
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
||||
println!("Signing String\n{}", s);
|
||||
Ok(STANDARD.encode(s)) as Result<_, MyError>
|
||||
})
|
||||
.await?;
|
||||
|
||||
let body = client.execute(request).await?.bytes().await?;
|
||||
|
||||
println!("{:?}", body);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
std::env::set_var("RUST_LOG", "info");
|
||||
pretty_env_logger::init();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let config = Config::default().require_header("accept");
|
||||
|
||||
request(config.clone()).await?;
|
||||
request(config.mastodon_compat()).await
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MyError {
|
||||
#[error("Failed to create signing string, {0}")]
|
||||
Convert(#[from] SignError),
|
||||
|
||||
#[error("Failed to send request")]
|
||||
SendRequest(#[from] reqwest::Error),
|
||||
|
||||
#[error("Failed to retrieve request body")]
|
||||
Body(reqwest::Error),
|
||||
}
|
217
reqwest/src/digest/mod.rs
Normal file
217
reqwest/src/digest/mod.rs
Normal file
|
@ -0,0 +1,217 @@
|
|||
use crate::{Config, Sign, SignError, Spawn};
|
||||
use reqwest::{Body, Request, RequestBuilder};
|
||||
use std::fmt::Display;
|
||||
|
||||
#[cfg(feature = "ring")]
|
||||
pub mod ring;
|
||||
#[cfg(feature = "sha-2")]
|
||||
mod sha2;
|
||||
#[cfg(feature = "sha-3")]
|
||||
mod sha3;
|
||||
|
||||
/// A trait for creating digests of an array of bytes
|
||||
pub trait DigestCreate {
|
||||
/// The name of the digest algorithm
|
||||
const NAME: &'static str;
|
||||
|
||||
/// Compute the digest of the input bytes
|
||||
fn compute(&mut self, input: &[u8]) -> String;
|
||||
}
|
||||
|
||||
/// Extend the Sign trait with support for adding Digest Headers to the request
|
||||
///
|
||||
/// It generates HTTP Signatures after the Digest header has been added, in order to have
|
||||
/// verification that the body has not been tampered with, or that the request can't be replayed by
|
||||
/// a malicious entity
|
||||
#[async_trait::async_trait]
|
||||
pub trait SignExt: Sign {
|
||||
async fn authorization_signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
S: Spawn + Send + Sync,
|
||||
Self: Sized;
|
||||
|
||||
async fn signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
S: Spawn + Send + Sync,
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SignExt for RequestBuilder {
|
||||
async fn authorization_signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
mut digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
S: Spawn + Send + Sync,
|
||||
{
|
||||
let (v, digest) = config
|
||||
.spawner
|
||||
.spawn_blocking(move || {
|
||||
let digest = digest.compute(v.as_ref());
|
||||
(v, digest)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| SignError::Canceled)?;
|
||||
|
||||
let mut req = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.authorization_signature(&config, key_id, f)
|
||||
.await?;
|
||||
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
|
||||
Ok(req)
|
||||
}
|
||||
|
||||
async fn signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
mut digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
S: Spawn + Send + Sync,
|
||||
{
|
||||
let (v, digest) = config
|
||||
.spawner
|
||||
.spawn_blocking(move || {
|
||||
let digest = digest.compute(v.as_ref());
|
||||
(v, digest)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| SignError::Canceled)?;
|
||||
|
||||
let mut req = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.signature(&config, key_id, f)
|
||||
.await?;
|
||||
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
|
||||
Ok(req)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "middleware")]
|
||||
mod middleware {
|
||||
use super::{Config, DigestCreate, Sign, SignError, SignExt, Spawn};
|
||||
use reqwest::{Body, Request};
|
||||
use reqwest_middleware::RequestBuilder;
|
||||
use std::fmt::Display;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SignExt for RequestBuilder {
|
||||
async fn authorization_signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
mut digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
S: Spawn + Send + Sync,
|
||||
Self: Sized,
|
||||
{
|
||||
let (v, digest) = config
|
||||
.spawner
|
||||
.spawn_blocking(move || {
|
||||
let digest = digest.compute(v.as_ref());
|
||||
(v, digest)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| SignError::Canceled)?;
|
||||
|
||||
let mut req = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.authorization_signature(&config, key_id, f)
|
||||
.await?;
|
||||
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
|
||||
Ok(req)
|
||||
}
|
||||
|
||||
async fn signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
mut digest: D,
|
||||
v: V,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
S: Spawn + Send + Sync,
|
||||
Self: Sized,
|
||||
{
|
||||
let (v, digest) = config
|
||||
.spawner
|
||||
.spawn_blocking(move || {
|
||||
let digest = digest.compute(v.as_ref());
|
||||
(v, digest)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| SignError::Canceled)?;
|
||||
|
||||
let mut req = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.signature(&config, key_id, f)
|
||||
.await?;
|
||||
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
|
||||
Ok(req)
|
||||
}
|
||||
}
|
||||
}
|
113
reqwest/src/digest/ring.rs
Normal file
113
reqwest/src/digest/ring.rs
Normal file
|
@ -0,0 +1,113 @@
|
|||
//! Types for creating digests with the `ring` cryptography library
|
||||
|
||||
use super::DigestCreate;
|
||||
|
||||
/// A Sha256 digest backed by ring
|
||||
#[derive(Clone)]
|
||||
pub struct Sha256 {
|
||||
ctx: ring::digest::Context,
|
||||
}
|
||||
|
||||
/// A Sha384 digest backed by ring
|
||||
#[derive(Clone)]
|
||||
pub struct Sha384 {
|
||||
ctx: ring::digest::Context,
|
||||
}
|
||||
|
||||
/// A Sha512 digest backed by ring
|
||||
#[derive(Clone)]
|
||||
pub struct Sha512 {
|
||||
ctx: ring::digest::Context,
|
||||
}
|
||||
|
||||
impl Sha256 {
|
||||
/// Create a new empty digest
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Extract the context
|
||||
pub fn into_inner(self) -> ring::digest::Context {
|
||||
self.ctx
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Sha256 {
|
||||
fn default() -> Self {
|
||||
Sha256 {
|
||||
ctx: ring::digest::Context::new(&ring::digest::SHA256),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sha384 {
|
||||
/// Create a new empty digest
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Extract the context
|
||||
pub fn into_inner(self) -> ring::digest::Context {
|
||||
self.ctx
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Sha384 {
|
||||
fn default() -> Self {
|
||||
Sha384 {
|
||||
ctx: ring::digest::Context::new(&ring::digest::SHA384),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sha512 {
|
||||
/// Create a new empty digest
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Extract the context
|
||||
pub fn into_inner(self) -> ring::digest::Context {
|
||||
self.ctx
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Sha512 {
|
||||
fn default() -> Self {
|
||||
Sha512 {
|
||||
ctx: ring::digest::Context::new(&ring::digest::SHA512),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create(mut context: ring::digest::Context, input: &[u8]) -> String {
|
||||
use base64::prelude::*;
|
||||
|
||||
context.update(input);
|
||||
let digest = context.finish();
|
||||
BASE64_STANDARD.encode(digest.as_ref())
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha256 {
|
||||
const NAME: &'static str = "SHA-256";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self.ctx.clone(), input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha384 {
|
||||
const NAME: &'static str = "SHA-384";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self.ctx.clone(), input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha512 {
|
||||
const NAME: &'static str = "SHA-512";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self.ctx.clone(), input)
|
||||
}
|
||||
}
|
|
@ -1,10 +1,14 @@
|
|||
use sha2::{Sha224, Sha256, Sha384, Sha512, Sha512Trunc224, Sha512Trunc256};
|
||||
use base64::prelude::*;
|
||||
use sha2::{Sha224, Sha256, Sha384, Sha512};
|
||||
|
||||
use super::DigestCreate;
|
||||
|
||||
fn create(digest: &mut impl sha2::Digest, input: &[u8]) -> String {
|
||||
digest.update(input);
|
||||
base64::encode(&digest.finalize_reset())
|
||||
fn create<D: sha2::Digest + sha2::digest::FixedOutputReset>(
|
||||
digest: &mut D,
|
||||
input: &[u8],
|
||||
) -> String {
|
||||
sha2::Digest::update(digest, input);
|
||||
BASE64_STANDARD.encode(&digest.finalize_reset())
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha224 {
|
||||
|
@ -38,19 +42,3 @@ impl DigestCreate for Sha512 {
|
|||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha512Trunc224 {
|
||||
const NAME: &'static str = "SHA-512-224";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha512Trunc256 {
|
||||
const NAME: &'static str = "SHA-512-256";
|
||||
|
||||
fn compute(&mut self, input: &[u8]) -> String {
|
||||
create(self, input)
|
||||
}
|
||||
}
|
|
@ -1,3 +1,4 @@
|
|||
use base64::prelude::*;
|
||||
use sha3::{
|
||||
Keccak224, Keccak256, Keccak256Full, Keccak384, Keccak512, Sha3_224, Sha3_256, Sha3_384,
|
||||
Sha3_512,
|
||||
|
@ -5,9 +6,12 @@ use sha3::{
|
|||
|
||||
use super::DigestCreate;
|
||||
|
||||
fn create(digest: &mut impl sha3::Digest, input: &[u8]) -> String {
|
||||
digest.update(input);
|
||||
base64::encode(&digest.finalize_reset())
|
||||
fn create<D: sha3::Digest + sha3::digest::FixedOutputReset>(
|
||||
digest: &mut D,
|
||||
input: &[u8],
|
||||
) -> String {
|
||||
sha3::Digest::update(digest, input);
|
||||
BASE64_STANDARD.encode(&digest.finalize_reset())
|
||||
}
|
||||
|
||||
impl DigestCreate for Sha3_224 {
|
456
reqwest/src/lib.rs
Normal file
456
reqwest/src/lib.rs
Normal file
|
@ -0,0 +1,456 @@
|
|||
use http_signature_normalization::create::Signed;
|
||||
use httpdate::HttpDate;
|
||||
use reqwest::{
|
||||
header::{InvalidHeaderValue, ToStrError},
|
||||
Request, RequestBuilder,
|
||||
};
|
||||
use std::{
|
||||
convert::TryInto,
|
||||
fmt::Display,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
pub use http_signature_normalization::RequiredError;
|
||||
|
||||
#[cfg(feature = "digest")]
|
||||
pub mod digest;
|
||||
|
||||
pub mod prelude {
|
||||
pub use crate::{Config, Sign, SignError};
|
||||
|
||||
#[cfg(feature = "default-spawner")]
|
||||
pub use crate::default_spawner::DefaultSpawner;
|
||||
|
||||
#[cfg(feature = "digest")]
|
||||
pub use crate::digest::{DigestCreate, SignExt};
|
||||
}
|
||||
|
||||
#[cfg(feature = "default-spawner")]
|
||||
pub use default_spawner::DefaultSpawner;
|
||||
|
||||
#[cfg(feature = "default-spawner")]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// Configuration for signing and verifying signatures
|
||||
///
|
||||
/// By default, the config is set up to create and verify signatures that expire after 10 seconds,
|
||||
/// and use the `(created)` and `(expires)` fields that were introduced in draft 11
|
||||
pub struct Config<Spawner = DefaultSpawner> {
|
||||
/// The inner config type
|
||||
config: http_signature_normalization::Config,
|
||||
|
||||
/// Whether to set the Host header
|
||||
set_host: bool,
|
||||
|
||||
/// Whether to set the Date header
|
||||
set_date: bool,
|
||||
|
||||
/// How to spawn blocking tasks
|
||||
spawner: Spawner,
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "default-spawner"))]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// Configuration for signing and verifying signatures
|
||||
///
|
||||
/// By default, the config is set up to create and verify signatures that expire after 10 seconds,
|
||||
/// and use the `(created)` and `(expires)` fields that were introduced in draft 11
|
||||
pub struct Config<Spawner> {
|
||||
/// The inner config type
|
||||
config: http_signature_normalization::Config,
|
||||
|
||||
/// Whether to set the Host header
|
||||
set_host: bool,
|
||||
|
||||
/// Whether to set the Date header
|
||||
set_date: bool,
|
||||
|
||||
/// How to spawn blocking tasks
|
||||
spawner: Spawner,
|
||||
}
|
||||
|
||||
#[cfg(feature = "default-spawner")]
|
||||
mod default_spawner {
|
||||
use super::{Canceled, Config, Spawn};
|
||||
|
||||
impl Config<DefaultSpawner> {
|
||||
/// Create a new config with the default spawner
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A default implementation of Spawner for spawning blocking operations
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct DefaultSpawner;
|
||||
|
||||
/// The future returned by DefaultSpawner when spawning blocking operations on the tokio
|
||||
/// blocking threadpool
|
||||
pub struct DefaultSpawnerFuture<Out> {
|
||||
inner: tokio::task::JoinHandle<Out>,
|
||||
}
|
||||
|
||||
impl Spawn for DefaultSpawner {
|
||||
type Future<T> = DefaultSpawnerFuture<T> where T: Send;
|
||||
|
||||
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
||||
where
|
||||
Func: FnOnce() -> Out + Send + 'static,
|
||||
Out: Send + 'static,
|
||||
{
|
||||
DefaultSpawnerFuture {
|
||||
inner: tokio::task::spawn_blocking(func),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Out> std::future::Future for DefaultSpawnerFuture<Out> {
|
||||
type Output = Result<Out, Canceled>;
|
||||
|
||||
fn poll(
|
||||
mut self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Self::Output> {
|
||||
let res = std::task::ready!(std::pin::Pin::new(&mut self.inner).poll(cx));
|
||||
|
||||
std::task::Poll::Ready(res.map_err(|_| Canceled))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An error that indicates a blocking operation panicked and cannot return a response
|
||||
#[derive(Debug)]
|
||||
pub struct Canceled;
|
||||
|
||||
impl std::fmt::Display for Canceled {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Operation was canceled")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Canceled {}
|
||||
|
||||
/// A trait dictating how to spawn a future onto a blocking threadpool. By default,
|
||||
/// http-signature-normalization-actix will use tokio's built-in blocking threadpool, but this
|
||||
/// can be customized
|
||||
pub trait Spawn {
|
||||
/// The future type returned by spawn_blocking
|
||||
type Future<T>: std::future::Future<Output = Result<T, Canceled>> + Send
|
||||
where
|
||||
T: Send;
|
||||
|
||||
/// Spawn the blocking function onto the threadpool
|
||||
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
||||
where
|
||||
Func: FnOnce() -> Out + Send + 'static,
|
||||
Out: Send + 'static;
|
||||
}
|
||||
|
||||
/// A trait implemented by the reqwest RequestBuilder type to add an HTTP Signature to the request
|
||||
#[async_trait::async_trait]
|
||||
pub trait Sign {
|
||||
/// Add an Authorization Signature to the request
|
||||
async fn authorization_signature<F, E, K, S>(
|
||||
self,
|
||||
config: &Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send,
|
||||
S: Spawn + Send + Sync;
|
||||
|
||||
/// Add a Signature to the request
|
||||
async fn signature<F, E, K, S>(self, config: &Config<S>, key_id: K, f: F) -> Result<Request, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send,
|
||||
S: Spawn + Send + Sync;
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SignError {
|
||||
#[error("Failed to read header, {0}")]
|
||||
/// An error occurred when reading the request's headers
|
||||
Header(#[from] ToStrError),
|
||||
|
||||
#[error("Failed to write header, {0}")]
|
||||
/// An error occured when adding a new header
|
||||
NewHeader(#[from] InvalidHeaderValue),
|
||||
|
||||
#[error("{0}")]
|
||||
/// Some headers were marked as required, but are missing
|
||||
RequiredError(#[from] RequiredError),
|
||||
|
||||
#[error("No host provided for URL, {0}")]
|
||||
/// Missing host
|
||||
Host(String),
|
||||
|
||||
#[error("Cannot sign request with body already present")]
|
||||
BodyPresent,
|
||||
|
||||
#[error("Panic in spawn blocking")]
|
||||
Canceled,
|
||||
}
|
||||
|
||||
impl<Spawner> Config<Spawner> {
|
||||
/// Create a new config with the provided spawner
|
||||
pub fn new_with_spawner(spawner: Spawner) -> Self {
|
||||
Config {
|
||||
config: Default::default(),
|
||||
set_host: Default::default(),
|
||||
set_date: Default::default(),
|
||||
spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// This method can be used to include the Host header in the HTTP Signature without
|
||||
/// interfering with Reqwest's built-in Host mechanisms
|
||||
pub fn set_host_header(self) -> Self {
|
||||
Config {
|
||||
config: self.config,
|
||||
set_host: true,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Enable mastodon compatibility
|
||||
///
|
||||
/// This is the same as disabling the use of `(created)` and `(expires)` signature fields,
|
||||
/// requiring the Date header, and requiring the Host header
|
||||
pub fn mastodon_compat(self) -> Self {
|
||||
Config {
|
||||
config: self.config.mastodon_compat(),
|
||||
set_host: true,
|
||||
set_date: true,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Require the Digest header be set
|
||||
///
|
||||
/// This is useful for POST, PUT, and PATCH requests, but doesn't make sense for GET or DELETE.
|
||||
pub fn require_digest(self) -> Self {
|
||||
Config {
|
||||
config: self.config.require_digest(),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opt out of using the (created) and (expires) fields introduced in draft 11
|
||||
///
|
||||
/// Note that by enabling this, the Date header becomes required on requests. This is to
|
||||
/// prevent replay attacks
|
||||
pub fn dont_use_created_field(self) -> Self {
|
||||
Config {
|
||||
config: self.config.dont_use_created_field(),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the expiration to a custom duration
|
||||
pub fn set_expiration(self, expiries_after: Duration) -> Self {
|
||||
Config {
|
||||
config: self.config.set_expiration(expiries_after),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Require a header on signed requests
|
||||
pub fn require_header(self, header: &str) -> Self {
|
||||
Config {
|
||||
config: self.config.require_header(header),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_spawner<NewSpawner: Spawn>(self, spawner: NewSpawner) -> Config<NewSpawner> {
|
||||
Config {
|
||||
config: self.config,
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Sign for RequestBuilder {
|
||||
async fn authorization_signature<F, E, K, S>(
|
||||
self,
|
||||
config: &Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send,
|
||||
S: Spawn + Send + Sync,
|
||||
{
|
||||
let mut request = self.build()?;
|
||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||
|
||||
let auth_header = signed.authorization_header();
|
||||
request.headers_mut().insert(
|
||||
"Authorization",
|
||||
auth_header.parse().map_err(SignError::NewHeader)?,
|
||||
);
|
||||
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
async fn signature<F, E, K, S>(self, config: &Config<S>, key_id: K, f: F) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send,
|
||||
S: Spawn + Send + Sync,
|
||||
{
|
||||
let mut request = self.build()?;
|
||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||
|
||||
let sig_header = signed.signature_header();
|
||||
|
||||
request.headers_mut().insert(
|
||||
"Signature",
|
||||
sig_header.parse().map_err(SignError::NewHeader)?,
|
||||
);
|
||||
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
|
||||
async fn prepare<F, E, K, S>(
|
||||
req: &mut Request,
|
||||
config: &Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Result<Signed, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + Send + 'static,
|
||||
K: Display + Send,
|
||||
S: Spawn,
|
||||
{
|
||||
if config.set_date && !req.headers().contains_key("date") {
|
||||
req.headers_mut().insert(
|
||||
"date",
|
||||
HttpDate::from(SystemTime::now())
|
||||
.to_string()
|
||||
.try_into()
|
||||
.map_err(SignError::from)?,
|
||||
);
|
||||
}
|
||||
let mut bt = std::collections::BTreeMap::new();
|
||||
for (k, v) in req.headers().iter() {
|
||||
bt.insert(
|
||||
k.as_str().to_owned(),
|
||||
v.to_str().map_err(SignError::from)?.to_owned(),
|
||||
);
|
||||
}
|
||||
if config.set_host {
|
||||
let header_string = req
|
||||
.url()
|
||||
.host()
|
||||
.ok_or_else(|| SignError::Host(req.url().to_string()))?
|
||||
.to_string();
|
||||
|
||||
let header_string = match req.url().port() {
|
||||
None | Some(443) | Some(80) => header_string,
|
||||
Some(port) => format!("{}:{}", header_string, port),
|
||||
};
|
||||
|
||||
bt.insert("Host".to_string(), header_string);
|
||||
}
|
||||
let path_and_query = if let Some(query) = req.url().query() {
|
||||
format!("{}?{}", req.url().path(), query)
|
||||
} else {
|
||||
req.url().path().to_string()
|
||||
};
|
||||
let unsigned = config
|
||||
.config
|
||||
.begin_sign(req.method().as_str(), &path_and_query, bt)
|
||||
.map_err(SignError::from)?;
|
||||
|
||||
let key_string = key_id.to_string();
|
||||
let signed = config
|
||||
.spawner
|
||||
.spawn_blocking(move || unsigned.sign(key_string, f))
|
||||
.await
|
||||
.map_err(|_| SignError::Canceled)??;
|
||||
Ok(signed)
|
||||
}
|
||||
|
||||
#[cfg(feature = "middleware")]
|
||||
mod middleware {
|
||||
use super::{prepare, Config, Sign, SignError, Spawn};
|
||||
use reqwest::Request;
|
||||
use reqwest_middleware::RequestBuilder;
|
||||
use std::fmt::Display;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Sign for RequestBuilder {
|
||||
async fn authorization_signature<F, E, K, S>(
|
||||
self,
|
||||
config: &Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send,
|
||||
S: Spawn + Send + Sync,
|
||||
{
|
||||
let mut request = self.build()?;
|
||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||
|
||||
let auth_header = signed.authorization_header();
|
||||
request.headers_mut().insert(
|
||||
"Authorization",
|
||||
auth_header.parse().map_err(SignError::NewHeader)?,
|
||||
);
|
||||
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
async fn signature<F, E, K, S>(
|
||||
self,
|
||||
config: &Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send,
|
||||
S: Spawn + Send + Sync,
|
||||
{
|
||||
let mut request = self.build()?;
|
||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||
|
||||
let sig_header = signed.signature_header();
|
||||
|
||||
request.headers_mut().insert(
|
||||
"Signature",
|
||||
sig_header.parse().map_err(SignError::NewHeader)?,
|
||||
);
|
||||
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,10 +1,9 @@
|
|||
//! Types and logic for creating signature and authorization headers
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use crate::{
|
||||
ALGORITHM_FIELD, ALGORITHM_VALUE, CREATED_FIELD, EXPIRES_FIELD, HEADERS_FIELD, KEY_ID_FIELD,
|
||||
SIGNATURE_FIELD,
|
||||
unix_timestamp, ALGORITHM_FIELD, ALGORITHM_VALUE, CREATED_FIELD, EXPIRES_FIELD, HEADERS_FIELD,
|
||||
KEY_ID_FIELD, SIGNATURE_FIELD,
|
||||
};
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[derive(Debug)]
|
||||
/// The signed stage of creating a signature
|
||||
|
@ -13,8 +12,8 @@ use crate::{
|
|||
pub struct Signed {
|
||||
signature: String,
|
||||
sig_headers: Vec<String>,
|
||||
created: Option<DateTime<Utc>>,
|
||||
expires: Option<DateTime<Utc>>,
|
||||
created: Option<SystemTime>,
|
||||
expires: Option<SystemTime>,
|
||||
key_id: String,
|
||||
}
|
||||
|
||||
|
@ -26,8 +25,8 @@ pub struct Signed {
|
|||
pub struct Unsigned {
|
||||
pub(crate) signing_string: String,
|
||||
pub(crate) sig_headers: Vec<String>,
|
||||
pub(crate) created: Option<DateTime<Utc>>,
|
||||
pub(crate) expires: Option<DateTime<Utc>>,
|
||||
pub(crate) created: Option<SystemTime>,
|
||||
pub(crate) expires: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl Signed {
|
||||
|
@ -51,8 +50,8 @@ impl Signed {
|
|||
vec![
|
||||
(KEY_ID_FIELD, self.key_id),
|
||||
(ALGORITHM_FIELD, ALGORITHM_VALUE.to_owned()),
|
||||
(CREATED_FIELD, created.timestamp().to_string()),
|
||||
(EXPIRES_FIELD, expires.timestamp().to_string()),
|
||||
(CREATED_FIELD, unix_timestamp(created).to_string()),
|
||||
(EXPIRES_FIELD, unix_timestamp(expires).to_string()),
|
||||
(HEADERS_FIELD, self.sig_headers.join(" ")),
|
||||
(SIGNATURE_FIELD, self.signature),
|
||||
]
|
||||
|
|
117
src/lib.rs
117
src/lib.rs
|
@ -10,12 +10,11 @@
|
|||
//! Http Signature Normalization is a minimal-dependency crate for producing HTTP Signatures with user-provided signing and verification. The API is simple; there's a series of steps for creation and verification with types that ensure reasonable usage.
|
||||
//!
|
||||
//! ```rust
|
||||
//! use chrono::Duration;
|
||||
//! use http_signature_normalization::Config;
|
||||
//! use std::collections::BTreeMap;
|
||||
//! use std::{collections::BTreeMap, time::Duration};
|
||||
//!
|
||||
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let config = Config::default().set_expiration(Duration::seconds(5));
|
||||
//! let config = Config::default().set_expiration(Duration::from_secs(5));
|
||||
//!
|
||||
//! let headers = BTreeMap::new();
|
||||
//!
|
||||
|
@ -42,8 +41,11 @@
|
|||
//! }
|
||||
//! ```
|
||||
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashSet},
|
||||
num::ParseIntError,
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
pub mod create;
|
||||
pub mod verify;
|
||||
|
@ -73,32 +75,72 @@ const SIGNATURE_FIELD: &str = "signature";
|
|||
pub struct Config {
|
||||
expires_after: Duration,
|
||||
use_created_field: bool,
|
||||
required_headers: HashSet<String>,
|
||||
required_headers: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[derive(Debug)]
|
||||
/// Error preparing a header for validation
|
||||
///
|
||||
/// This could be due to a missing header, and unparsable header, or an expired header
|
||||
pub enum PrepareVerifyError {
|
||||
#[error("{0}")]
|
||||
/// Error validating the header
|
||||
Validate(#[from] ValidateError),
|
||||
Validate(ValidateError),
|
||||
|
||||
#[error("{0}")]
|
||||
/// Error parsing the header
|
||||
Parse(#[from] ParseSignatureError),
|
||||
Parse(ParseSignatureError),
|
||||
|
||||
#[error("{0}")]
|
||||
/// Missing required headers
|
||||
Required(#[from] RequiredError),
|
||||
Required(RequiredError),
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Missing required headers {0:?}")]
|
||||
impl std::fmt::Display for PrepareVerifyError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Validate(ref e) => std::fmt::Display::fmt(e, f),
|
||||
Self::Parse(ref e) => std::fmt::Display::fmt(e, f),
|
||||
Self::Required(ref e) => std::fmt::Display::fmt(e, f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PrepareVerifyError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::Validate(ref e) => Some(e),
|
||||
Self::Parse(ref e) => Some(e),
|
||||
Self::Required(ref e) => Some(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ValidateError> for PrepareVerifyError {
|
||||
fn from(e: ValidateError) -> Self {
|
||||
Self::Validate(e)
|
||||
}
|
||||
}
|
||||
impl From<ParseSignatureError> for PrepareVerifyError {
|
||||
fn from(e: ParseSignatureError) -> Self {
|
||||
Self::Parse(e)
|
||||
}
|
||||
}
|
||||
impl From<RequiredError> for PrepareVerifyError {
|
||||
fn from(e: RequiredError) -> Self {
|
||||
Self::Required(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// Failed to build a signing string due to missing required headers
|
||||
pub struct RequiredError(HashSet<String>);
|
||||
|
||||
impl std::fmt::Display for RequiredError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Missing required headers {:?}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RequiredError {}
|
||||
|
||||
impl RequiredError {
|
||||
/// Retrieve the missing headers from the error
|
||||
pub fn headers(&self) -> &HashSet<String> {
|
||||
|
@ -113,8 +155,12 @@ impl RequiredError {
|
|||
|
||||
impl Config {
|
||||
/// Create a new Config with a default expiration of 10 seconds
|
||||
pub fn new() -> Self {
|
||||
Config::default()
|
||||
pub const fn new() -> Self {
|
||||
Config {
|
||||
expires_after: Duration::from_secs(10),
|
||||
use_created_field: true,
|
||||
required_headers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Enable mastodon compatibility
|
||||
|
@ -142,14 +188,14 @@ impl Config {
|
|||
}
|
||||
|
||||
/// Set the expiration to a custom duration
|
||||
pub fn set_expiration(mut self, expires_after: Duration) -> Self {
|
||||
pub const fn set_expiration(mut self, expires_after: Duration) -> Self {
|
||||
self.expires_after = expires_after;
|
||||
self
|
||||
}
|
||||
|
||||
/// Mark a header as required
|
||||
pub fn require_header(mut self, header: &str) -> Self {
|
||||
self.required_headers.insert(header.to_lowercase());
|
||||
self.required_headers.push(header.to_lowercase());
|
||||
self
|
||||
}
|
||||
|
||||
|
@ -169,7 +215,7 @@ impl Config {
|
|||
let sig_headers = self.build_headers_list(&headers);
|
||||
|
||||
let (created, expires) = if self.use_created_field {
|
||||
let created = Utc::now();
|
||||
let created = SystemTime::now();
|
||||
let expires = created + self.expires_after;
|
||||
|
||||
(Some(created), Some(expires))
|
||||
|
@ -184,7 +230,7 @@ impl Config {
|
|||
expires,
|
||||
&sig_headers,
|
||||
&mut headers,
|
||||
self.required_headers.clone(),
|
||||
self.required_headers.iter().cloned().collect(),
|
||||
)?;
|
||||
|
||||
Ok(Unsigned {
|
||||
|
@ -195,7 +241,7 @@ impl Config {
|
|||
})
|
||||
}
|
||||
|
||||
/// Perform the neccessary operations to produce and [`Unerified`] type, which can be used to
|
||||
/// Perform the neccessary operations to produce and [`Unverified`] type, which can be used to
|
||||
/// verify the header
|
||||
pub fn begin_verify(
|
||||
&self,
|
||||
|
@ -218,7 +264,7 @@ impl Config {
|
|||
method,
|
||||
path_and_query,
|
||||
&mut headers,
|
||||
self.required_headers.clone(),
|
||||
self.required_headers.iter().cloned().collect(),
|
||||
)?;
|
||||
|
||||
Ok(unvalidated.validate(self.expires_after)?)
|
||||
|
@ -246,8 +292,8 @@ impl Config {
|
|||
fn build_signing_string(
|
||||
method: &str,
|
||||
path_and_query: &str,
|
||||
created: Option<DateTime<Utc>>,
|
||||
expires: Option<DateTime<Utc>>,
|
||||
created: Option<SystemTime>,
|
||||
expires: Option<SystemTime>,
|
||||
sig_headers: &[String],
|
||||
btm: &mut BTreeMap<String, String>,
|
||||
mut required_headers: HashSet<String>,
|
||||
|
@ -256,10 +302,10 @@ fn build_signing_string(
|
|||
|
||||
btm.insert(REQUEST_TARGET.to_owned(), request_target);
|
||||
if let Some(created) = created {
|
||||
btm.insert(CREATED.to_owned(), created.timestamp().to_string());
|
||||
btm.insert(CREATED.to_owned(), unix_timestamp(created).to_string());
|
||||
}
|
||||
if let Some(expires) = expires {
|
||||
btm.insert(EXPIRES.to_owned(), expires.timestamp().to_string());
|
||||
btm.insert(EXPIRES.to_owned(), unix_timestamp(expires).to_string());
|
||||
}
|
||||
|
||||
let signing_string = sig_headers
|
||||
|
@ -283,14 +329,21 @@ fn build_signing_string(
|
|||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config {
|
||||
expires_after: Duration::seconds(10),
|
||||
use_created_field: true,
|
||||
required_headers: HashSet::new(),
|
||||
}
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn unix_timestamp(time: SystemTime) -> u64 {
|
||||
time.duration_since(UNIX_EPOCH)
|
||||
.expect("UNIX_EPOCH is never in the future")
|
||||
.as_secs()
|
||||
}
|
||||
|
||||
fn parse_unix_timestamp(s: &str) -> Result<SystemTime, ParseIntError> {
|
||||
let u: u64 = s.parse()?;
|
||||
Ok(UNIX_EPOCH + Duration::from_secs(u))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Config;
|
||||
|
|
129
src/verify.rs
129
src/verify.rs
|
@ -1,15 +1,15 @@
|
|||
//! Types and methods to verify a signature or authorization header
|
||||
use chrono::{DateTime, Duration, TimeZone, Utc};
|
||||
use crate::{
|
||||
build_signing_string, parse_unix_timestamp, RequiredError, ALGORITHM_FIELD, CREATED,
|
||||
CREATED_FIELD, EXPIRES_FIELD, HEADERS_FIELD, KEY_ID_FIELD, SIGNATURE_FIELD,
|
||||
};
|
||||
use httpdate::HttpDate;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap, HashSet},
|
||||
error::Error,
|
||||
fmt,
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
build_signing_string, RequiredError, ALGORITHM_FIELD, CREATED, CREATED_FIELD, EXPIRES_FIELD,
|
||||
HEADERS_FIELD, KEY_ID_FIELD, SIGNATURE_FIELD,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
|
@ -33,9 +33,9 @@ pub struct Unvalidated {
|
|||
pub(crate) key_id: String,
|
||||
pub(crate) signature: String,
|
||||
pub(crate) algorithm: Option<Algorithm>,
|
||||
pub(crate) created: Option<DateTime<Utc>>,
|
||||
pub(crate) expires: Option<DateTime<Utc>>,
|
||||
pub(crate) parsed_at: DateTime<Utc>,
|
||||
pub(crate) created: Option<SystemTime>,
|
||||
pub(crate) expires: Option<SystemTime>,
|
||||
pub(crate) parsed_at: SystemTime,
|
||||
pub(crate) date: Option<String>,
|
||||
pub(crate) signing_string: String,
|
||||
}
|
||||
|
@ -47,9 +47,9 @@ pub struct ParsedHeader {
|
|||
key_id: String,
|
||||
headers: Vec<String>,
|
||||
algorithm: Option<Algorithm>,
|
||||
created: Option<DateTime<Utc>>,
|
||||
expires: Option<DateTime<Utc>>,
|
||||
parsed_at: DateTime<Utc>,
|
||||
created: Option<SystemTime>,
|
||||
expires: Option<SystemTime>,
|
||||
parsed_at: SystemTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
|
@ -105,13 +105,35 @@ pub enum Algorithm {
|
|||
Unknown(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
/// Indicator of which date field was checked for an expired error
|
||||
pub enum ExpiredField {
|
||||
/// (expires) pseudo-header
|
||||
Expires,
|
||||
|
||||
/// (created) pseudo-header
|
||||
Created,
|
||||
|
||||
/// Date header
|
||||
Date,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
/// Kinds of errors for validating a request
|
||||
pub enum ValidateError {
|
||||
/// The Authorization or Signature header is not present
|
||||
Missing,
|
||||
/// The request's `created` or `expires` field indicates it is too old to be valid
|
||||
Expired,
|
||||
Expired {
|
||||
/// Which field did the date come from
|
||||
field: ExpiredField,
|
||||
|
||||
/// When did the signature expire
|
||||
expires: SystemTime,
|
||||
|
||||
/// When was the signature checked
|
||||
checked: SystemTime,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
@ -180,20 +202,32 @@ impl Unvalidated {
|
|||
pub fn validate(self, expires_after: Duration) -> Result<Unverified, ValidateError> {
|
||||
if let Some(expires) = self.expires {
|
||||
if expires < self.parsed_at {
|
||||
return Err(ValidateError::Expired);
|
||||
return Err(ValidateError::Expired {
|
||||
field: ExpiredField::Expires,
|
||||
expires,
|
||||
checked: self.parsed_at,
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(created) = self.created {
|
||||
if created + expires_after < self.parsed_at {
|
||||
return Err(ValidateError::Expired);
|
||||
return Err(ValidateError::Expired {
|
||||
field: ExpiredField::Created,
|
||||
expires: created + expires_after,
|
||||
checked: self.parsed_at,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(date) = self.date {
|
||||
if let Ok(datetime) = DateTime::parse_from_rfc2822(&date) {
|
||||
let datetime: DateTime<Utc> = datetime.into();
|
||||
if datetime + expires_after < self.parsed_at {
|
||||
return Err(ValidateError::Expired);
|
||||
if let Ok(datetime) = date.parse::<HttpDate>() {
|
||||
let date = SystemTime::from(datetime);
|
||||
if date + expires_after < self.parsed_at {
|
||||
return Err(ValidateError::Expired {
|
||||
field: ExpiredField::Date,
|
||||
expires: date + expires_after,
|
||||
checked: self.parsed_at,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -274,7 +308,7 @@ impl FromStr for ParsedHeader {
|
|||
algorithm: hm.remove(ALGORITHM_FIELD).map(Algorithm::from),
|
||||
created: parse_time(&mut hm, CREATED_FIELD)?,
|
||||
expires: parse_time(&mut hm, EXPIRES_FIELD)?,
|
||||
parsed_at: Utc::now(),
|
||||
parsed_at: SystemTime::now(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -282,12 +316,10 @@ impl FromStr for ParsedHeader {
|
|||
fn parse_time(
|
||||
hm: &mut HashMap<String, String>,
|
||||
key: &'static str,
|
||||
) -> Result<Option<DateTime<Utc>>, ParseSignatureError> {
|
||||
let r = hm.remove(key).map(|s| {
|
||||
s.parse()
|
||||
.map(|timestamp| Utc.timestamp(timestamp, 0))
|
||||
.map_err(|_| ParseSignatureError(key))
|
||||
});
|
||||
) -> Result<Option<SystemTime>, ParseSignatureError> {
|
||||
let r = hm
|
||||
.remove(key)
|
||||
.map(|s| parse_unix_timestamp(&s).map_err(|_| ParseSignatureError(key)));
|
||||
|
||||
match r {
|
||||
Some(Ok(t)) => Ok(Some(t)),
|
||||
|
@ -372,34 +404,47 @@ impl Error for ParseSignatureError {
|
|||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ExpiredField {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Expires => write!(f, "expires pseudo-header"),
|
||||
Self::Created => write!(f, "created pseudo-header"),
|
||||
Self::Date => write!(f, "Date header"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ValidateError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
ValidateError::Missing => write!(f, "Http Signature is missing"),
|
||||
ValidateError::Expired => write!(f, "Http Signature is expired"),
|
||||
ValidateError::Expired {
|
||||
field,
|
||||
expires,
|
||||
checked,
|
||||
} => write!(
|
||||
f,
|
||||
"Http Signature is expired, checked {}, checked at {}, expired at {}",
|
||||
field,
|
||||
httpdate::fmt_http_date(checked),
|
||||
httpdate::fmt_http_date(expires)
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ValidateError {
|
||||
fn description(&self) -> &'static str {
|
||||
match *self {
|
||||
ValidateError::Missing => "Http Signature is missing",
|
||||
ValidateError::Expired => "Http Signature is expired",
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Error for ValidateError {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
|
||||
use super::ParsedHeader;
|
||||
use crate::unix_timestamp;
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[test]
|
||||
fn parses_header_succesfully_1() {
|
||||
let time1 = Utc::now().timestamp();
|
||||
let time2 = Utc::now().timestamp();
|
||||
let time1 = unix_timestamp(SystemTime::now());
|
||||
let time2 = unix_timestamp(SystemTime::now());
|
||||
|
||||
let h = format!(
|
||||
r#"Signature keyId="my-key-id",algorithm="hs2019",created="{}",expires="{}",headers="(request-target) (created) (expires) date content-type",signature="blah blah blah""#,
|
||||
|
@ -411,8 +456,8 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn parses_header_succesfully_2() {
|
||||
let time1 = Utc::now().timestamp();
|
||||
let time2 = Utc::now().timestamp();
|
||||
let time1 = unix_timestamp(SystemTime::now());
|
||||
let time2 = unix_timestamp(SystemTime::now());
|
||||
|
||||
let h = format!(
|
||||
r#"Signature keyId="my-key-id",algorithm="rsa-sha256",created="{}",expires="{}",signature="blah blah blah""#,
|
||||
|
@ -424,7 +469,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn parses_header_succesfully_3() {
|
||||
let time1 = Utc::now().timestamp();
|
||||
let time1 = unix_timestamp(SystemTime::now());
|
||||
|
||||
let h = format!(
|
||||
r#"Signature keyId="my-key-id",algorithm="rsa-sha256",created="{}",headers="(request-target) (created) date content-type",signature="blah blah blah""#,
|
||||
|
|
661
warp/LICENSE
Normal file
661
warp/LICENSE
Normal file
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
Loading…
Reference in a new issue