forked from berty/berty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_services_auth.go
247 lines (201 loc) · 6.28 KB
/
api_services_auth.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package bertyprotocol
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"golang.org/x/net/context/ctxhttp"
"berty.tech/berty/v2/go/internal/cryptoutil"
"berty.tech/berty/v2/go/pkg/errcode"
"berty.tech/berty/v2/go/pkg/protocoltypes"
)
const (
AuthResponseType = "code"
AuthGrantType = "authorization_code"
AuthRedirect = "berty://services-auth/"
AuthClientID = "berty"
AuthCodeChallengeMethod = "S256"
)
type authExchangeResponse struct {
AccessToken string `json:"access_token"`
Scope string `json:"scope"`
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
Services map[string]string `json:"services"`
}
type authSession struct {
state string
codeVerifier string // codeVerifier base64 encoded random value
baseURL string
}
func authSessionCodeChallenge(codeVerifier string) string {
codeChallengeArr := sha256.Sum256([]byte(codeVerifier))
codeChallenge := make([]byte, sha256.Size)
for i, c := range codeChallengeArr {
codeChallenge[i] = c
}
return base64.RawURLEncoding.EncodeToString(codeChallenge)
}
func authSessionCodeVerifierAndChallenge() (string, string, error) {
verifierArr, err := cryptoutil.GenerateNonce()
if err != nil {
return "", "", err
}
codeVerifierBytes := make([]byte, cryptoutil.NonceSize)
for i, c := range verifierArr {
codeVerifierBytes[i] = c
}
verifier := base64.RawURLEncoding.EncodeToString(codeVerifierBytes)
return verifier, authSessionCodeChallenge(verifier), nil
}
func newAuthSession(baseURL string) (*authSession, string, error) {
state, err := cryptoutil.GenerateNonce()
if err != nil {
return nil, "", err
}
verifier, challenge, err := authSessionCodeVerifierAndChallenge()
if err != nil {
return nil, "", err
}
stateBytes := make([]byte, cryptoutil.NonceSize)
for i, c := range state {
stateBytes[i] = c
}
auth := &authSession{
baseURL: baseURL,
state: base64.RawURLEncoding.EncodeToString(stateBytes),
codeVerifier: verifier,
}
return auth, challenge, nil
}
func (s *service) authInitURL(baseURL string) (string, error) {
parsedAuthURL, err := url.Parse(baseURL)
if err != nil {
return "", errcode.ErrServicesAuthInvalidURL
}
switch parsedAuthURL.Scheme {
case "http", "https":
default:
return "", errcode.ErrServicesAuthInvalidURL
}
if parsedAuthURL.Host == "" {
return "", errcode.ErrServicesAuthInvalidURL
}
if strings.HasSuffix(baseURL, "/") {
baseURL = baseURL[:len(baseURL)-1]
}
auth, codeChallenge, err := newAuthSession(baseURL)
if err != nil {
return "", err
}
s.authSession.Store(auth)
return fmt.Sprintf("%s%s?response_type=%s&client_id=%s&redirect_uri=%s&state=%s&code_challenge=%s&code_challenge_method=%s",
baseURL,
AuthHTTPPathAuthorize,
AuthResponseType,
AuthClientID,
url.QueryEscape(AuthRedirect),
auth.state,
codeChallenge,
AuthCodeChallengeMethod,
), nil
}
func (s *service) AuthServiceCompleteFlow(ctx context.Context, request *protocoltypes.AuthServiceCompleteFlow_Request) (*protocoltypes.AuthServiceCompleteFlow_Reply, error) {
u, err := url.Parse(request.CallbackURL)
if err != nil {
return nil, err
}
if e := u.Query().Get("error"); e != "" {
return nil, errcode.ErrServicesAuthServer.Wrap(fmt.Errorf("got error: %s (%s)", e, u.Query().Get("error_description")))
}
code, state := u.Query().Get("code"), u.Query().Get("state")
authUntyped := s.authSession.Load()
if authUntyped == nil {
return nil, errcode.ErrServicesAuthNotInitialized
}
auth, ok := authUntyped.(*authSession)
if !ok {
return nil, errcode.ErrServicesAuthNotInitialized
}
if auth.state != state {
return nil, errcode.ErrServicesAuthWrongState
}
endpoint := fmt.Sprintf("%s%s", auth.baseURL, AuthHTTPPathTokenExchange)
res, err := ctxhttp.PostForm(ctx, http.DefaultClient, endpoint, url.Values{
"grant_type": {AuthGrantType},
"code": {code},
"client_id": {AuthClientID},
"code_verifier": {auth.codeVerifier},
})
if err != nil {
return nil, errcode.ErrStreamWrite.Wrap(err)
}
defer res.Body.Close()
if res.StatusCode >= 300 {
return nil, errcode.ErrServicesAuthInvalidResponse.Wrap(fmt.Errorf("invalid status code %d", res.StatusCode))
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, errcode.ErrStreamRead.Wrap(err)
}
resMsg := &authExchangeResponse{}
if err := json.Unmarshal(body, &resMsg); err != nil {
return nil, errcode.ErrDeserialization.Wrap(err)
}
if resMsg.Error != "" {
return nil, errcode.ErrServicesAuthServer.Wrap(err)
}
if resMsg.AccessToken == "" {
return nil, errcode.ErrServicesAuthInvalidResponse.Wrap(fmt.Errorf("missing access token in response"))
}
if len(resMsg.Services) == 0 {
return nil, errcode.ErrServicesAuthInvalidResponse.Wrap(fmt.Errorf("no services returned along token"))
}
services := make([]*protocoltypes.ServiceTokenSupportedService, len(resMsg.Services))
i := 0
for k, v := range resMsg.Services {
services[i] = &protocoltypes.ServiceTokenSupportedService{
ServiceType: k,
ServiceEndpoint: v,
}
i++
}
if _, err := s.accountGroup.metadataStore.SendAccountServiceTokenAdded(ctx, &protocoltypes.ServiceToken{
Token: resMsg.AccessToken,
AuthenticationURL: auth.baseURL,
SupportedServices: services,
Expiration: -1,
}); err != nil {
return nil, err
}
return &protocoltypes.AuthServiceCompleteFlow_Reply{}, nil
}
func (s *service) AuthServiceInitFlow(ctx context.Context, request *protocoltypes.AuthServiceInitFlow_Request) (*protocoltypes.AuthServiceInitFlow_Reply, error) {
u, err := s.authInitURL(request.AuthURL)
if err != nil {
return nil, err
}
return &protocoltypes.AuthServiceInitFlow_Reply{
URL: u,
SecureURL: strings.HasPrefix(u, "https://"),
}, nil
}
func (s *service) ServicesTokenList(request *protocoltypes.ServicesTokenList_Request, server protocoltypes.ProtocolService_ServicesTokenListServer) error {
for _, t := range s.accountGroup.metadataStore.listServiceTokens() {
if server.Context().Err() != nil {
break
}
if err := server.Send(&protocoltypes.ServicesTokenList_Reply{
TokenID: t.TokenID(),
Service: t,
}); err != nil {
return err
}
}
return nil
}