/
signer.ex
275 lines (220 loc) · 9.49 KB
/
signer.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
defmodule Joken.Signer do
@moduledoc """
Interface between Joken and JOSE for signing and verifying tokens.
In the future we plan to keep this interface but make it pluggable for other crypto
implementations like using only standard `:crypto` and `:public_key` modules. So,
**avoid** depending on the inner structure of this module.
"""
alias JOSE.{JWK, JWS, JWT}
@hs_algorithms ["HS256", "HS384", "HS512"]
@rs_algorithms ["RS256", "RS384", "RS512"]
@es_algorithms ["ES256", "ES384", "ES512"]
@ps_algorithms ["PS256", "PS384", "PS512"]
@eddsa_algorithms ["Ed25519", "Ed25519ph", "Ed448", "Ed448ph", "EdDSA"]
@map_key_algorithms @rs_algorithms ++ @es_algorithms ++ @ps_algorithms ++ @eddsa_algorithms
@algorithms @hs_algorithms ++ @map_key_algorithms
@typedoc "A key may be an octet or a map with parameters according to JWK (JSON Web Key)"
@type key :: binary() | map()
@typedoc """
A `Joken.Signer` instance is a JWS (JSON Web Signature) and JWK (JSON Web Key) struct.
It also contains an `alg` field for performance reasons.
"""
@type t :: %__MODULE__{
jwk: JWK.t() | nil,
jws: JWS.t() | nil,
alg: binary() | nil
}
defstruct jwk: nil, jws: nil, alg: nil
@doc """
All supported algorithms.
"""
@spec algorithms() :: [binary()]
def algorithms, do: @algorithms
@doc """
Map key algorithms.
"""
@spec map_key_algorithms() :: [binary()]
def map_key_algorithms, do: @map_key_algorithms
@doc """
Creates a new Joken.Signer struct. Can accept either a binary for HS*** algorithms
or a map with arguments for the other kinds of keys. Also, accepts an optional map
that will be passed as extra header arguments for generated JWT tokens.
## Example
iex> Joken.Signer.create("HS256", "s3cret")
%Joken.Signer{
alg: "HS256",
jwk: %JOSE.JWK{
fields: %{},
keys: :undefined,
kty: {:jose_jwk_kty_oct, "s3cret"}
},
jws: %JOSE.JWS{
alg: {:jose_jws_alg_hmac, :HS256},
b64: :undefined,
fields: %{"typ" => "JWT"}
}
}
"""
@spec create(binary(), key(), %{binary() => term()}) :: __MODULE__.t()
def create(alg, key, jose_extra_headers \\ %{})
def create(alg, secret, headers) when is_binary(secret) and alg in @hs_algorithms do
raw_create(
alg,
headers |> transform_headers(alg) |> JWS.from_map(),
JWK.from_oct(secret)
)
end
def create(alg, _key, _headers) when alg in @hs_algorithms,
do: raise(Joken.Error, :algorithm_needs_binary_key)
def create(alg, %{"pem" => pem, "passphrase" => passphrase}, headers)
when alg in @map_key_algorithms do
raw_create(
alg,
headers |> transform_headers(alg) |> JWS.from_map(),
JWK.from_pem(passphrase, pem)
)
end
def create(alg, %{"pem" => pem}, headers) when alg in @map_key_algorithms do
raw_create(
alg,
headers |> transform_headers(alg) |> JWS.from_map(),
JWK.from_pem(pem)
)
end
def create(alg, key, headers) when is_map(key) and alg in @map_key_algorithms do
raw_create(
alg,
headers |> transform_headers(alg) |> JWS.from_map(),
JWK.from_map(key)
)
end
def create(alg, _key, _headers) when alg in @map_key_algorithms,
do: raise(Joken.Error, :algorithm_needs_key)
def create(_, _, _), do: raise(Joken.Error, :unrecognized_algorithm)
defp raw_create(alg, jws, jwk) do
%__MODULE__{
jws: jws,
jwk: jwk,
alg: alg
}
end
@doc """
Signs a map of claims with the given Joken.Signer.
## Examples
iex> Joken.Signer.sign(%{"name" => "John Doe"}, Joken.Signer.create("HS256", "secret"))
{:ok, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.xuEv8qrfXu424LZk8bVgr9MQJUIrp1rHcPyZw_KSsds"}
iex> Joken.Signer.sign(%{"name" => "John Doe"}, Joken.Signer.parse_config(:rs256))
{:ok, "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.e3hyn_oaaA2lxMlqH1UPo8STN-a_sszl8B2_s6tY9aT_YBAmfd7BXJOPsOMl7x2wXeKMQaNBVjna2tA0UiO_m3SpwiYgoTcU65D6OgkzugmLD_DhjDK1YCOKlm7So1uhbkb_QCuo4Ij5scsQqwv7hkxo4IximGBeH9LAvPhPTaGmYJMI7_tWIld2TlY6tNUQP4n0qctXsI3hjvGzdvuQW-tRnzAQCC4TYe-mJgFa033NSHeiX-sZB-SuYlWi7DJqDTiwlb_beVdqWpxxtFDA005Iw6FZTpH9Rs1LVwJU5t3RN5iWB-z4ZI-kKsGUGLNrAZ7btV6Ow2FMAdj9TXmNpQ"}
"""
@spec sign(Joken.claims(), __MODULE__.t()) ::
{:ok, Joken.bearer_token()} | {:error, Joken.error_reason()}
def sign(claims, %__MODULE__{alg: _, jwk: jwk, jws: %JWS{alg: {alg, _}} = jws})
when is_map(claims) do
with result = {%{alg: ^alg}, _} <- JWT.sign(jwk, jws, claims),
{_, compacted_token} <- JWS.compact(result) do
{:ok, compacted_token}
end
end
@doc """
Verifies the given token's signature with the given `Joken.Signer`.
## Examples
iex> Joken.Signer.verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.xuEv8qrfXu424LZk8bVgr9MQJUIrp1rHcPyZw_KSsds", Joken.Signer.create("HS256", "secret"))
{:ok, %{"name" => "John Doe"}}
iex> Joken.Signer.verify("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.e3hyn_oaaA2lxMlqH1UPo8STN-a_sszl8B2_s6tY9aT_YBAmfd7BXJOPsOMl7x2wXeKMQaNBVjna2tA0UiO_m3SpwiYgoTcU65D6OgkzugmLD_DhjDK1YCOKlm7So1uhbkb_QCuo4Ij5scsQqwv7hkxo4IximGBeH9LAvPhPTaGmYJMI7_tWIld2TlY6tNUQP4n0qctXsI3hjvGzdvuQW-tRnzAQCC4TYe-mJgFa033NSHeiX-sZB-SuYlWi7DJqDTiwlb_beVdqWpxxtFDA005Iw6FZTpH9Rs1LVwJU5t3RN5iWB-z4ZI-kKsGUGLNrAZ7btV6Ow2FMAdj9TXmNpQ", Joken.Signer.parse_config(:rs256))
{:ok, %{"name" => "John Doe"}}
"""
@spec verify(Joken.bearer_token(), %__MODULE__{}) ::
{:ok, Joken.claims()} | {:error, Joken.error_reason()}
def verify(token, %__MODULE__{alg: alg, jwk: jwk}) when is_binary(token) do
case JWT.verify_strict(jwk, [alg], token) do
{true, %JWT{fields: claims}, _} -> {:ok, claims}
_ -> {:error, :signature_error}
end
end
@doc """
Generates a `Joken.Signer` from Joken's application configuration.
A `Joken.Signer` has an algorithm (one of #{inspect(@algorithms)}) and a key.
There are several types of keys used by JWTs algorithms:
- RSA
- Elliptic Curve
- Octet (binary)
- So on...
Also, they can be encoded in several ways:
- Raw (map of parameters)
- PEM (Privacy Enhanced Mail format)
- Open SSH encoding
- So on...
To ease configuring these types of keys used by JWTs algorithms, Joken accepts a few
parameters in its configuration:
- `:signer_alg` : one of #{inspect(@algorithms)}.
- `:key_pem` : a binary containing a key in PEM encoding format.
- `:key_openssh` : a binary containing a key in Open SSH encoding format.
- `:key_map` : a map with the raw parameters.
- `:key_octet` : a binary used as the password for HS algorithms only.
## Examples
config :joken,
hs256: [
signer_alg: "HS256",
key_octet: "test"
]
config :joken,
rs256: [
signer_alg: "RS256",
key_pem: \"\"\"
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDdlatRjRjogo3WojgGHFHYLugdUWAY9iR3fy4arWNA1KoS8kVw33cJibXr8bvwUAUparCwlvdbH6dvEOfou0/gCFQsHUfQrSDv+MuSUMAe8jzKE4qW+jK+xQU9a03GUnKHkkle+Q0pX/g6jXZ7r1/xAK5Do2kQ+X5xK9cipRgEKwIDAQABAoGAD+onAtVye4ic7VR7V50DF9bOnwRwNXrARcDhq9LWNRrRGElESYYTQ6EbatXS3MCyjjX2eMhu/aF5YhXBwkppwxg+EOmXeh+MzL7Zh284OuPbkglAaGhV9bb6/5CpuGb1esyPbYW+Ty2PC0GSZfIXkXs76jXAu9TOBvD0ybc2YlkCQQDywg2R/7t3Q2OE2+yo382CLJdrlSLVROWKwb4tb2PjhY4XAwV8d1vy0RenxTB+K5Mu57uVSTHtrMK0GAtFr833AkEA6avx20OHo61Yela/4k5kQDtjEf1N0LfI+BcWZtxsS3jDM3i1Hp0KSu5rsCPb8acJo5RO26gGVrfAsDcIXKC+bQJAZZ2XIpsitLyPpuiMOvBbzPavd4gY6Z8KWrfYzJoI/Q9FuBo6rKwl4BFoToD7WIUS+hpkagwWiz+6zLoX1dbOZwJACmH5fSSjAkLRi54PKJ8TFUeOP15h9sQzydI8zJU+upvDEKZsZc/UhT/SySDOxQ4G/523Y0sz/OZtSWcol/UMgQJALesy++GdvoIDLfJX5GBQpuFgFenRiRDabxrE9MNUZ2aPFaFp+DyAe+b4nDwuJaW2LURbr8AEZga7oQj0uYxcYw==
-----END RSA PRIVATE KEY-----
\"\"\"
]
"""
@spec parse_config(atom()) :: __MODULE__.t() | nil
def parse_config(key \\ :default_key) do
case Application.get_env(:joken, key) do
key_config when is_binary(key_config) ->
create("HS256", key_config)
key_config when is_list(key_config) ->
parse_list_config(key_config)
_ ->
nil
end
end
defp parse_list_config(config) do
signer_alg = config[:signer_alg] || "HS256"
headers = config[:jose_extra_headers] || %{}
key_pem =
case {config[:key_pem], config[:passphrase]} do
{nil, _} -> nil
{key, nil} -> key
{key, password} -> {key, password}
end
key_map = config[:key_map]
key_openssh = config[:key_openssh]
key_octet = config[:key_octet]
key_config =
[
{&from_pem/1, key_pem},
{&JWK.from_map/1, key_map},
{&JWK.from_openssh_key/1, key_openssh},
{&JWK.from_oct/1, key_octet}
]
|> Enum.filter(fn {_, val} -> not is_nil(val) end)
unless Enum.count(key_config) == 1, do: raise(Joken.Error, :wrong_key_parameters)
{jwk_function, value} = List.first(key_config)
if signer_alg in @algorithms do
raw_create(
signer_alg,
headers |> transform_headers(signer_alg) |> JWS.from_map(),
jwk_function.(value)
)
else
raise Joken.Error, :unrecognized_algorithm
end
end
defp from_pem({key, passphrase}), do: JWK.from_pem(passphrase, key)
defp from_pem(key), do: JWK.from_pem(key)
defp transform_headers(headers, signer_alg) when is_map(headers) and is_binary(signer_alg) do
headers
|> Map.put("alg", signer_alg)
|> Map.put_new("typ", "JWT")
end
end