diff --git a/.reuse/dep5 b/.reuse/dep5 new file mode 100644 index 0000000..b8bb6be --- /dev/null +++ b/.reuse/dep5 @@ -0,0 +1,15 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: SOP-Java +Upstream-Contact: Paul Schaub +Source: https://pgpainless.org + +# Sample paragraph, commented out: +# +# Files: src/* +# Copyright: $YEAR $NAME <$CONTACT> +# License: ... + +# Gradle build tool +Files: gradle* +Copyright: 2015 the original author or authors. +License: Apache-2.0 diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..137069b --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer 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, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/settings.gradle b/settings.gradle index 3bf81fd..a636bb0 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + rootProject.name = 'VKS-Java' include 'vks-java' \ No newline at end of file diff --git a/vks-java/build.gradle b/vks-java/build.gradle index b363175..57c150a 100644 --- a/vks-java/build.gradle +++ b/vks-java/build.gradle @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + plugins { id 'java-library' } @@ -21,9 +25,11 @@ dependencies { // Lombok compileOnly 'org.projectlombok:lombok:1.18.22' annotationProcessor 'org.projectlombok:lombok:1.18.22' - testCompileOnly 'org.projectlombok:lombok:1.18.22' testAnnotationProcessor 'org.projectlombok:lombok:1.18.22' + + // JSON + implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.1' } test { diff --git a/vks-java/src/main/java/pgp/vks/client/Get.java b/vks-java/src/main/java/pgp/vks/client/Get.java index df50b10..55a665f 100644 --- a/vks-java/src/main/java/pgp/vks/client/Get.java +++ b/vks-java/src/main/java/pgp/vks/client/Get.java @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + package pgp.vks.client; import pgp.vks.client.exception.CertNotFoundException; @@ -7,10 +11,39 @@ import java.io.InputStream; public interface Get { + /** + * Retrieve a certificate by its fingerprint or the fingerprint of one of its subkeys. + * + * @param fingerprint fingerprint consisting of 32, 40 or 64 uppercase hex characters (without leading "0x" prefix). + * @return InputStream containing the ASCII armored certificate + * + * @throws CertNotFoundException in case the certificate cannot be found + * @throws IOException in case of an IO error + */ InputStream byFingerprint(String fingerprint) throws CertNotFoundException, IOException; - InputStream byKeyId(long keyId) throws CertNotFoundException; + /** + * Retrieve a certificate by its primary key id or the key id of one if its subkeys. + * + * @param keyId key id + * @return InputStream containing the ASCII armored certificate + * + * @throws CertNotFoundException in case the certificate cannot be found + * @throws IOException in case of an IO error + */ + InputStream byKeyId(long keyId) throws CertNotFoundException, IOException; - InputStream byEmail(String email) throws CertNotFoundException; + /** + * Retrieve a certificate by email address. + * Only exact matches are accepted. + * Note: On some servers, lookup by email address requires opt-in by the email addresses owner. + * + * @param email email address + * @return InputStream containing the ASCII armored certificate + * + * @throws CertNotFoundException in case the certificate cannot be found + * @throws IOException in case of an IO error + */ + InputStream byEmail(String email) throws CertNotFoundException, IOException; } diff --git a/vks-java/src/main/java/pgp/vks/client/RequestVerify.java b/vks-java/src/main/java/pgp/vks/client/RequestVerify.java index c67979b..ed059e0 100644 --- a/vks-java/src/main/java/pgp/vks/client/RequestVerify.java +++ b/vks-java/src/main/java/pgp/vks/client/RequestVerify.java @@ -1,4 +1,22 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + package pgp.vks.client; +import pgp.vks.client.v1.dto.VerificationResponse; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + public interface RequestVerify { + + default VerificationResponse forEmailAddresses(List emailAddresses, String uploadToken) + throws IOException { + return forEmailAddresses(emailAddresses, uploadToken, Arrays.asList("en_US", "en_GB")); + } + + VerificationResponse forEmailAddresses(List emailAddresses, String uploadToken, List locale) + throws IOException; } diff --git a/vks-java/src/main/java/pgp/vks/client/Upload.java b/vks-java/src/main/java/pgp/vks/client/Upload.java index 73d6486..ad074cb 100644 --- a/vks-java/src/main/java/pgp/vks/client/Upload.java +++ b/vks-java/src/main/java/pgp/vks/client/Upload.java @@ -1,11 +1,17 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + package pgp.vks.client; -import pgp.certificate_store.Certificate; -import pgp.vks.client.response.UploadResponse; +import pgp.vks.client.v1.dto.UploadResponse; import javax.annotation.Nonnull; +import java.io.IOException; +import java.io.InputStream; public interface Upload { - UploadResponse cert(@Nonnull Certificate certificate); + UploadResponse cert(@Nonnull InputStream certInStream) throws IOException; + } diff --git a/vks-java/src/main/java/pgp/vks/client/VKS.java b/vks-java/src/main/java/pgp/vks/client/VKS.java index f6fa633..5245bba 100644 --- a/vks-java/src/main/java/pgp/vks/client/VKS.java +++ b/vks-java/src/main/java/pgp/vks/client/VKS.java @@ -1,28 +1,85 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + package pgp.vks.client; +import pgp.vks.client.exception.UnsupportedApiException; + import javax.annotation.Nonnull; public interface VKS { + /** + * API Version. + */ enum Version { v1 } - default Get get() { + /** + * Retrieve OpenPGP certificates from a Verifying Key Server via the v1 API. + * + * @return Get API + * + * @throws UnsupportedApiException if Get-API v1 is not supported by the implementation of this interface + */ + default Get get() throws UnsupportedApiException { return get(Version.v1); } - Get get(@Nonnull Version version); + /** + * Retrieve OpenPGP certificates from a Verifying Key Server. + * + * @param version API version + * @return Get API + * + * @throws UnsupportedApiException if Get-API
version
is not supported by the implementation + * of this interface + */ + Get get(@Nonnull Version version) throws UnsupportedApiException; - default Upload upload() { + /** + * Upload an OpenPGP certificate to a Verifying Key Server via the v1 API. + * + * @return Upload API + * + * @throws UnsupportedApiException if Upload-API v1 is not supported by the implementation of this interface + */ + default Upload upload() throws UnsupportedApiException { return upload(Version.v1); } - Upload upload(@Nonnull Version version); + /** + * Upload an OpenPGP certificate to a Verifying Key Server. + * + * @param version API version + * @return Upload API + * + * @throws UnsupportedApiException if Upload-API
version
is not supported by the implementation + * of this interface + */ + Upload upload(@Nonnull Version version) throws UnsupportedApiException; - default RequestVerify requestVerify() { - return requestVerify(Version.v1); + /** + * Verify ownership of OpenPGP User-IDs on a Verifying Key Server via the v1 API. + * + * @return Request-Verify API + * + * @throws UnsupportedApiException if Request-Verify-API v1 is not supported by the implementation of this interface + */ + default RequestVerify requestVerification() throws UnsupportedApiException { + return requestVerification(Version.v1); } - RequestVerify requestVerify(Version version); + /** + * Verify ownership of OpenPGP User-IDs on a Verifying Key Server. + * + * @param version API version + * @return Upload API + * + * @throws UnsupportedApiException if Request-Verify-API
version
is not supported by the implementation + * of this interface + */ + RequestVerify requestVerification(Version version) throws UnsupportedApiException; } diff --git a/vks-java/src/main/java/pgp/vks/client/exception/CertCannotBePublishedException.java b/vks-java/src/main/java/pgp/vks/client/exception/CertCannotBePublishedException.java new file mode 100644 index 0000000..07b5fc3 --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/exception/CertCannotBePublishedException.java @@ -0,0 +1,14 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.exception; + +import java.net.ConnectException; + +public class CertCannotBePublishedException extends ConnectException { + + public CertCannotBePublishedException(String errorMessage) { + super(errorMessage); + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/exception/CertNotFoundException.java b/vks-java/src/main/java/pgp/vks/client/exception/CertNotFoundException.java index f5591f0..039eea7 100644 --- a/vks-java/src/main/java/pgp/vks/client/exception/CertNotFoundException.java +++ b/vks-java/src/main/java/pgp/vks/client/exception/CertNotFoundException.java @@ -1,12 +1,18 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + package pgp.vks.client.exception; -public class CertNotFoundException extends Exception { +import java.net.ConnectException; - public CertNotFoundException(Throwable cause) { - super(cause); - } +public class CertNotFoundException extends ConnectException { public CertNotFoundException() { + super(); + } + public CertNotFoundException(String message) { + super(message); } } diff --git a/vks-java/src/main/java/pgp/vks/client/exception/UnsupportedApiException.java b/vks-java/src/main/java/pgp/vks/client/exception/UnsupportedApiException.java new file mode 100644 index 0000000..7f017b6 --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/exception/UnsupportedApiException.java @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.exception; + +public class UnsupportedApiException extends RuntimeException { + + public UnsupportedApiException(String message) { + super(message); + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/impl/VKSImpl.java b/vks-java/src/main/java/pgp/vks/client/impl/VKSImpl.java deleted file mode 100644 index 6cd086c..0000000 --- a/vks-java/src/main/java/pgp/vks/client/impl/VKSImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -package pgp.vks.client.impl; - -import lombok.SneakyThrows; -import pgp.vks.client.Get; -import pgp.vks.client.RequestVerify; -import pgp.vks.client.Upload; -import pgp.vks.client.VKS; -import pgp.vks.client.impl.v1.GetImpl; -import pgp.vks.client.impl.v1.RequestVerifyImpl; -import pgp.vks.client.impl.v1.UploadImpl; -import pgp.vks.client.impl.v1.V1API; - -import javax.annotation.Nonnull; -import java.net.URL; - -public class VKSImpl implements VKS { - - private final V1API api; - - public VKSImpl(URL vksService) { - this.api = new V1API(vksService); - } - - @SneakyThrows - public static VKS keysDotOpenPgpDotOrg() { - return new VKSImpl(new URL("https://keys.openpgp.org")); - } - - @Override - public Get get(@Nonnull Version version) { - switch (version) { - case v1: - return new GetImpl(api); - default: - throw new IllegalArgumentException("Invalid version: " + version); - } - } - - @Override - public Upload upload(@Nonnull Version version) { - switch (version) { - case v1: - return new UploadImpl(); - default: - throw new IllegalArgumentException("Invalid version: " + version); - } - } - - @Override - public RequestVerify requestVerify(Version version) { - switch (version) { - case v1: - return new RequestVerifyImpl(); - default: - throw new IllegalArgumentException("Invalid version: " + version); - } - } -} diff --git a/vks-java/src/main/java/pgp/vks/client/impl/v1/GetImpl.java b/vks-java/src/main/java/pgp/vks/client/impl/v1/GetImpl.java deleted file mode 100644 index ad54d73..0000000 --- a/vks-java/src/main/java/pgp/vks/client/impl/v1/GetImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -package pgp.vks.client.impl.v1; - -import pgp.vks.client.Get; -import pgp.vks.client.exception.CertNotFoundException; - -import javax.net.ssl.HttpsURLConnection; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; - -public class GetImpl implements Get { - - private final V1API api; - - public GetImpl(V1API api) { - this.api = api; - } - - @Override - public InputStream byFingerprint(String fingerprint) throws CertNotFoundException, IOException { - URL url = api.getByFingerprint(fingerprint); - HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int status = connection.getResponseCode(); - if (status == 200) { - return connection.getInputStream(); - } else if (status == 404) { - throw new CertNotFoundException(); - } else { - throw new IllegalStateException("Unhandled status code: " + status); - } - } - - @Override - public InputStream byKeyId(long keyId) throws CertNotFoundException { - return null; - } - - @Override - public InputStream byEmail(String email) throws CertNotFoundException { - return null; - } -} diff --git a/vks-java/src/main/java/pgp/vks/client/impl/v1/RequestVerifyImpl.java b/vks-java/src/main/java/pgp/vks/client/impl/v1/RequestVerifyImpl.java deleted file mode 100644 index afd2cd0..0000000 --- a/vks-java/src/main/java/pgp/vks/client/impl/v1/RequestVerifyImpl.java +++ /dev/null @@ -1,6 +0,0 @@ -package pgp.vks.client.impl.v1; - -import pgp.vks.client.RequestVerify; - -public class RequestVerifyImpl implements RequestVerify { -} diff --git a/vks-java/src/main/java/pgp/vks/client/impl/v1/UploadImpl.java b/vks-java/src/main/java/pgp/vks/client/impl/v1/UploadImpl.java deleted file mode 100644 index 21489a5..0000000 --- a/vks-java/src/main/java/pgp/vks/client/impl/v1/UploadImpl.java +++ /dev/null @@ -1,14 +0,0 @@ -package pgp.vks.client.impl.v1; - -import pgp.certificate_store.Certificate; -import pgp.vks.client.Upload; -import pgp.vks.client.response.UploadResponse; - -import javax.annotation.Nonnull; - -public class UploadImpl implements Upload { - @Override - public UploadResponse cert(@Nonnull Certificate certificate) { - return null; - } -} diff --git a/vks-java/src/main/java/pgp/vks/client/request/RequestVerifyRequest.java b/vks-java/src/main/java/pgp/vks/client/request/RequestVerifyRequest.java deleted file mode 100644 index c2fb1c3..0000000 --- a/vks-java/src/main/java/pgp/vks/client/request/RequestVerifyRequest.java +++ /dev/null @@ -1,17 +0,0 @@ -package pgp.vks.client.request; - -import javax.annotation.Nonnull; -import java.util.List; - -public class RequestVerifyRequest { - - private final String token; - private final List addresses; - private final List locale; - - public RequestVerifyRequest(@Nonnull String token, @Nonnull List addresses, @Nonnull List locale) { - this.token = token; - this.addresses = addresses; - this.locale = locale; - } -} diff --git a/vks-java/src/main/java/pgp/vks/client/request/UploadRequest.java b/vks-java/src/main/java/pgp/vks/client/request/UploadRequest.java deleted file mode 100644 index d9eff90..0000000 --- a/vks-java/src/main/java/pgp/vks/client/request/UploadRequest.java +++ /dev/null @@ -1,12 +0,0 @@ -package pgp.vks.client.request; - -import javax.annotation.Nonnull; - -public class UploadRequest { - - private final String keytext; - - public UploadRequest(@Nonnull String keytext) { - this.keytext = keytext; - } -} diff --git a/vks-java/src/main/java/pgp/vks/client/response/ErrorResponse.java b/vks-java/src/main/java/pgp/vks/client/response/ErrorResponse.java deleted file mode 100644 index 34c2799..0000000 --- a/vks-java/src/main/java/pgp/vks/client/response/ErrorResponse.java +++ /dev/null @@ -1,16 +0,0 @@ -package pgp.vks.client.response; - -import javax.annotation.Nonnull; - -public class ErrorResponse { - - private final String error; - - public ErrorResponse(@Nonnull String error) { - this.error = error; - } - - public String getError() { - return error; - } -} diff --git a/vks-java/src/main/java/pgp/vks/client/response/RequestVerifyResponse.java b/vks-java/src/main/java/pgp/vks/client/response/RequestVerifyResponse.java deleted file mode 100644 index 7fec6de..0000000 --- a/vks-java/src/main/java/pgp/vks/client/response/RequestVerifyResponse.java +++ /dev/null @@ -1,17 +0,0 @@ -package pgp.vks.client.response; - -import javax.annotation.Nonnull; -import java.util.Map; - -public class RequestVerifyResponse { - - private final String key_fpr; - private final Map status; - private final String token; - - public RequestVerifyResponse(@Nonnull String key_fpr, @Nonnull Map status, @Nonnull String token) { - this.key_fpr = key_fpr; - this.status = status; - this.token = token; - } -} diff --git a/vks-java/src/main/java/pgp/vks/client/response/Status.java b/vks-java/src/main/java/pgp/vks/client/response/Status.java deleted file mode 100644 index a230ee0..0000000 --- a/vks-java/src/main/java/pgp/vks/client/response/Status.java +++ /dev/null @@ -1,8 +0,0 @@ -package pgp.vks.client.response; - -enum Status { - unpublished, - published, - revoked, - pending -} diff --git a/vks-java/src/main/java/pgp/vks/client/response/UploadResponse.java b/vks-java/src/main/java/pgp/vks/client/response/UploadResponse.java deleted file mode 100644 index 463fce9..0000000 --- a/vks-java/src/main/java/pgp/vks/client/response/UploadResponse.java +++ /dev/null @@ -1,17 +0,0 @@ -package pgp.vks.client.response; - -import java.util.Map; - -public class UploadResponse { - - private final String key_fpr; - private final Map status; - private final String token; - - public UploadResponse(String key_fpr, Map status, String token) { - this.key_fpr = key_fpr; - this.status = status; - this.token = token; - } - -} diff --git a/vks-java/src/main/java/pgp/vks/client/v1/dto/ErrorResponse.java b/vks-java/src/main/java/pgp/vks/client/v1/dto/ErrorResponse.java new file mode 100644 index 0000000..1ac0e2a --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/dto/ErrorResponse.java @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ErrorResponse { + + private final String error; + + public ErrorResponse(@JsonProperty("error") String error) { + this.error = error; + } + + @JsonProperty("error") + public String getError() { + return error; + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/v1/dto/Status.java b/vks-java/src/main/java/pgp/vks/client/v1/dto/Status.java new file mode 100644 index 0000000..c6fde2c --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/dto/Status.java @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.dto; + +public enum Status { + unpublished, + published, + revoked, + pending +} diff --git a/vks-java/src/main/java/pgp/vks/client/v1/dto/UploadRequest.java b/vks-java/src/main/java/pgp/vks/client/v1/dto/UploadRequest.java new file mode 100644 index 0000000..7acaaeb --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/dto/UploadRequest.java @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Base64; + +import java.nio.charset.StandardCharsets; + +public class UploadRequest { + + private static final byte[] ARMOR_HEADER = "-----BEGIN PGP PUBLIC KEY BLOCK-----".getBytes(StandardCharsets.UTF_8); + + private final String keytext; + + public UploadRequest(@JsonProperty("keytext") String keytext) { + this.keytext = keytext; + } + + public static UploadRequest fromBytes(byte[] keytext) { + String armoredOrBase64 = new String(base64IfNecessary(keytext)); + return new UploadRequest(armoredOrBase64); + } + + private static byte[] base64IfNecessary(byte[] certBytes) { + if (!Arrays.areEqual(certBytes, 0, ARMOR_HEADER.length, ARMOR_HEADER, 0, ARMOR_HEADER.length)) { + certBytes = Base64.encode(certBytes); + } + return certBytes; + } + + @JsonProperty("keytext") + public String getKeyText() { + return keytext; + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/v1/dto/UploadResponse.java b/vks-java/src/main/java/pgp/vks/client/v1/dto/UploadResponse.java new file mode 100644 index 0000000..1aca588 --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/dto/UploadResponse.java @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.dto; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.HashMap; +import java.util.Map; + +public class UploadResponse { + + private final String key_fpr; + private final Map status; + private final String token; + + public UploadResponse(@JsonProperty("key_fpr") String key_fpr, + @JsonProperty("status") Map status, + @JsonProperty("token") String token) { + this.key_fpr = key_fpr; + this.status = status; + this.token = token; + } + + @JsonProperty("key_fpr") + public String getKeyFingerprint() { + return key_fpr; + } + + @JsonProperty("token") + public String getToken() { + return token; + } + + @JsonProperty("status") + public Map getStatus() { + return new HashMap<>(status); + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/v1/dto/VerificationRequest.java b/vks-java/src/main/java/pgp/vks/client/v1/dto/VerificationRequest.java new file mode 100644 index 0000000..62bbfe2 --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/dto/VerificationRequest.java @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public class VerificationRequest { + + private final String token; + private final List addresses; + private final List locale; + + public VerificationRequest(@JsonProperty("token") String token, + @JsonProperty("addresses") List addresses, + @JsonProperty("locale") List locale) { + this.token = token; + this.addresses = addresses; + this.locale = locale; + } + + @JsonProperty("token") + public String getToken() { + return token; + } + + @JsonProperty("addresses") + public List getAddresses() { + return addresses; + } + + @JsonProperty("locale") + public List getLocale() { + return locale; + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/v1/dto/VerificationResponse.java b/vks-java/src/main/java/pgp/vks/client/v1/dto/VerificationResponse.java new file mode 100644 index 0000000..ffee3ea --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/dto/VerificationResponse.java @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Map; + +public class VerificationResponse { + + private final String key_fpr; + private final Map status; + private final String token; + + public VerificationResponse(@JsonProperty("key_fpr") String key_fpr, + @JsonProperty("status") Map status, + @JsonProperty("token") String token) { + this.key_fpr = key_fpr; + this.status = status; + this.token = token; + } + + @JsonProperty("key_fpr") + public String getKeyFingerprint() { + return key_fpr; + } + + @JsonProperty("token") + public String getToken() { + return token; + } + + @JsonProperty("status") + public Map getStatus() { + return status; + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/v1/impl/GetImpl.java b/vks-java/src/main/java/pgp/vks/client/v1/impl/GetImpl.java new file mode 100644 index 0000000..2cf38d0 --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/impl/GetImpl.java @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.impl; + +import pgp.vks.client.Get; +import pgp.vks.client.exception.CertNotFoundException; + +import javax.net.ssl.HttpsURLConnection; +import java.io.IOException; +import java.io.InputStream; +import java.net.ConnectException; +import java.net.URL; + +public class GetImpl implements Get { + + private final URLMapper api; + + public GetImpl(URLMapper api) { + this.api = api; + } + + @Override + public InputStream byFingerprint(String fingerprint) throws IOException { + URL url = api.getByFingerprint(fingerprint); + return fetchFromUrl(url); + } + + @Override + public InputStream byKeyId(long keyId) throws IOException { + URL url = api.getByKeyid(keyId); + return fetchFromUrl(url); + } + + @Override + public InputStream byEmail(String email) throws IOException { + URL url = api.getByEmail(email); + return fetchFromUrl(url); + } + + private InputStream fetchFromUrl(URL url) throws IOException { + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + + int status = connection.getResponseCode(); + if (status == 200) { + return connection.getInputStream(); + } else if (status == 404) { + throw new CertNotFoundException("Certificate not found. Status Code: 404"); + } else { + throw new ConnectException("Cannot retrieve certificate. Status Code: " + status); + } + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/v1/impl/RequestVerifyImpl.java b/vks-java/src/main/java/pgp/vks/client/v1/impl/RequestVerifyImpl.java new file mode 100644 index 0000000..a548c49 --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/impl/RequestVerifyImpl.java @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import pgp.vks.client.RequestVerify; +import pgp.vks.client.exception.CertCannotBePublishedException; +import pgp.vks.client.v1.dto.ErrorResponse; +import pgp.vks.client.v1.dto.VerificationResponse; +import pgp.vks.client.v1.dto.VerificationRequest; + +import javax.net.ssl.HttpsURLConnection; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.List; + +public class RequestVerifyImpl implements RequestVerify { + + private final URLMapper api; + private final ObjectMapper json = new ObjectMapper(); + + public RequestVerifyImpl(URLMapper api) { + this.api = api; + } + + @Override + public VerificationResponse forEmailAddresses(List emailAddresses, String token, List locale) + throws IOException { + VerificationRequest request = new VerificationRequest(token, emailAddresses, locale); + + URL url = api.postRequestVerify(); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + + OutputStream out = connection.getOutputStream(); + json.writeValue(out, request); + out.flush(); + out.close(); + + int status = connection.getResponseCode(); + InputStream responseIn; + if (status >= 400) { + responseIn = connection.getErrorStream(); + ErrorResponse errorResponse = json.readValue(responseIn, ErrorResponse.class); + throw new CertCannotBePublishedException(errorResponse.getError() + (status)); + } else { + responseIn = connection.getInputStream(); + VerificationResponse response = json.readValue(responseIn, VerificationResponse.class); + return response; + } + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/impl/v1/V1API.java b/vks-java/src/main/java/pgp/vks/client/v1/impl/URLMapper.java similarity index 50% rename from vks-java/src/main/java/pgp/vks/client/impl/v1/V1API.java rename to vks-java/src/main/java/pgp/vks/client/v1/impl/URLMapper.java index 7e29b47..ad99c69 100644 --- a/vks-java/src/main/java/pgp/vks/client/impl/v1/V1API.java +++ b/vks-java/src/main/java/pgp/vks/client/v1/impl/URLMapper.java @@ -1,17 +1,22 @@ -package pgp.vks.client.impl.v1; +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.impl; import lombok.SneakyThrows; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; +import java.util.regex.Pattern; /** * URL mapper for the VKS API. * * @see VKS API Documentatioon */ -public class V1API { +public class URLMapper { private static final String GET_BY_FINGERPRINT = "/vks/v1/by-fingerprint/"; private static final String GET_BY_KEYID = "/vks/v1/by-keyid/"; @@ -19,14 +24,28 @@ public class V1API { private static final String POST_UPLOAD = "/vks/v1/upload"; private static final String POST_REQUEST_VERIFY = "/vks/v1/request-verify"; + private static final Pattern PATTERN_HEX = Pattern.compile("^[0-9A-F]*$"); + // see Java Regex from https://emailregex.com/ + private static final Pattern PATTERN_EMAIL = Pattern.compile("(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"); + private final URL serviceUrl; - public V1API(URL serviceUrl) { + /** + * Create an {@link URLMapper} for the given key server. + * + * @param serviceUrl URL of the key server + */ + public URLMapper(URL serviceUrl) { this.serviceUrl = serviceUrl; } public URL getByFingerprint(String fingerprint) { - return getUrl(GET_BY_FINGERPRINT, fingerprint.toUpperCase()); + String uppercase = fingerprint.toUpperCase(); + int len = uppercase.length(); + if ((len != 32 && len != 40 && len != 64) || !PATTERN_HEX.matcher(uppercase).matches()) { + throw new IllegalArgumentException("Invalid OpenPGP fingerprint: " + fingerprint); + } + return getUrl(GET_BY_FINGERPRINT, uppercase); } public URL getByKeyid(long keyId) { @@ -34,6 +53,10 @@ public class V1API { } public URL getByEmail(String email) { + if (!PATTERN_EMAIL.matcher(email).matches()) { + throw new IllegalArgumentException("Invalid email address: " + email); + } + try { return getUrl(GET_BY_EMAIL, URLEncoder.encode(email, "UTF-8")); } catch (UnsupportedEncodingException e) { diff --git a/vks-java/src/main/java/pgp/vks/client/v1/impl/UploadImpl.java b/vks-java/src/main/java/pgp/vks/client/v1/impl/UploadImpl.java new file mode 100644 index 0000000..887901b --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/impl/UploadImpl.java @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.impl; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.bouncycastle.util.io.Streams; +import pgp.vks.client.Upload; +import pgp.vks.client.exception.CertCannotBePublishedException; +import pgp.vks.client.v1.dto.UploadRequest; +import pgp.vks.client.v1.dto.ErrorResponse; +import pgp.vks.client.v1.dto.UploadResponse; + +import javax.annotation.Nonnull; +import javax.net.ssl.HttpsURLConnection; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; + +public class UploadImpl implements Upload { + + private final URLMapper api; + private final ObjectMapper json = new ObjectMapper(); + + public UploadImpl(URLMapper api) { + this.api = api; + } + + @Override + public UploadResponse cert(@Nonnull InputStream certInStream) throws IOException { + ByteArrayOutputStream certBuf = new ByteArrayOutputStream(); + Streams.pipeAll(certInStream, certBuf); + certInStream.close(); + + UploadRequest request = UploadRequest.fromBytes(certBuf.toByteArray()); + + URL url = api.postUpload(); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setDoOutput(true); + + OutputStream out = connection.getOutputStream(); + byte[] requestBody = json.writeValueAsBytes(request); + out.write(requestBody); + out.flush(); + out.close(); + + int status = connection.getResponseCode(); + System.out.println(status); + InputStream responseIn; + if (status >= 400) { + responseIn = connection.getErrorStream(); + ErrorResponse errorResponse = json.readValue(responseIn, ErrorResponse.class); + throw new CertCannotBePublishedException(errorResponse.getError() + (status)); + } else { + responseIn = connection.getInputStream(); + UploadResponse response = json.readValue(responseIn, UploadResponse.class); + return response; + } + } +} diff --git a/vks-java/src/main/java/pgp/vks/client/v1/impl/VKSImpl.java b/vks-java/src/main/java/pgp/vks/client/v1/impl/VKSImpl.java new file mode 100644 index 0000000..d0a9526 --- /dev/null +++ b/vks-java/src/main/java/pgp/vks/client/v1/impl/VKSImpl.java @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.v1.impl; + +import lombok.SneakyThrows; +import pgp.vks.client.Get; +import pgp.vks.client.RequestVerify; +import pgp.vks.client.Upload; +import pgp.vks.client.VKS; +import pgp.vks.client.exception.UnsupportedApiException; + +import javax.annotation.Nonnull; +import java.net.MalformedURLException; +import java.net.URL; + +public class VKSImpl implements VKS { + + private final URLMapper api; + + public VKSImpl(String vksServiceDomain) throws MalformedURLException { + this(new URL(vksServiceDomain)); + } + + public VKSImpl(URL vksService) { + this.api = new URLMapper(vksService); + } + + @SneakyThrows + public static VKS keysDotOpenPgpDotOrg() { + return new VKSImpl("https://keys.openpgp.org"); + } + + @Override + public Get get(@Nonnull Version version) { + switch (version) { + case v1: + return new GetImpl(api); + default: + throw new UnsupportedApiException("Get-API in version " + version + " not supported."); + } + } + + @Override + public Upload upload(@Nonnull Version version) { + switch (version) { + case v1: + return new UploadImpl(api); + default: + throw new UnsupportedApiException("Upload-API in version " + version + " not supported."); + } + } + + @Override + public RequestVerify requestVerification(Version version) { + switch (version) { + case v1: + return new RequestVerifyImpl(api); + default: + throw new UnsupportedApiException("Request-Verify-API in version " + version + " not supported."); + } + } +} diff --git a/vks-java/src/test/java/pgp/vks/client/impl/v1/V1APITest.java b/vks-java/src/test/java/pgp/vks/client/impl/v1/V1APITest.java index b28b605..8b5c6d1 100644 --- a/vks-java/src/test/java/pgp/vks/client/impl/v1/V1APITest.java +++ b/vks-java/src/test/java/pgp/vks/client/impl/v1/V1APITest.java @@ -1,7 +1,12 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + package pgp.vks.client.impl.v1; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import pgp.vks.client.v1.impl.URLMapper; import java.net.MalformedURLException; import java.net.URL; @@ -10,11 +15,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class V1APITest { - private static V1API api; + private static URLMapper api; @BeforeAll static void prepare() throws MalformedURLException { - api = new V1API(new URL("https://keys.openpgp.org")); + api = new URLMapper(new URL("https://keys.openpgp.org")); } @Test diff --git a/vks-java/src/test/java/pgp/vks/client/impl/v1/VKSTest.java b/vks-java/src/test/java/pgp/vks/client/impl/v1/VKSTest.java index 8aa0d43..80ba414 100644 --- a/vks-java/src/test/java/pgp/vks/client/impl/v1/VKSTest.java +++ b/vks-java/src/test/java/pgp/vks/client/impl/v1/VKSTest.java @@ -1,16 +1,25 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + package pgp.vks.client.impl.v1; -import lombok.SneakyThrows; import org.bouncycastle.util.io.Streams; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import pgp.vks.client.VKS; import pgp.vks.client.exception.CertNotFoundException; -import pgp.vks.client.impl.VKSImpl; +import pgp.vks.client.v1.dto.VerificationResponse; +import pgp.vks.client.v1.impl.VKSImpl; +import pgp.vks.client.v1.dto.UploadResponse; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class VKSTest { @@ -23,7 +32,7 @@ public class VKSTest { } @Test - public void testGetByFingerprint() throws CertNotFoundException, IOException { + public void testGetByFingerprint() throws IOException { InputStream inputStream = vks.get().byFingerprint("7F9116FEA90A5983936C7CFAA027DB2F3E1E118A"); Streams.pipeAll(inputStream, System.out); } @@ -33,4 +42,51 @@ public class VKSTest { assertThrows(CertNotFoundException.class, () -> vks.get().byFingerprint("0000000000000000000000000000000000000000")); } + + @Test + public void testUploadArmored() throws IOException { + String keyArmored = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "Comment: 5741 7147 D0C8 B548 220A 36A6 0BAA B05A 0877 68D3\n" + + "Comment: \n" + + "\n" + + "xjMEYky2cxYJKwYBBAHaRw8BAQdA+l48gCNI3qq+I5KFOWzJUEqd1ojQ9dj8vPxX\n" + + "FaQFwrPCwBEEHxYKAIMFgmJMtnMFiQWkj70DCwkHCRALqrBaCHdo00cUAAAAAAAe\n" + + "ACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmecnaLE0kMC8KdcEyXcBbGa\n" + + "YjiagLt29IAfEb5gkvRdlwMVCggCmwECHgEWIQRXQXFH0Mi1SCIKNqYLqrBaCHdo\n" + + "0wAAIi8A/1HZNJgTKluUnWx9LArNy7/zeJfqjv/OpM+2UTnzx39YAP4jDLV4MnQR\n" + + "yqV8cwMIUs3ywVLUXC1mhb4Mos+fCJv8Ac0XPHRlc3QxMjNhc2Rhc2RAYnlvbS5k\n" + + "ZT7CwBQEExYKAIYFgmJMtnMFiQWkj70DCwkHCRALqrBaCHdo00cUAAAAAAAeACBz\n" + + "YWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmfb06zBQi+jpdGinb/RdunCKtsB\n" + + "1p2+/BK+OhAg7QeoegM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yLVIIgo2pguqsFoId2jTAAAgMgD+PH0e2GkKe+gw\n" + + "Bv60rUPUuwD2ubrASm5EkT+wPfY+ZyoBAOjp0Z2Vbrx0NkW7nd+HENb4v91eNUJA\n" + + "YA3TLiYiZbEM\n" + + "=QRwY\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + String keyFingerprint = "57417147D0C8B548220A36A60BAAB05A087768D3"; + + UploadResponse uploadResponse = vks.upload().cert(new ByteArrayInputStream(keyArmored.getBytes(StandardCharsets.UTF_8))); + assertEquals(keyFingerprint, uploadResponse.getKeyFingerprint()); + + VerificationResponse verifyResponse = vks.requestVerification().forEmailAddresses( + Collections.singletonList("test123asdasd@byom.de"), + uploadResponse.getToken(), + Collections.singletonList("de_DE")); + + assertEquals(keyFingerprint, verifyResponse.getKeyFingerprint()); + } } diff --git a/vks-java/src/test/java/pgp/vks/client/impl/v1/dto/UploadRequestTest.java b/vks-java/src/test/java/pgp/vks/client/impl/v1/dto/UploadRequestTest.java new file mode 100644 index 0000000..e9a3998 --- /dev/null +++ b/vks-java/src/test/java/pgp/vks/client/impl/v1/dto/UploadRequestTest.java @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.impl.v1.dto; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.bouncycastle.util.encoders.Base64; +import org.junit.jupiter.api.Test; +import pgp.vks.client.v1.dto.UploadRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class UploadRequestTest { + + private static final String TEST_CERT_ARMORED = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "Comment: 9DF2 C3FE 6F69 A3EE DBD5 FB81 69E8 A788 A36E 7BFD\n" + + "Comment: Test\n" + + "\n" + + "xjMEYkyuqxYJKwYBBAHaRw8BAQdAKayCvDEF4ZBcUJ9NPZlrG2jYOrNHDfYqOHpq\n" + + "D+3AkK7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336RMsPgE3JlKx9zGPZcU9HVib70Q2fXxSVR7RQD+O9PEF7MqsIZXiTFG\n" + + "vkwLe97LoCBBw6LhO8YlDiIZAwwWIQSd8sP+b2mj7tvV+4Fp6KeIo257/QAAdekA\n" + + "/jp1Nc5kihBPK/vsQSJkHtUeeYPZQz9wxeFgKjEVQiBVAP9lwdJzgC4FNdz0rpp6\n" + + "xCG38GI2o97S1cr+ot3lkaZpBc44BGJMrqsSCisGAQQBl1UBBQEBB0D8iZDZOC0M\n" + + "MkZHO7UPpqhCaW642O00LkrToWaKbaUoRAMBCAnCwAYEGBYKAHgFgmJMrqsFiQWk\n" + + "j70JEGnop4ijbnv9RxQAAAAAAB4AIHNhbHRAbm90YXRpb25zLnNlcXVvaWEtcGdw\n" + + "Lm9yZ8Jbc6jIIwGN+Pb7UYyTUCzjBvypv9S6ewlfyYYIvbIpApsMFiEEnfLD/m9p\n" + + "o+7b1fuBaeiniKNue/0AAGQlAQCULqkfbB5T/62qn6o7U4BrmmC90gGksSdpyiur\n" + + "c9OuIQEAgCeZNcTY8ocGWjsW+6h4A4a1UcmXpK9aqkHd1MNXxQ8=\n" + + "=stBT\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + private static final String TEST_CERT_BASE64 = "xjMEYkyuqxYJKwYBBAHaRw8BAQdAKayCvDEF4ZBcUJ9NPZlrG2jYOrNHDfYqOHpqD+3AkK7CwBEE" + + "HxYKAIMFgmJMrqsFiQWkj70DCwkHCRBp6KeIo257/UcUAAAAAAAeACBzYWx0QG5vdGF0aW9ucy5z" + + "ZXF1b2lhLXBncC5vcmeCqtr0bdgGRbTWiCD+lFXmcyAF5bE3vAgLRHfSSjXcDgMVCggCmwECHgEW" + + "IQSd8sP+b2mj7tvV+4Fp6KeIo257/QAA5pYA/1LKPHcYBTFAIQEJo7cN6ZUJVupGCPI5g2F2qBJb" + + "k5OTAQCmiYScX22UVuoOq/QIgMXhlVMb/oFs7ttWiSbTWHQMAM0EVGVzdMLAFAQTFgo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IHNhbHRAbm90YXRpb25zLnNlcXVvaWEtcGdwLm9yZ8Jbc6jIIwGN+Pb7UYyTUCzjBvypv9S6" + + "ewlfyYYIvbIpApsMFiEEnfLD/m9po+7b1fuBaeiniKNue/0AAGQlAQCULqkfbB5T/62qn6o7U4Br" + + "mmC90gGksSdpyiurc9OuIQEAgCeZNcTY8ocGWjsW+6h4A4a1UcmXpK9aqkHd1MNXxQ8="; + + private static final ObjectMapper json = new ObjectMapper(); + + @Test + public void testSerializeDeserializeArmoredCert() throws JsonProcessingException { + UploadRequest request = new UploadRequest(TEST_CERT_ARMORED); + + String val = json.writeValueAsString(request); + request = json.readValue(val, UploadRequest.class); + + assertEquals(TEST_CERT_ARMORED, request.getKeyText()); + } + + @Test + public void testSerializeDeserializeBase64() throws JsonProcessingException { + byte[] rawCert = Base64.decode(TEST_CERT_BASE64); + UploadRequest request = UploadRequest.fromBytes(rawCert); + + String val = json.writeValueAsString(request); + request = json.readValue(val, UploadRequest.class); + + assertEquals(TEST_CERT_BASE64, request.getKeyText()); + } +} diff --git a/vks-java/src/test/java/pgp/vks/client/impl/v1/dto/UploadResponseTest.java b/vks-java/src/test/java/pgp/vks/client/impl/v1/dto/UploadResponseTest.java new file mode 100644 index 0000000..fa0c5cd --- /dev/null +++ b/vks-java/src/test/java/pgp/vks/client/impl/v1/dto/UploadResponseTest.java @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + +package pgp.vks.client.impl.v1.dto; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import pgp.vks.client.v1.dto.Status; +import pgp.vks.client.v1.dto.UploadResponse; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class UploadResponseTest { + + private static final ObjectMapper json = new ObjectMapper(); + + @Test + public void testSerializeDeserialize() throws JsonProcessingException { + String fingerprint = "9DF2C3FE6F69A3EEDBD5FB8169E8A788A36E7BFD"; + Map statusMap = new HashMap<>(); + statusMap.put("hello@world.mail", Status.pending); + statusMap.put("hello@mail.world", Status.unpublished); + String token = "t0k3n5tr1n9"; + + UploadResponse response = new UploadResponse(fingerprint, statusMap, token); + + String val = json.writeValueAsString(response); + response = json.readValue(val, UploadResponse.class); + + assertEquals(fingerprint, response.getKeyFingerprint()); + assertEquals(statusMap, response.getStatus()); + assertEquals(token, response.getToken()); + } +} diff --git a/vks-java/src/test/java/pgp/vks/client/impl/v1/dummy_vks/DummyVks.java b/vks-java/src/test/java/pgp/vks/client/impl/v1/dummy_vks/DummyVks.java index a9d8375..3a446a4 100644 --- a/vks-java/src/test/java/pgp/vks/client/impl/v1/dummy_vks/DummyVks.java +++ b/vks-java/src/test/java/pgp/vks/client/impl/v1/dummy_vks/DummyVks.java @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2022 Paul Schaub +// +// SPDX-License-Identifier: Apache-2.0 + package pgp.vks.client.impl.v1.dummy_vks; public class DummyVks {