forked from Kopano-dev/konnect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.go
225 lines (189 loc) · 6.86 KB
/
models.go
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
/*
* Copyright 2017 Kopano and its licensors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package clients
import (
"context"
"crypto"
"crypto/subtle"
"encoding/base64"
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/mendsley/gojwk"
"golang.org/x/crypto/blake2b"
_ "gopkg.in/yaml.v2" // Make sure we have yaml.
"stash.kopano.io/kgol/rndm"
)
// Constat data used with dynamic stateless clients.
const (
DynamicStatelessClientIDPrefix = "dyn."
DynamicStatelessClientStaticSaltV1 = "konnect-client-v1"
)
// RegistryData is the base structur of our client registry configuration file.
type RegistryData struct {
Clients []*ClientRegistration `yaml:"clients,flow"`
}
// ClientRegistration defines a client with its properties.
type ClientRegistration struct {
ID string `yaml:"id" json:"-"`
Secret string `yaml:"secret" json:"-"`
Trusted bool `yaml:"trusted" json:"-"`
TrustedScopes []string `yaml:"trusted_scopes" json:"-"`
Insecure bool `yaml:"insecure" json:"-"`
Dynamic bool `yaml:"-" json:"-"`
IDIssuedAt int64 `yaml:"-" json:"-"`
SecretExpiresAt int64 `yaml:"-" json:"-"`
Contacts []string `yaml:"contacts,flow" json:"contacts,omitempty"`
Name string `yaml:"name" json:"name,omitempty"`
URI string `yaml:"uri" json:"uri,omitempty"`
GrantTypes []string `yaml:"grant_types,flow" json:"grant_types,omitempty"`
ApplicationType string `yaml:"application_type" json:"application_type,omitempty"`
RedirectURIs []string `yaml:"redirect_uris,flow" json:"redirect_uris,omitempty"`
Origins []string `yaml:"origins,flow" json:"-"`
JWKS *gojwk.Key `yaml:"jwks" json:"-"`
RawIDTokenSignedResponseAlg string `yaml:"id_token_signed_response_alg" json:"id_token_signed_response_alg,omitempty"`
RawUserInfoSignedResponseAlg string `yaml:"userinfo_signed_response_alg" json:"userinfo_signed_response_alg,omitempty"`
RawRequestObjectSigningAlg string `yaml:"request_object_signing_alg" json:"request_object_signing_alg,omitempty"`
RawTokenEndpointAuthMethod string `yaml:"token_endpoint_auth_method" json:"token_endpoint_auth_method,omitempty"`
RawTokenEndpointAuthSigningAlg string `yaml:"token_endpoint_auth_signing_alg" json:"token_endpoint_auth_signing_alg,omitempty"`
PostLogoutRedirectURIs []string `yaml:"post_logout_redirect_uris,flow" json:"post_logout_redirect_uris,omitempty"`
}
// Validate validates the associated client registration data and returns error
// if the data is not valid.
func (cr *ClientRegistration) Validate() error {
return nil
}
// Secure looks up the a matching key from the accociated client registration
// and returns its public key part as a secured client.
func (cr *ClientRegistration) Secure(rawKid interface{}) (*Secured, error) {
var kid string
var key crypto.PublicKey
var err error
switch len(cr.JWKS.Keys) {
case 0:
// breaks
case 1:
// Use the one and only, no matter what kid says.
key, err = cr.JWKS.Keys[0].DecodePublicKey()
if err != nil {
return nil, err
}
kid = cr.JWKS.Keys[0].Kid
default:
// Find by kid.
kid, _ = rawKid.(string)
if kid == "" {
kid = "default"
}
for _, k := range cr.JWKS.Keys {
if kid == k.Kid {
key, err = k.DecodePublicKey()
if err != nil {
return nil, err
}
break
}
}
}
if key == nil {
return nil, fmt.Errorf("unknown kid")
}
return &Secured{
ID: cr.ID,
DisplayName: cr.Name,
ApplicationType: cr.ApplicationType,
Kid: kid,
PublicKey: key,
TrustedScopes: cr.TrustedScopes,
Registration: cr,
}, nil
}
// SetDynamic modifieds the required data for the associated client registration
// so it becomes a dynamic client.
func (cr *ClientRegistration) SetDynamic(ctx context.Context, creator func(ctx context.Context, signingMethod jwt.SigningMethod, claims jwt.Claims) (string, error)) error {
if creator == nil {
return fmt.Errorf("no creator")
}
if cr.ID != "" {
return fmt.Errorf("has ID already")
}
// Initialize basic client registration data for dynamic client.
cr.IDIssuedAt = time.Now().Unix()
cr.SecretExpiresAt = time.Now().Add(1 * time.Hour).Unix()
cr.Dynamic = true
sub, secret, err := cr.makeSecret(nil)
if err != nil {
return fmt.Errorf("failed to make dynamic client secret: %v", err)
}
// Stateless Dynamic Client Registration encodes all relevant data in the
// client_id. See https://openid.net/specs/openid-connect-registration-1_0.html#StatelessRegistration
// for more information. We use a JWT as client_id.
claims := &RegistrationClaims{
StandardClaims: jwt.StandardClaims{
Subject: sub,
IssuedAt: cr.IDIssuedAt,
ExpiresAt: cr.SecretExpiresAt,
},
ClientRegistration: cr,
}
// Create signed stateless client ID by help of the provided creator function.
id, err := creator(ctx, nil, claims)
if err != nil {
return nil
}
// Fill in ID and secret.
cr.ID = DynamicStatelessClientIDPrefix + id
cr.Secret = secret
return nil
}
func (cr *ClientRegistration) makeSecret(secret []byte) (string, string, error) {
// Create random secret. HMAC the client name with it to get the subject.
if secret == nil {
secret = rndm.GenerateRandomBytes(64)
}
hasher, err := blake2b.New512(secret)
if err != nil {
return "", "", fmt.Errorf("failed to create hasher for dynamic client_id: %v", err)
}
hasher.Write([]byte(cr.Name))
hasher.Write([]byte(" "))
hasher.Write([]byte(DynamicStatelessClientStaticSaltV1))
sub := base64.RawURLEncoding.EncodeToString(hasher.Sum(nil))
return sub, base64.RawURLEncoding.EncodeToString(secret), nil
}
func (cr *ClientRegistration) validateSecret(clientSecret string) (bool, error) {
if cr.Dynamic {
if cr.Secret == "" {
// Fail fast, since dynamic clients must have a secret.
return false, fmt.Errorf("no secret in registration")
}
// Dynamic clients use hashed passwords.
secret, err := base64.RawURLEncoding.DecodeString(clientSecret)
if err != nil {
return false, fmt.Errorf("failed to decode client secret: %v", err)
}
sub, _, err := cr.makeSecret(secret)
if err != nil {
return false, fmt.Errorf("failed to produce client secret for comparison: %v", err)
}
return subtle.ConstantTimeCompare([]byte(sub), []byte(cr.Secret)) == 1, nil
}
if cr.Secret != "" && subtle.ConstantTimeCompare([]byte(clientSecret), []byte(cr.Secret)) != 1 {
return false, nil
}
return true, nil
}