health_cards 0.0.1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/LICENSE.txt +202 -0
- data/lib/health_cards.rb +25 -0
- data/lib/health_cards/chunking.rb +69 -0
- data/lib/health_cards/covid_health_card.rb +12 -0
- data/lib/health_cards/encoding.rb +24 -0
- data/lib/health_cards/exceptions.rb +45 -0
- data/lib/health_cards/exporter.rb +23 -0
- data/lib/health_cards/health_card.rb +223 -0
- data/lib/health_cards/importer.rb +25 -0
- data/lib/health_cards/issuer.rb +60 -0
- data/lib/health_cards/jws.rb +124 -0
- data/lib/health_cards/key.rb +69 -0
- data/lib/health_cards/key_set.rb +86 -0
- data/lib/health_cards/private_key.rb +50 -0
- data/lib/health_cards/public_key.rb +31 -0
- data/lib/health_cards/verification.rb +32 -0
- data/lib/health_cards/verifier.rb +68 -0
- data/lib/health_cards/version.rb +5 -0
- metadata +92 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: f299c1c4dec501f53d77e64007a9805316974ea5e649b1918f413e52ffc0dbf4
|
4
|
+
data.tar.gz: 118a46c61178a67461d0ee3fbeedab15ea4b0f93433ece7add27aceb1f398e0c
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: d9765d939d22cd01ff11b5c20a29d413af83124970ecb06cf89abc0b7cff393080ae12a908e22de411b991aa05ecaaddeb2023a9192aaab741379ecffd9a5c4a
|
7
|
+
data.tar.gz: 1102f68ec1d832766ecd37c15fd790ff3ab0e7d8505468dcf210d3b97d516900d5876a2aa7e5de963bad9667b4c48d654b5fcec733f3b3a141dd4f84b9d19097
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,202 @@
|
|
1
|
+
|
2
|
+
Apache License
|
3
|
+
Version 2.0, January 2004
|
4
|
+
http://www.apache.org/licenses/
|
5
|
+
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
7
|
+
|
8
|
+
1. Definitions.
|
9
|
+
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
12
|
+
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
14
|
+
the copyright owner that is granting the License.
|
15
|
+
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
17
|
+
other entities that control, are controlled by, or are under common
|
18
|
+
control with that entity. For the purposes of this definition,
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
20
|
+
direction or management of such entity, whether by contract or
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
23
|
+
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
25
|
+
exercising permissions granted by this License.
|
26
|
+
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
28
|
+
including but not limited to software source code, documentation
|
29
|
+
source, and configuration files.
|
30
|
+
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
32
|
+
transformation or translation of a Source form, including but
|
33
|
+
not limited to compiled object code, generated documentation,
|
34
|
+
and conversions to other media types.
|
35
|
+
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
37
|
+
Object form, made available under the License, as indicated by a
|
38
|
+
copyright notice that is included in or attached to the work
|
39
|
+
(an example is provided in the Appendix below).
|
40
|
+
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
47
|
+
the Work and Derivative Works thereof.
|
48
|
+
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
50
|
+
the original version of the Work and any modifications or additions
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
62
|
+
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
65
|
+
subsequently incorporated within the Work.
|
66
|
+
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
73
|
+
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
79
|
+
where such license applies only to those patent claims licensable
|
80
|
+
by such Contributor that are necessarily infringed by their
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
83
|
+
institute patent litigation against any entity (including a
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
86
|
+
or contributory patent infringement, then any patent licenses
|
87
|
+
granted to You under this License for that Work shall terminate
|
88
|
+
as of the date such litigation is filed.
|
89
|
+
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
92
|
+
modifications, and in Source or Object form, provided that You
|
93
|
+
meet the following conditions:
|
94
|
+
|
95
|
+
(a) You must give any other recipients of the Work or
|
96
|
+
Derivative Works a copy of this License; and
|
97
|
+
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
99
|
+
stating that You changed the files; and
|
100
|
+
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
103
|
+
attribution notices from the Source form of the Work,
|
104
|
+
excluding those notices that do not pertain to any part of
|
105
|
+
the Derivative Works; and
|
106
|
+
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
109
|
+
include a readable copy of the attribution notices contained
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
112
|
+
of the following places: within a NOTICE text file distributed
|
113
|
+
as part of the Derivative Works; within the Source form or
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
115
|
+
within a display generated by the Derivative Works, if and
|
116
|
+
wherever such third-party notices normally appear. The contents
|
117
|
+
of the NOTICE file are for informational purposes only and
|
118
|
+
do not modify the License. You may add Your own attribution
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
121
|
+
that such additional attribution notices cannot be construed
|
122
|
+
as modifying the License.
|
123
|
+
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
125
|
+
may provide additional or different license terms and conditions
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
129
|
+
the conditions stated in this License.
|
130
|
+
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
134
|
+
this License, without any additional terms or conditions.
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
136
|
+
the terms of any separate license agreement you may have executed
|
137
|
+
with Licensor regarding such Contributions.
|
138
|
+
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
141
|
+
except as required for reasonable and customary use in describing the
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
143
|
+
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
153
|
+
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
159
|
+
incidental, or consequential damages of any character arising as a
|
160
|
+
result of this License or out of the use or inability to use the
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
163
|
+
other commercial damages or losses), even if such Contributor
|
164
|
+
has been advised of the possibility of such damages.
|
165
|
+
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
169
|
+
or other liability obligations and/or rights consistent with this
|
170
|
+
License. However, in accepting such obligations, You may act only
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
175
|
+
of your accepting any such warranty or additional liability.
|
176
|
+
|
177
|
+
END OF TERMS AND CONDITIONS
|
178
|
+
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
180
|
+
|
181
|
+
To apply the Apache License to your work, attach the following
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
183
|
+
replaced with your own identifying information. (Don't include
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
185
|
+
comment syntax for the file format. We also recommend that a
|
186
|
+
file or class name and description of purpose be included on the
|
187
|
+
same "printed page" as the copyright notice for easier
|
188
|
+
identification within third-party archives.
|
189
|
+
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
191
|
+
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
193
|
+
you may not use this file except in compliance with the License.
|
194
|
+
You may obtain a copy of the License at
|
195
|
+
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
197
|
+
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
201
|
+
See the License for the specific language governing permissions and
|
202
|
+
limitations under the License.
|
data/lib/health_cards.rb
ADDED
@@ -0,0 +1,25 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'health_cards/version'
|
4
|
+
require 'health_cards/encoding'
|
5
|
+
require 'health_cards/issuer'
|
6
|
+
require 'health_cards/key'
|
7
|
+
require 'health_cards/jws'
|
8
|
+
require 'health_cards/key_set'
|
9
|
+
require 'health_cards/private_key'
|
10
|
+
require 'health_cards/public_key'
|
11
|
+
require 'health_cards/health_card'
|
12
|
+
require 'health_cards/chunking'
|
13
|
+
require 'health_cards/exceptions'
|
14
|
+
require 'health_cards/verifier'
|
15
|
+
require 'health_cards/importer'
|
16
|
+
require 'health_cards/covid_health_card'
|
17
|
+
require 'health_cards/exporter'
|
18
|
+
|
19
|
+
require 'base64'
|
20
|
+
require 'fhir_models'
|
21
|
+
|
22
|
+
module HealthCards
|
23
|
+
class Error < StandardError; end
|
24
|
+
# Your code goes here...
|
25
|
+
end
|
@@ -0,0 +1,69 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module HealthCards
|
4
|
+
# Split up a JWS into chunks if encoded size is above QR Code Size constraint
|
5
|
+
module Chunking
|
6
|
+
extend self
|
7
|
+
MAX_SINGLE_JWS_SIZE = 1195
|
8
|
+
MAX_CHUNK_SIZE = 1191
|
9
|
+
|
10
|
+
def split_bundle(jws)
|
11
|
+
if jws.length <= MAX_SINGLE_JWS_SIZE
|
12
|
+
[jws]
|
13
|
+
else
|
14
|
+
chunk_count = (jws.length / MAX_CHUNK_SIZE.to_f).ceil
|
15
|
+
chunk_size = (jws.length / chunk_count.to_f).ceil
|
16
|
+
jws.scan(/.{1,#{chunk_size}}/)
|
17
|
+
end
|
18
|
+
end
|
19
|
+
|
20
|
+
# Splits jws into chunks and converts each string into numeric
|
21
|
+
def generate_qr_chunks(jws)
|
22
|
+
jws_chunks = split_bundle jws.to_s
|
23
|
+
jws_chunks.map { |c| convert_jws_to_numeric(c) }
|
24
|
+
end
|
25
|
+
|
26
|
+
# Assemble jws from qr code chunks
|
27
|
+
def assemble_jws(qr_chunks)
|
28
|
+
if qr_chunks.length == 1
|
29
|
+
# Strip off shc:/ and convert numeric jws
|
30
|
+
numeric_jws = qr_chunks[0].delete_prefix('shc:/')
|
31
|
+
convert_numeric_jws numeric_jws
|
32
|
+
else
|
33
|
+
ordered_qr_chunks = strip_prefix_and_sort qr_chunks
|
34
|
+
ordered_qr_chunks.map { |c| convert_numeric_jws(c) }.join
|
35
|
+
end
|
36
|
+
end
|
37
|
+
|
38
|
+
def get_payload_from_qr(qr_chunks)
|
39
|
+
jws = assemble_jws qr_chunks
|
40
|
+
|
41
|
+
# Get JWS payload, then decode and inflate
|
42
|
+
message = Base64.urlsafe_decode64 jws.split('.')[1]
|
43
|
+
JSON.parse(Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(message))
|
44
|
+
end
|
45
|
+
|
46
|
+
private
|
47
|
+
|
48
|
+
# Each character "c" of the jws is converted into a sequence of two digits by taking c.ord - 45
|
49
|
+
def convert_jws_to_numeric(jws)
|
50
|
+
jws.chars.map { |c| format('%02d', c.ord - 45) }.join
|
51
|
+
end
|
52
|
+
|
53
|
+
def convert_numeric_jws(numeric_jws)
|
54
|
+
result_jws = ''.dup
|
55
|
+
numeric_jws.chars.each_slice(2) do |a, b|
|
56
|
+
result_jws << ((a + b).to_i + 45).chr
|
57
|
+
end
|
58
|
+
result_jws
|
59
|
+
end
|
60
|
+
|
61
|
+
def strip_prefix_and_sort(qr_chunks)
|
62
|
+
# Multiple QR codes are prefixed with 'shc:/C/N' where C is the index and N is the total number of chunks
|
63
|
+
# Sorts chunks by C
|
64
|
+
sorted_chunks = qr_chunks.sort_by { |c| c[%r{/(.*?)/}, 1].to_i }
|
65
|
+
# Strip prefix
|
66
|
+
sorted_chunks.map { |c| c.sub(%r{shc:/(.*?)/(.*?)/}, '') }
|
67
|
+
end
|
68
|
+
end
|
69
|
+
end
|
@@ -0,0 +1,12 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module HealthCards
|
4
|
+
# Implements HealthCard for use with COVID Vaccination IG
|
5
|
+
class COVIDHealthCard < HealthCards::HealthCard
|
6
|
+
fhir_version '4.0.1'
|
7
|
+
additional_types 'https://smarthealth.cards#covid19'
|
8
|
+
|
9
|
+
allow FHIR::Patient, %w[name birthDate]
|
10
|
+
allow FHIR::Immunization, %w[status vaccineCode patient occurrenceDateTime]
|
11
|
+
end
|
12
|
+
end
|
@@ -0,0 +1,24 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'base64'
|
4
|
+
|
5
|
+
module HealthCards
|
6
|
+
# Encoding utilities for producing JWS
|
7
|
+
#
|
8
|
+
# @see https://datatracker.ietf.org/doc/html/rfc7515#appendix-A.3.1
|
9
|
+
module Encoding
|
10
|
+
# Encodes the provided data using url safe base64 without padding
|
11
|
+
# @param data [String] the data to be encoded
|
12
|
+
# @return [String] the encoded data
|
13
|
+
def encode(data)
|
14
|
+
Base64.urlsafe_encode64(data, padding: false).gsub("\n", '')
|
15
|
+
end
|
16
|
+
|
17
|
+
# Decodes the provided data using url safe base 64
|
18
|
+
# @param data [String] the data to be decoded
|
19
|
+
# @return [String] the decoded data
|
20
|
+
def decode(data)
|
21
|
+
Base64.urlsafe_decode64(data)
|
22
|
+
end
|
23
|
+
end
|
24
|
+
end
|
@@ -0,0 +1,45 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module HealthCards
|
4
|
+
# Exception thrown when a private key is expected or required
|
5
|
+
class MissingPrivateKey < StandardError
|
6
|
+
def initialize(msg = 'Missing private key')
|
7
|
+
super(msg)
|
8
|
+
end
|
9
|
+
end
|
10
|
+
|
11
|
+
# Exception thrown when a public key is expected or required
|
12
|
+
class MissingPublicKey < StandardError
|
13
|
+
def initialize(msg = 'Missing public key')
|
14
|
+
super(msg)
|
15
|
+
end
|
16
|
+
end
|
17
|
+
|
18
|
+
# Exception thrown when an invalid payload is provided
|
19
|
+
class InvalidPayloadException < ArgumentError
|
20
|
+
def initialize(msg = 'Bundle must be a FHIR::Bundle')
|
21
|
+
super(msg)
|
22
|
+
end
|
23
|
+
end
|
24
|
+
|
25
|
+
# Exception thrown when verifiable credential JSON does not include a locatable FHIR Bundle
|
26
|
+
class InvalidCredentialException < ArgumentError
|
27
|
+
def initialize(msg = 'Unable to locate FHIR Bundle in credential')
|
28
|
+
super(msg)
|
29
|
+
end
|
30
|
+
end
|
31
|
+
|
32
|
+
# Exception thrown when an invalid key (public or private) is provided
|
33
|
+
class InvalidKeyException < ArgumentError
|
34
|
+
def initialize(expected_class, actual_obj)
|
35
|
+
super("Expected an instance of #{expected_class} but was #{actual_obj.class}")
|
36
|
+
end
|
37
|
+
end
|
38
|
+
|
39
|
+
# Exception thrown when a reference in a bundle in unresolvable
|
40
|
+
class InvalidBundleReferenceException < ArgumentError
|
41
|
+
def initialize(url)
|
42
|
+
super("Unable to resolve url (#{url}) within bundle")
|
43
|
+
end
|
44
|
+
end
|
45
|
+
end
|
@@ -0,0 +1,23 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module HealthCards
|
4
|
+
# Converts a JWS to formats needed by endpoints (e.g. $issue-health-card, download and qr code)
|
5
|
+
module Exporter
|
6
|
+
extend Chunking
|
7
|
+
|
8
|
+
# Export JWS for file download
|
9
|
+
# @param [Array<JWS, String>] An array of JWS objects to be exported
|
10
|
+
# @return [String] JSON string containing file download contents
|
11
|
+
def self.download(jws)
|
12
|
+
{ verifiableCredential: jws.map(&:to_s) }.to_json
|
13
|
+
end
|
14
|
+
|
15
|
+
# Export JWS for $issue-health-card endpoint
|
16
|
+
# @param [Array<WJS, String] An array of JWS objects to be exported
|
17
|
+
# @return [String] JSON string containing a FHIR Parameters resource
|
18
|
+
def self.issue(jws)
|
19
|
+
params = jws.map { |j| FHIR::Parameters::Parameter.new(name: 'verifiableCredential', valueString: j) }
|
20
|
+
FHIR::Parameters.new(parameter: params).to_json
|
21
|
+
end
|
22
|
+
end
|
23
|
+
end
|
@@ -0,0 +1,223 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'json/minify'
|
4
|
+
require 'zlib'
|
5
|
+
|
6
|
+
module HealthCards
|
7
|
+
# A HealthCard which implements the credential claims specified by https://smarthealth.cards/
|
8
|
+
class HealthCard
|
9
|
+
VC_TYPE = [
|
10
|
+
'https://healthwallet.cards#health-card'
|
11
|
+
].freeze
|
12
|
+
|
13
|
+
attr_reader :issuer, :nbf, :bundle
|
14
|
+
|
15
|
+
class << self
|
16
|
+
# Creates a HealthCard from a JWS
|
17
|
+
# @param jws [String] the JWS string
|
18
|
+
# @param public_key [HealthCards::PublicKey] the public key associated with the JWS
|
19
|
+
# @param key [HealthCards::PrivateKey] the private key associated with the JWS
|
20
|
+
# @return [HealthCards::HealthCard]
|
21
|
+
def from_jws(jws, public_key: nil, key: nil)
|
22
|
+
jws = JWS.from_jws(jws, public_key: public_key, key: key)
|
23
|
+
from_payload(jws.payload)
|
24
|
+
end
|
25
|
+
|
26
|
+
# Create a HealthCard from a compressed payload
|
27
|
+
# @param payload [String]
|
28
|
+
# @return [HealthCards::HealthCard]
|
29
|
+
def from_payload(payload)
|
30
|
+
json = decompress_payload(payload)
|
31
|
+
bundle_hash = json.dig('vc', 'credentialSubject', 'fhirBundle')
|
32
|
+
|
33
|
+
raise HealthCards::InvalidCredentialException unless bundle_hash
|
34
|
+
|
35
|
+
bundle = FHIR::Bundle.new(bundle_hash)
|
36
|
+
new(issuer: json['iss'], bundle: bundle)
|
37
|
+
end
|
38
|
+
|
39
|
+
# Decompress an arbitrary payload, useful for debugging
|
40
|
+
# @param payload [String] compressed payload
|
41
|
+
# @return [Hash] Hash built from JSON contents of payload
|
42
|
+
def decompress_payload(payload)
|
43
|
+
inf = Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(payload)
|
44
|
+
JSON.parse(inf)
|
45
|
+
end
|
46
|
+
|
47
|
+
# Compress an arbitrary payload, useful for debugging
|
48
|
+
# @param payload [Object] Any object that responds to to_s
|
49
|
+
# @return A compressed version of that payload parameter
|
50
|
+
def compress_payload(payload)
|
51
|
+
Zlib::Deflate.new(nil, -Zlib::MAX_WBITS).deflate(payload.to_s, Zlib::FINISH)
|
52
|
+
end
|
53
|
+
|
54
|
+
# Define allowed attributes for this HealthCard class
|
55
|
+
# @param klass [Class] Scopes the attributes to a spefic class. Must be a subclass of FHIR::Model
|
56
|
+
# @param attributes [Array] An array of string with the attribute names that will be passed through
|
57
|
+
# when data is minimized
|
58
|
+
def allow(klass, attributes)
|
59
|
+
resource_type = klass.name.split('::').last
|
60
|
+
allowable[resource_type] = attributes
|
61
|
+
end
|
62
|
+
|
63
|
+
# Define allowed attributes for this HealthCard class
|
64
|
+
# @return [Hash] A hash of FHIR::Model subclasses and attributes that will pass through minimization
|
65
|
+
def allowable
|
66
|
+
@allowable ||= {}
|
67
|
+
end
|
68
|
+
|
69
|
+
# Sets/Gets the fhir version that will be passed through to the credential created by an instnace of
|
70
|
+
# this HealthCard (sub)class
|
71
|
+
# @param ver [String] FHIR Version supported by this HealthCard (sub)class. Leaving this param out
|
72
|
+
# will only return the current value
|
73
|
+
# value (used as a getter)
|
74
|
+
# @return [String] Current FHIR version supported
|
75
|
+
def fhir_version(ver = nil)
|
76
|
+
@fhir_version ||= ver unless ver.nil?
|
77
|
+
@fhir_version
|
78
|
+
end
|
79
|
+
|
80
|
+
# Additional type claims this HealthCard class supports
|
81
|
+
# @param types [String, Array] A string or array of string representing the additional type claims or nil
|
82
|
+
# if used as a getter
|
83
|
+
# @return [Array] the additional types added by this classes
|
84
|
+
def additional_types(*add_types)
|
85
|
+
types.concat(add_types) unless add_types.nil?
|
86
|
+
types - VC_TYPE
|
87
|
+
end
|
88
|
+
|
89
|
+
# Type claims supported by this HealthCard subclass
|
90
|
+
# @return [Array] an array of Strings with all the supported type claims
|
91
|
+
def types
|
92
|
+
@types ||= VC_TYPE.dup
|
93
|
+
end
|
94
|
+
|
95
|
+
# Check if this class supports the given type claim(s)
|
96
|
+
# @param type [Array, String] A type as defined by the SMART Health Cards framework
|
97
|
+
# @return [Boolean] Whether or not the type param is included in the types supported by the HealthCard (sub)class
|
98
|
+
def supports_type?(*type)
|
99
|
+
!types.intersection(type).empty?
|
100
|
+
end
|
101
|
+
end
|
102
|
+
|
103
|
+
# Create a HealthCard
|
104
|
+
#
|
105
|
+
# @param bundle [FHIR::Bundle] VerifiableCredential containing a fhir bundle
|
106
|
+
# @param issuer [String] The url from the Issuer of the HealthCard
|
107
|
+
def initialize(bundle:, issuer: nil)
|
108
|
+
raise InvalidPayloadException unless bundle.is_a?(FHIR::Bundle)
|
109
|
+
|
110
|
+
@issuer = issuer
|
111
|
+
@bundle = bundle
|
112
|
+
end
|
113
|
+
|
114
|
+
# A Hash matching the VC structure specified by https://smarthealth.cards/#health-cards-are-encoded-as-compact-serialization-json-web-signatures-jws
|
115
|
+
# @return [Hash]
|
116
|
+
def to_hash
|
117
|
+
{
|
118
|
+
iss: issuer,
|
119
|
+
nbf: Time.now.to_i,
|
120
|
+
vc: {
|
121
|
+
type: self.class.types,
|
122
|
+
credentialSubject: {
|
123
|
+
fhirVersion: self.class.fhir_version,
|
124
|
+
fhirBundle: strip_fhir_bundle
|
125
|
+
}
|
126
|
+
}
|
127
|
+
|
128
|
+
}
|
129
|
+
end
|
130
|
+
|
131
|
+
# A compressed version of the FHIR::Bundle based on the SMART Health Cards frame work and any other constraints
|
132
|
+
# defined by a subclass
|
133
|
+
# @return String compressed payload
|
134
|
+
def to_s
|
135
|
+
HealthCard.compress_payload(to_json)
|
136
|
+
end
|
137
|
+
|
138
|
+
# A minified JSON string matching the VC structure specified by https://smarthealth.cards/#health-cards-are-encoded-as-compact-serialization-json-web-signatures-jws
|
139
|
+
# @return [String] JSON string
|
140
|
+
def to_json(*_args)
|
141
|
+
JSON.minify(to_hash.to_json)
|
142
|
+
end
|
143
|
+
|
144
|
+
# Processes the bundle according to https://smarthealth.cards/#health-cards-are-small and returns
|
145
|
+
# a Hash with equivalent values
|
146
|
+
# @return [Hash] A hash with the same content as the FHIR::Bundle, processed accoding
|
147
|
+
# to SMART Health Cards framework and any constraints created by subclasses
|
148
|
+
def strip_fhir_bundle
|
149
|
+
stripped_bundle = @bundle.to_hash
|
150
|
+
if stripped_bundle.key?('entry') && !stripped_bundle['entry'].empty?
|
151
|
+
entries = stripped_bundle['entry']
|
152
|
+
entries, @url_map = redefine_uris(entries)
|
153
|
+
update_elements(entries)
|
154
|
+
end
|
155
|
+
stripped_bundle
|
156
|
+
end
|
157
|
+
|
158
|
+
private
|
159
|
+
|
160
|
+
def redefine_uris(entries)
|
161
|
+
url_map = {}
|
162
|
+
resource_count = 0
|
163
|
+
entries.each do |entry|
|
164
|
+
old_url = entry['fullUrl']
|
165
|
+
new_url = "resource:#{resource_count}"
|
166
|
+
url_map[old_url] = new_url
|
167
|
+
entry['fullUrl'] = new_url
|
168
|
+
resource_count += 1
|
169
|
+
end
|
170
|
+
[entries, url_map]
|
171
|
+
end
|
172
|
+
|
173
|
+
def update_elements(entries)
|
174
|
+
entries.each do |entry|
|
175
|
+
resource = entry['resource']
|
176
|
+
|
177
|
+
resource.delete('id')
|
178
|
+
resource.delete('text')
|
179
|
+
if resource.dig('meta', 'security')
|
180
|
+
resource['meta'] = resource['meta'].slice('security')
|
181
|
+
else
|
182
|
+
resource.delete('meta')
|
183
|
+
end
|
184
|
+
handle_allowable(resource)
|
185
|
+
update_nested_elements(resource)
|
186
|
+
end
|
187
|
+
end
|
188
|
+
|
189
|
+
def handle_allowable(resource)
|
190
|
+
allowable = self.class.allowable[resource['resourceType']]
|
191
|
+
return resource unless allowable
|
192
|
+
|
193
|
+
allow = allowable + ['resourceType']
|
194
|
+
resource.select! { |att| allow.include?(att) }
|
195
|
+
end
|
196
|
+
|
197
|
+
def process_url(url)
|
198
|
+
new_url = @url_map.key?(url) ? @url_map[url] : @url_map["#{issuer}/#{url}"]
|
199
|
+
raise InvalidBundleReferenceException, url unless new_url
|
200
|
+
|
201
|
+
new_url
|
202
|
+
end
|
203
|
+
|
204
|
+
def update_nested_elements(hash)
|
205
|
+
hash.map { |k, v| update_nested_element(hash, k, v) }
|
206
|
+
end
|
207
|
+
|
208
|
+
def update_nested_element(hash, attribute_name, value) # rubocop:disable Metrics/CyclomaticComplexity
|
209
|
+
case value
|
210
|
+
when String
|
211
|
+
hash[attribute_name] = process_url(value) if attribute_name == 'reference'
|
212
|
+
when Hash
|
213
|
+
value.delete('text') if attribute_name.include?('CodeableConcept') || value.key?('coding')
|
214
|
+
update_nested_elements(value)
|
215
|
+
when Array
|
216
|
+
value.each do |member_element|
|
217
|
+
member_element.delete('display') if attribute_name == 'coding'
|
218
|
+
update_nested_elements(member_element) if member_element.is_a?(Hash)
|
219
|
+
end
|
220
|
+
end
|
221
|
+
end
|
222
|
+
end
|
223
|
+
end
|
@@ -0,0 +1,25 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module HealthCards
|
4
|
+
# Converts a JWS to formats needed by endpoints (e.g. $issue-health-card, download and qr code)
|
5
|
+
module Importer
|
6
|
+
extend Chunking
|
7
|
+
|
8
|
+
# Import JWS from file upload
|
9
|
+
# @param [String] JSON string containing file upload contents
|
10
|
+
# @return [Array<JWS>] An array of JWS objects
|
11
|
+
def self.upload(jws_string)
|
12
|
+
vc = JSON.parse(jws_string)
|
13
|
+
vc_jws = vc['verifiableCredential']
|
14
|
+
vc_jws.map do |j|
|
15
|
+
jws = JWS.from_jws(j)
|
16
|
+
HealthCard.decompress_payload(jws.payload)
|
17
|
+
end
|
18
|
+
end
|
19
|
+
|
20
|
+
def self.scan(qr_contents)
|
21
|
+
contents = JSON.parse(qr_contents)
|
22
|
+
get_payload_from_qr contents
|
23
|
+
end
|
24
|
+
end
|
25
|
+
end
|
@@ -0,0 +1,60 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'fhir_models'
|
4
|
+
|
5
|
+
module HealthCards
|
6
|
+
# Issue Health Cards based on a stored private key
|
7
|
+
class Issuer
|
8
|
+
attr_reader :url, :key
|
9
|
+
|
10
|
+
# Create an Issuer
|
11
|
+
#
|
12
|
+
# @param key [HealthCards::PrivateKey] the private key used for signing issued health cards
|
13
|
+
def initialize(key:, url: nil)
|
14
|
+
@url = url
|
15
|
+
PrivateKey.enforce_valid_key_type!(key)
|
16
|
+
self.key = key
|
17
|
+
end
|
18
|
+
|
19
|
+
# Create a HealthCard from the supplied FHIR bundle
|
20
|
+
#
|
21
|
+
# @param bundle [FHIR::Bundle, String] the FHIR bundle used as the Health Card payload
|
22
|
+
# @return [HealthCard::]
|
23
|
+
def create_health_card(bundle, type: HealthCard)
|
24
|
+
type.new(issuer: url, bundle: bundle)
|
25
|
+
end
|
26
|
+
|
27
|
+
# Create a JWS for a given payload
|
28
|
+
#
|
29
|
+
# @param bundle [FHIR::Bundle] A FHIR::Bundle that will form the payload of the JWS object
|
30
|
+
# @param type [Class] A subclass of HealthCards::Card that processes the bundle according to a specific IG.
|
31
|
+
# Leave blank for default SMART Health Card behavior
|
32
|
+
# @return [HealthCards::JWS] An instance of JWS using the payload and signed by the issuer's private key
|
33
|
+
def issue_jws(bundle, type: HealthCard)
|
34
|
+
card = create_health_card(bundle, type: type)
|
35
|
+
JWS.new(header: jws_header, payload: card.to_s, key: key)
|
36
|
+
end
|
37
|
+
|
38
|
+
# Set the private key used for signing issued health cards
|
39
|
+
#
|
40
|
+
# @param key [HealthCards::PrivateKey, nil] the private key used for signing issued health cards
|
41
|
+
def key=(key)
|
42
|
+
PrivateKey.enforce_valid_key_type!(key)
|
43
|
+
|
44
|
+
@key = key
|
45
|
+
end
|
46
|
+
|
47
|
+
# Returns the public key matching this issuer's
|
48
|
+
# private key as a JWK KeySet JSON string useful for .well-known endpoints
|
49
|
+
# @return [String] JSON string in JWK standard
|
50
|
+
def to_jwk
|
51
|
+
KeySet.new(key.public_key).to_jwk
|
52
|
+
end
|
53
|
+
|
54
|
+
private
|
55
|
+
|
56
|
+
def jws_header
|
57
|
+
{ 'zip' => 'DEF', 'alg' => 'ES256', 'kid' => key.public_key.kid }
|
58
|
+
end
|
59
|
+
end
|
60
|
+
end
|
@@ -0,0 +1,124 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module HealthCards
|
4
|
+
# Create JWS from a payload
|
5
|
+
class JWS
|
6
|
+
class << self
|
7
|
+
include Encoding
|
8
|
+
|
9
|
+
# Creates a Card from a JWS
|
10
|
+
# @param jws [String, HealthCards::JWS] the JWS string
|
11
|
+
# @param public_key [HealthCards::PublicKey] the public key associated with the JWS
|
12
|
+
# @param key [HealthCards::PrivateKey] the private key associated with the JWS
|
13
|
+
# @return [HealthCards::HealthCard]
|
14
|
+
def from_jws(jws, public_key: nil, key: nil)
|
15
|
+
unless jws.is_a?(HealthCards::JWS) || jws.is_a?(String)
|
16
|
+
raise ArgumentError,
|
17
|
+
'Expected either a HealthCards::JWS or String'
|
18
|
+
end
|
19
|
+
|
20
|
+
header, payload, signature = jws.to_s.split('.').map { |entry| decode(entry) }
|
21
|
+
header = JSON.parse(header)
|
22
|
+
JWS.new(header: header, payload: payload, signature: signature,
|
23
|
+
public_key: public_key, key: key)
|
24
|
+
end
|
25
|
+
end
|
26
|
+
|
27
|
+
attr_reader :key, :public_key, :payload
|
28
|
+
attr_writer :signature
|
29
|
+
attr_accessor :header
|
30
|
+
|
31
|
+
# Create a new JWS
|
32
|
+
|
33
|
+
def initialize(header: nil, payload: nil, signature: nil, key: nil, public_key: nil)
|
34
|
+
# Not using accessors because they reset the signature which requires both a key and a payload
|
35
|
+
@header = header
|
36
|
+
@payload = payload
|
37
|
+
@signature = signature if signature
|
38
|
+
@key = key
|
39
|
+
@public_key = public_key || key&.public_key
|
40
|
+
end
|
41
|
+
|
42
|
+
# The kid value from the JWS header, used to identify the key to use to verify
|
43
|
+
# @return [String]
|
44
|
+
def kid
|
45
|
+
header['kid']
|
46
|
+
end
|
47
|
+
|
48
|
+
# Set the private key used for signing issued health cards
|
49
|
+
#
|
50
|
+
# @param key [HealthCards::PrivateKey, nil] the private key used for signing issued health cards
|
51
|
+
def key=(key)
|
52
|
+
PrivateKey.enforce_valid_key_type!(key, allow_nil: true)
|
53
|
+
|
54
|
+
@key = key
|
55
|
+
|
56
|
+
# If it's a new private key then the public key and signature should be updated
|
57
|
+
return if @key.nil?
|
58
|
+
|
59
|
+
reset_signature
|
60
|
+
self.public_key = @key.public_key
|
61
|
+
end
|
62
|
+
|
63
|
+
# Set the public key used for signing issued health cards
|
64
|
+
#
|
65
|
+
# @param public_key [HealthCards::PublicKey, nil] the private key used for signing issued health cards
|
66
|
+
def public_key=(public_key)
|
67
|
+
PublicKey.enforce_valid_key_type!(public_key, allow_nil: true)
|
68
|
+
|
69
|
+
@public_key = public_key
|
70
|
+
end
|
71
|
+
|
72
|
+
# Set the JWS payload. Setting a new payload will result in the a new signature
|
73
|
+
# @param new_payload [Object]
|
74
|
+
def payload=(new_payload)
|
75
|
+
@payload = new_payload
|
76
|
+
reset_signature
|
77
|
+
end
|
78
|
+
|
79
|
+
# The signature component of the card
|
80
|
+
#
|
81
|
+
# @return [String] the unencoded signature
|
82
|
+
def signature
|
83
|
+
return @signature if @signature
|
84
|
+
|
85
|
+
raise MissingPrivateKey unless key
|
86
|
+
|
87
|
+
@signature ||= key.sign(jws_signing_input)
|
88
|
+
end
|
89
|
+
|
90
|
+
# Export the card to a JWS String
|
91
|
+
# @return [String] the JWS
|
92
|
+
def to_s
|
93
|
+
[JSON.generate(header), payload, signature].map { |entry| JWS.encode(entry) }.join('.')
|
94
|
+
end
|
95
|
+
|
96
|
+
# Verify the digital signature on the jws
|
97
|
+
#
|
98
|
+
# @return [Boolean]
|
99
|
+
def verify
|
100
|
+
raise MissingPublicKey unless public_key
|
101
|
+
|
102
|
+
public_key.verify(jws_signing_input, signature)
|
103
|
+
end
|
104
|
+
|
105
|
+
private
|
106
|
+
|
107
|
+
def jws_signing_input
|
108
|
+
"#{JWS.encode(@header.to_json)}.#{encoded_payload}"
|
109
|
+
end
|
110
|
+
|
111
|
+
def encoded_payload
|
112
|
+
JWS.encode(payload)
|
113
|
+
end
|
114
|
+
|
115
|
+
# Resets the signature
|
116
|
+
#
|
117
|
+
# This method is primarily used when an attribute that affects
|
118
|
+
# the signature is changed (e.g. the private key changes, the payload changes)
|
119
|
+
def reset_signature
|
120
|
+
@signature = nil
|
121
|
+
signature if key && payload
|
122
|
+
end
|
123
|
+
end
|
124
|
+
end
|
@@ -0,0 +1,69 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'openssl'
|
4
|
+
require 'base64'
|
5
|
+
|
6
|
+
module HealthCards
|
7
|
+
# Methods to generate signing keys and jwk
|
8
|
+
class Key
|
9
|
+
BASE = { kty: 'EC', crv: 'P-256' }.freeze
|
10
|
+
DIGEST = OpenSSL::Digest.new('SHA256')
|
11
|
+
|
12
|
+
# Checks if obj is the the correct key type or nil
|
13
|
+
# @param obj Object that should be of same type as caller or nil
|
14
|
+
# @param allow_nil Allow/Disallow key to be nil
|
15
|
+
def self.enforce_valid_key_type!(obj, allow_nil: false)
|
16
|
+
raise InvalidKeyException.new(self, obj) unless obj.is_a?(self) || (allow_nil && obj.nil?)
|
17
|
+
end
|
18
|
+
|
19
|
+
# Create a key from a JWK
|
20
|
+
#
|
21
|
+
# @param jwk_key [Hash] The JWK represented by a Hash
|
22
|
+
# @return [HealthCards::Key] The key represented by the JWK
|
23
|
+
def self.from_jwk(jwk_key)
|
24
|
+
jwk_key = jwk_key.transform_keys(&:to_sym)
|
25
|
+
group = OpenSSL::PKey::EC::Group.new('prime256v1')
|
26
|
+
key = OpenSSL::PKey::EC.new(group)
|
27
|
+
key.private_key = OpenSSL::BN.new(Base64.urlsafe_decode64(jwk_key[:d]), 2) if jwk_key[:d]
|
28
|
+
public_key_bn = ['04'].pack('H*') + Base64.urlsafe_decode64(jwk_key[:x]) + Base64.urlsafe_decode64(jwk_key[:y])
|
29
|
+
key.public_key = OpenSSL::PKey::EC::Point.new(group, OpenSSL::BN.new(public_key_bn, 2))
|
30
|
+
key.private_key? ? HealthCards::PrivateKey.new(key) : HealthCards::PublicKey.new(key)
|
31
|
+
end
|
32
|
+
|
33
|
+
def initialize(ec_key)
|
34
|
+
@key = ec_key
|
35
|
+
end
|
36
|
+
|
37
|
+
def group
|
38
|
+
@key.group
|
39
|
+
end
|
40
|
+
|
41
|
+
def to_json(*_args)
|
42
|
+
to_jwk.to_json
|
43
|
+
end
|
44
|
+
|
45
|
+
def to_jwk
|
46
|
+
coordinates.merge(kid: kid, use: 'sig', alg: 'ES256')
|
47
|
+
end
|
48
|
+
|
49
|
+
def kid
|
50
|
+
Base64.urlsafe_encode64(DIGEST.digest(public_coordinates.to_json), padding: false)
|
51
|
+
end
|
52
|
+
|
53
|
+
def public_coordinates
|
54
|
+
coordinates.slice(:crv, :kty, :x, :y)
|
55
|
+
end
|
56
|
+
|
57
|
+
def coordinates
|
58
|
+
return @coordinates if @coordinates
|
59
|
+
|
60
|
+
key_binary = @key.public_key.to_bn.to_s(2)
|
61
|
+
coords = { x: key_binary[1, key_binary.length / 2],
|
62
|
+
y: key_binary[key_binary.length / 2 + 1, key_binary.length] }
|
63
|
+
coords[:d] = @key.private_key.to_s(2) if @key.private_key?
|
64
|
+
@coordinates = coords.transform_values do |val|
|
65
|
+
Base64.urlsafe_encode64(val, padding: false)
|
66
|
+
end.merge(BASE)
|
67
|
+
end
|
68
|
+
end
|
69
|
+
end
|
@@ -0,0 +1,86 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'forwardable'
|
4
|
+
|
5
|
+
module HealthCards
|
6
|
+
# A set of keys used for signing or verifying HealthCards
|
7
|
+
class KeySet
|
8
|
+
extend Forwardable
|
9
|
+
|
10
|
+
def_delegator :keys, :empty?
|
11
|
+
|
12
|
+
# Create a KeySet from a JWKS
|
13
|
+
#
|
14
|
+
# @param jwks [String] the JWKS as a string
|
15
|
+
# @return [HealthCards::KeySet]
|
16
|
+
def self.from_jwks(jwks)
|
17
|
+
jwks = JSON.parse(jwks)
|
18
|
+
keys = jwks['keys'].map { |jwk| HealthCards::Key.from_jwk(jwk) }
|
19
|
+
KeySet.new(keys)
|
20
|
+
end
|
21
|
+
|
22
|
+
# Create a new KeySet
|
23
|
+
#
|
24
|
+
# @param keys [HealthCards::Key, Array<HealthCards::Key>, nil] the initial keys
|
25
|
+
def initialize(keys = nil)
|
26
|
+
@key_map = {}
|
27
|
+
add_keys(keys) unless keys.nil?
|
28
|
+
end
|
29
|
+
|
30
|
+
# The contained keys
|
31
|
+
#
|
32
|
+
# @return [Array]
|
33
|
+
def keys
|
34
|
+
@key_map.values
|
35
|
+
end
|
36
|
+
|
37
|
+
# Returns the keys as a JWK
|
38
|
+
#
|
39
|
+
# @return JSON string in JWK format
|
40
|
+
def to_jwk
|
41
|
+
{ keys: keys.map(&:to_jwk) }.to_json
|
42
|
+
end
|
43
|
+
|
44
|
+
# Retrieves a key from the keyset with a kid
|
45
|
+
# that matches the parameter
|
46
|
+
# @param kid [String] a Base64 encoded kid from a JWS or Key
|
47
|
+
# @return [HealthCard::Key] a key with a matching kid or nil if not found
|
48
|
+
def find_key(kid)
|
49
|
+
@key_map[kid]
|
50
|
+
end
|
51
|
+
|
52
|
+
# Add keys to KeySet
|
53
|
+
#
|
54
|
+
# Keys are added based on the key kid
|
55
|
+
#
|
56
|
+
# @param new_keys [HealthCards::Key, Array<HealthCards::Key>, HealthCards::KeySet] the initial keys
|
57
|
+
def add_keys(new_keys)
|
58
|
+
if new_keys.is_a? KeySet
|
59
|
+
add_keys(new_keys.keys)
|
60
|
+
else
|
61
|
+
[*new_keys].each { |new_key| @key_map[new_key.kid] = new_key }
|
62
|
+
end
|
63
|
+
end
|
64
|
+
|
65
|
+
# Remove keys from KeySet
|
66
|
+
#
|
67
|
+
# Keys are remove based on the key kid
|
68
|
+
#
|
69
|
+
# @param new_keys [HealthCards::Key, Array<HealthCards::Key>, HealthCards::KeySet] the initial keys
|
70
|
+
def remove_keys(removed_keys)
|
71
|
+
if removed_keys.is_a? KeySet
|
72
|
+
remove_keys(removed_keys.keys)
|
73
|
+
else
|
74
|
+
[*removed_keys].each { |removed_key| @key_map.delete(removed_key.kid) }
|
75
|
+
end
|
76
|
+
end
|
77
|
+
|
78
|
+
# Check if key is included in the KeySet
|
79
|
+
#
|
80
|
+
# @param key [HealthCards::Key]
|
81
|
+
# @return [Boolean]
|
82
|
+
def include?(key)
|
83
|
+
!@key_map[key.kid].nil?
|
84
|
+
end
|
85
|
+
end
|
86
|
+
end
|
@@ -0,0 +1,50 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module HealthCards
|
4
|
+
# A key used for signing JWS
|
5
|
+
class PrivateKey < Key
|
6
|
+
def self.from_file(path)
|
7
|
+
pem = OpenSSL::PKey::EC.new(File.read(path))
|
8
|
+
PrivateKey.new(pem)
|
9
|
+
end
|
10
|
+
|
11
|
+
def self.load_from_or_create_from_file(path)
|
12
|
+
if File.exist?(path)
|
13
|
+
from_file(path)
|
14
|
+
else
|
15
|
+
generate_key(file_path: path)
|
16
|
+
end
|
17
|
+
end
|
18
|
+
|
19
|
+
def self.generate_key(file_path: nil)
|
20
|
+
key = OpenSSL::PKey::EC.generate('prime256v1')
|
21
|
+
File.write(file_path, key.to_pem) if file_path
|
22
|
+
PrivateKey.new(key)
|
23
|
+
end
|
24
|
+
|
25
|
+
def sign(payload)
|
26
|
+
asn1_to_raw(@key.sign(OpenSSL::Digest.new('SHA256'), payload), self)
|
27
|
+
end
|
28
|
+
|
29
|
+
def public_key
|
30
|
+
return @public_key if @public_key
|
31
|
+
|
32
|
+
pub = OpenSSL::PKey::EC.new('prime256v1')
|
33
|
+
pub.public_key = @key.public_key
|
34
|
+
@public_key = PublicKey.new(pub)
|
35
|
+
end
|
36
|
+
|
37
|
+
private
|
38
|
+
|
39
|
+
# Convert the ASN.1 Representation into the raw signature
|
40
|
+
#
|
41
|
+
# Adapted from ruby-jwt and json-jwt gems. More info here:
|
42
|
+
# https://github.com/nov/json-jwt/issues/21
|
43
|
+
# https://github.com/jwt/ruby-jwt/pull/87
|
44
|
+
# https://github.com/jwt/ruby-jwt/issues/84
|
45
|
+
def asn1_to_raw(signature, private_key)
|
46
|
+
byte_size = (private_key.group.degree + 7) / 8
|
47
|
+
OpenSSL::ASN1.decode(signature).value.map { |value| value.value.to_s(2).rjust(byte_size, "\x00") }.join
|
48
|
+
end
|
49
|
+
end
|
50
|
+
end
|
@@ -0,0 +1,31 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module HealthCards
|
4
|
+
# A key used for verifying JWS
|
5
|
+
class PublicKey < Key
|
6
|
+
def self.from_json(json)
|
7
|
+
# TODO
|
8
|
+
end
|
9
|
+
|
10
|
+
def verify(payload, signature)
|
11
|
+
@key.verify(OpenSSL::Digest.new('SHA256'), raw_to_asn1(signature, self), payload)
|
12
|
+
end
|
13
|
+
|
14
|
+
private
|
15
|
+
|
16
|
+
# Convert the raw signature into the ASN.1 Representation
|
17
|
+
#
|
18
|
+
# Adapted from ruby-jwt and json-jwt gems. More info here:
|
19
|
+
# https://github.com/nov/json-jwt/issues/21
|
20
|
+
# https://github.com/jwt/ruby-jwt/pull/87
|
21
|
+
# https://github.com/jwt/ruby-jwt/issues/84
|
22
|
+
def raw_to_asn1(signature, key)
|
23
|
+
byte_size = (key.group.degree + 7) / 8
|
24
|
+
sig_bytes = signature[0..(byte_size - 1)]
|
25
|
+
sig_char = signature[byte_size..] || ''
|
26
|
+
OpenSSL::ASN1::Sequence.new([sig_bytes, sig_char].map do |int|
|
27
|
+
OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(int, 2))
|
28
|
+
end).to_der
|
29
|
+
end
|
30
|
+
end
|
31
|
+
end
|
@@ -0,0 +1,32 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module HealthCards
|
4
|
+
# Logic for verifying a HealthCard JWS
|
5
|
+
module Verification
|
6
|
+
# Verify Health Card with given KeySet
|
7
|
+
#
|
8
|
+
# @param verifiable [HealthCards::JWS, String] the health card to verify
|
9
|
+
# @param key_set [HealthCards::KeySet, nil] the KeySet from which keys should be taken or added
|
10
|
+
# @param resolve_keys [Boolean] if keys should be resolved
|
11
|
+
# @return [Boolean]
|
12
|
+
def verify_using_key_set(verifiable, key_set = nil, resolve_keys: true)
|
13
|
+
jws = JWS.from_jws(verifiable)
|
14
|
+
key_set ||= HealthCards::KeySet.new
|
15
|
+
key_set.add_keys(resolve_key(jws)) if resolve_keys && key_set.find_key(jws.kid).nil?
|
16
|
+
|
17
|
+
key = key_set.find_key(jws.kid)
|
18
|
+
raise MissingPublicKey, 'Verifier does not contain public key that is able to verify this signature' unless key
|
19
|
+
|
20
|
+
jws.public_key = key
|
21
|
+
jws.verify
|
22
|
+
end
|
23
|
+
|
24
|
+
# Resolve a key
|
25
|
+
# @param jws [HealthCards::JWS, String] The JWS for which to resolve keys
|
26
|
+
# @return [HealthCards::KeySet]
|
27
|
+
def resolve_key(jws)
|
28
|
+
res = Net::HTTP.get(URI("#{HealthCard.from_jws(jws.to_s).issuer}/.well-known/jwks.json"))
|
29
|
+
HealthCards::KeySet.from_jwks(res)
|
30
|
+
end
|
31
|
+
end
|
32
|
+
end
|
@@ -0,0 +1,68 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'net/http'
|
4
|
+
require_relative 'verification'
|
5
|
+
|
6
|
+
module HealthCards
|
7
|
+
# Verifiers can validate HealthCards using public keys
|
8
|
+
class Verifier
|
9
|
+
attr_reader :keys
|
10
|
+
attr_accessor :resolve_keys
|
11
|
+
|
12
|
+
include HealthCards::Verification
|
13
|
+
extend HealthCards::Verification
|
14
|
+
|
15
|
+
# Verify a HealthCard
|
16
|
+
#
|
17
|
+
# This method _always_ uses key resolution and does not depend on any cached keys
|
18
|
+
#
|
19
|
+
# @param verifiable [HealthCards::JWS, String] the health card to verify
|
20
|
+
# @return [Boolean]
|
21
|
+
def self.verify(verifiable)
|
22
|
+
verify_using_key_set(verifiable)
|
23
|
+
end
|
24
|
+
|
25
|
+
# Create a new Verifier
|
26
|
+
#
|
27
|
+
# @param keys [HealthCards::KeySet, HealthCards::Key, nil] keys to use when verifying Health Cards
|
28
|
+
# @param resolve_keys [Boolean] Enables or disables key resolution
|
29
|
+
def initialize(keys: nil, resolve_keys: true)
|
30
|
+
@keys = case keys
|
31
|
+
when KeySet
|
32
|
+
keys
|
33
|
+
when Key
|
34
|
+
KeySet.new(keys)
|
35
|
+
else
|
36
|
+
KeySet.new
|
37
|
+
end
|
38
|
+
|
39
|
+
self.resolve_keys = resolve_keys
|
40
|
+
end
|
41
|
+
|
42
|
+
# Add a key to use when verifying
|
43
|
+
#
|
44
|
+
# @param key [HealthCards::Key, HealthCards::KeySet] the key to add
|
45
|
+
def add_keys(key)
|
46
|
+
@keys.add_keys(key)
|
47
|
+
end
|
48
|
+
|
49
|
+
# Remove a key to use when verifying
|
50
|
+
#
|
51
|
+
# @param key [HealthCards::Key] the key to remove
|
52
|
+
def remove_keys(key)
|
53
|
+
@keys.remove_keys(key)
|
54
|
+
end
|
55
|
+
|
56
|
+
# Verify a HealthCard
|
57
|
+
#
|
58
|
+
# @param verifiable [HealthCards::JWS, String] the health card to verify
|
59
|
+
# @return [Boolean]
|
60
|
+
def verify(verifiable)
|
61
|
+
verify_using_key_set(verifiable, keys, resolve_keys: resolve_keys?)
|
62
|
+
end
|
63
|
+
|
64
|
+
def resolve_keys?
|
65
|
+
resolve_keys
|
66
|
+
end
|
67
|
+
end
|
68
|
+
end
|
metadata
ADDED
@@ -0,0 +1,92 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: health_cards
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.0.1
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Reece Adamson
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2021-05-14 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: fhir_models
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - ">="
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '0'
|
20
|
+
type: :runtime
|
21
|
+
prerelease: false
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
23
|
+
requirements:
|
24
|
+
- - ">="
|
25
|
+
- !ruby/object:Gem::Version
|
26
|
+
version: '0'
|
27
|
+
- !ruby/object:Gem::Dependency
|
28
|
+
name: json-minify
|
29
|
+
requirement: !ruby/object:Gem::Requirement
|
30
|
+
requirements:
|
31
|
+
- - ">="
|
32
|
+
- !ruby/object:Gem::Version
|
33
|
+
version: '0'
|
34
|
+
type: :runtime
|
35
|
+
prerelease: false
|
36
|
+
version_requirements: !ruby/object:Gem::Requirement
|
37
|
+
requirements:
|
38
|
+
- - ">="
|
39
|
+
- !ruby/object:Gem::Version
|
40
|
+
version: '0'
|
41
|
+
description: Create SMART Health Cards
|
42
|
+
email:
|
43
|
+
- radamson@mitre.org
|
44
|
+
executables: []
|
45
|
+
extensions: []
|
46
|
+
extra_rdoc_files: []
|
47
|
+
files:
|
48
|
+
- LICENSE.txt
|
49
|
+
- lib/health_cards.rb
|
50
|
+
- lib/health_cards/chunking.rb
|
51
|
+
- lib/health_cards/covid_health_card.rb
|
52
|
+
- lib/health_cards/encoding.rb
|
53
|
+
- lib/health_cards/exceptions.rb
|
54
|
+
- lib/health_cards/exporter.rb
|
55
|
+
- lib/health_cards/health_card.rb
|
56
|
+
- lib/health_cards/importer.rb
|
57
|
+
- lib/health_cards/issuer.rb
|
58
|
+
- lib/health_cards/jws.rb
|
59
|
+
- lib/health_cards/key.rb
|
60
|
+
- lib/health_cards/key_set.rb
|
61
|
+
- lib/health_cards/private_key.rb
|
62
|
+
- lib/health_cards/public_key.rb
|
63
|
+
- lib/health_cards/verification.rb
|
64
|
+
- lib/health_cards/verifier.rb
|
65
|
+
- lib/health_cards/version.rb
|
66
|
+
homepage: https://github.com/dvci/health-cards
|
67
|
+
licenses:
|
68
|
+
- Apache 2.0
|
69
|
+
metadata:
|
70
|
+
homepage_uri: https://github.com/dvci/health-cards
|
71
|
+
source_code_uri: https://github.com/dvci/health_cards
|
72
|
+
changelog_uri: https://github.com/dvci/health_cards/CHANGELOG.md
|
73
|
+
post_install_message:
|
74
|
+
rdoc_options: []
|
75
|
+
require_paths:
|
76
|
+
- lib
|
77
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
78
|
+
requirements:
|
79
|
+
- - ">="
|
80
|
+
- !ruby/object:Gem::Version
|
81
|
+
version: 2.7.0
|
82
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
83
|
+
requirements:
|
84
|
+
- - ">="
|
85
|
+
- !ruby/object:Gem::Version
|
86
|
+
version: '0'
|
87
|
+
requirements: []
|
88
|
+
rubygems_version: 3.2.15
|
89
|
+
signing_key:
|
90
|
+
specification_version: 4
|
91
|
+
summary: Create SMART Health Cards
|
92
|
+
test_files: []
|