generated from fluffy-bunny/fluffycore-grpc-starterkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
externalidp.go
334 lines (302 loc) · 11.5 KB
/
externalidp.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
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package externalidp
import (
"net/http"
"strings"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
di "github.com/fluffy-bunny/fluffy-dozm-di"
contracts_config "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/contracts/config"
contracts_cookies "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/contracts/cookies"
contracts_oauth2factory "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/contracts/oauth2factory"
contracts_oidc_session "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/contracts/oidc_session"
services_echo_handlers_base "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/services/echo/handlers/base"
echo_utils "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/services/echo/utils"
wellknown_echo "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/wellknown/echo"
proto_oidc_idp "github.com/fluffy-bunny/fluffycore-rage-identity/proto/oidc/idp"
proto_oidc_models "github.com/fluffy-bunny/fluffycore-rage-identity/proto/oidc/models"
contracts_handler "github.com/fluffy-bunny/fluffycore/echo/contracts/handler"
contracts_sessions "github.com/fluffy-bunny/fluffycore/echo/contracts/sessions"
fluffycore_utils "github.com/fluffy-bunny/fluffycore/utils"
status "github.com/gogo/status"
echo "github.com/labstack/echo/v4"
xid "github.com/rs/xid"
zerolog "github.com/rs/zerolog"
oauth2 "golang.org/x/oauth2"
codes "google.golang.org/grpc/codes"
)
type (
service struct {
*services_echo_handlers_base.BaseHandler
oauth2Factory contracts_oauth2factory.IOAuth2Factory
config *contracts_config.Config
oidcSession contracts_oidc_session.IOIDCSession
wellknownCookies contracts_cookies.IWellknownCookies
}
)
var stemService = (*service)(nil)
func init() {
var _ contracts_handler.IHandler = stemService
}
const (
// make sure only one is shown. This is an internal error code to point the developer to the code that is failing
InternalError_ExternalIDP_001 = "rg-external-idp-001"
InternalError_ExternalIDP_002 = "rg-external-idp-002"
InternalError_ExternalIDP_003 = "rg-external-idp-003"
InternalError_ExternalIDP_004 = "rg-external-idp-004"
InternalError_ExternalIDP_005 = "rg-external-idp-005"
InternalError_ExternalIDP_006 = "rg-external-idp-006"
InternalError_ExternalIDP_007 = "rg-external-idp-007"
InternalError_ExternalIDP_008 = "rg-external-idp-008"
InternalError_ExternalIDP_009 = "rg-external-idp-009"
InternalError_ExternalIDP_010 = "rg-external-idp-010"
InternalError_ExternalIDP_011 = "rg-external-idp-011"
InternalError_ExternalIDP_099 = "rg-external-idp-099" // 99 is a bind problem
)
func (s *service) Ctor(
config *contracts_config.Config,
container di.Container,
oauth2Factory contracts_oauth2factory.IOAuth2Factory,
oidcSession contracts_oidc_session.IOIDCSession,
wellknownCookies contracts_cookies.IWellknownCookies,
) (*service, error) {
return &service{
BaseHandler: services_echo_handlers_base.NewBaseHandler(container),
oauth2Factory: oauth2Factory,
config: config,
oidcSession: oidcSession,
wellknownCookies: wellknownCookies,
}, nil
}
// AddScopedIHandler registers the *service as a singleton.
func AddScopedIHandler(builder di.ContainerBuilder) {
contracts_handler.AddScopedIHandleWithMetadata[*service](builder,
stemService.Ctor,
[]contracts_handler.HTTPVERB{
// do auto post
//contracts_handler.GET,
contracts_handler.POST,
},
wellknown_echo.ExternalIDPPath,
)
}
func (s *service) GetMiddleware() []echo.MiddlewareFunc {
return []echo.MiddlewareFunc{}
}
func (s *service) getSession() (contracts_sessions.ISession, error) {
session, err := s.oidcSession.GetSession()
if err != nil {
return nil, err
}
return session, nil
}
type ExternalIDPAuthRequest struct {
Directive string `param:"directive" query:"directive" form:"directive" json:"directive" xml:"directive"`
IDPHint string `param:"idp_hint" query:"idp_hint" form:"idp_hint" json:"idp_hint" xml:"idp_hint"`
}
func (s *service) validateLoginGetRequest(model *ExternalIDPAuthRequest) error {
if fluffycore_utils.IsEmptyOrNil(model.IDPHint) {
return status.Error(codes.InvalidArgument, "IDPHint is required")
}
if fluffycore_utils.IsEmptyOrNil(model.Directive) {
return status.Error(codes.InvalidArgument, "Directive is required")
}
if !(model.Directive == "login" || model.Directive == "signup") {
return status.Error(codes.InvalidArgument, "Directive must be 'login' or 'signup'")
}
return nil
}
func (s *service) DoPost(c echo.Context) error {
r := c.Request()
rootPath := echo_utils.GetMyRootPath(c)
// is the request get or post?
//rootPath := echo_utils.GetMyRootPath(c)
ctx := r.Context()
log := zerolog.Ctx(ctx).With().Logger()
model := &ExternalIDPAuthRequest{}
if err := c.Bind(model); err != nil {
log.Error().Err(err).Msg("c.Bind")
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_099)
}
if err := s.validateLoginGetRequest(model); err != nil {
log.Error().Err(err).Msg("validateLoginGetRequest")
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_002)
}
log.Debug().Interface("model", model).Msg("model")
session, err := s.getSession()
if err != nil {
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_003)
}
dd, err := session.Get("request")
if err != nil {
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_004)
}
dd2 := dd.(*proto_oidc_models.AuthorizationRequest)
getIDPBySlugResponse, err := s.IdpServiceServer().GetIDPBySlug(ctx,
&proto_oidc_idp.GetIDPBySlugRequest{
Slug: model.IDPHint,
})
if err != nil {
log.Error().Err(err).Msg("GetIDPBySlug")
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_005)
}
idp := getIDPBySlugResponse.Idp
externalState := xid.New().String()
if idp.Protocol != nil {
log.Debug().Interface("getIDPBySlugResponse", getIDPBySlugResponse).Msg("getIDPBySlugResponse")
switch v := idp.Protocol.Value.(type) {
case *proto_oidc_models.Protocol_Github:
{
codeChallenge, verifier := generateCodeChallenge()
externalOAuth2State := &proto_oidc_models.ExternalOauth2State{
Request: &proto_oidc_models.ExternalOauth2Request{
IdpHint: model.IDPHint,
ClientId: v.Github.ClientId,
State: dd2.State,
CodeChallenge: codeChallenge,
CodeChallengeMethod: "S256",
CodeChallengeVerifier: verifier,
Directive: model.Directive,
ParentState: dd2.State,
},
}
err = s.wellknownCookies.SetExternalOauth2Cookie(c, &contracts_cookies.SetExternalOauth2CookieRequest{
State: externalState,
ExternalOAuth2State: externalOAuth2State,
})
if err != nil {
log.Error().Err(err).Msg("SetExternalOauth2Cookie")
// redirect to error page
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_006)
}
getConfigResponse, err := s.oauth2Factory.GetConfig(ctx,
&contracts_oauth2factory.GetConfigRequest{
IDPHint: model.IDPHint,
})
if err != nil {
log.Error().Err(err).Msg("Failed to get oauth2Config")
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_007)
}
oauth2Config := getConfigResponse.Config
u := oauth2Config.AuthCodeURL(externalState,
oauth2.SetAuthURLParam("code_challenge", codeChallenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"))
return c.Redirect(http.StatusFound, u)
}
case *proto_oidc_models.Protocol_Oauth2:
{
codeChallenge, verifier := generateCodeChallenge()
externalOAuth2State := &proto_oidc_models.ExternalOauth2State{
Request: &proto_oidc_models.ExternalOauth2Request{
IdpHint: model.IDPHint,
ClientId: v.Oauth2.ClientId,
State: dd2.State,
CodeChallenge: codeChallenge,
CodeChallengeMethod: "S256",
CodeChallengeVerifier: verifier,
Directive: model.Directive,
ParentState: dd2.State,
},
}
err = s.wellknownCookies.SetExternalOauth2Cookie(c, &contracts_cookies.SetExternalOauth2CookieRequest{
State: externalState,
ExternalOAuth2State: externalOAuth2State,
})
if err != nil {
log.Error().Err(err).Msg("SetExternalOauth2Cookie")
// redirect to error page
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_008)
}
scopes := strings.Split(v.Oauth2.Scope, " ")
config := oauth2.Config{
ClientID: v.Oauth2.ClientId,
ClientSecret: v.Oauth2.ClientSecret,
Scopes: scopes,
RedirectURL: rootPath + s.config.OIDCConfig.OAuth2CallbackPath,
Endpoint: oauth2.Endpoint{
AuthURL: v.Oauth2.AuthorizationEndpoint,
TokenURL: v.Oauth2.TokenEndpoint,
},
}
u := config.AuthCodeURL(externalState,
oauth2.SetAuthURLParam("code_challenge", codeChallenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"))
return c.Redirect(http.StatusFound, u)
}
case *proto_oidc_models.Protocol_Oidc:
{
nonce := xid.New().String()
externalOAuth2State := &proto_oidc_models.ExternalOauth2State{
Request: &proto_oidc_models.ExternalOauth2Request{
IdpHint: model.IDPHint,
ClientId: v.Oidc.ClientId,
State: dd2.State,
Directive: model.Directive,
ParentState: dd2.State,
Nonce: nonce,
},
}
//codeChallenge, verifier := generateCodeChallenge()
err = s.wellknownCookies.SetExternalOauth2Cookie(c, &contracts_cookies.SetExternalOauth2CookieRequest{
State: externalState,
ExternalOAuth2State: externalOAuth2State,
})
if err != nil {
log.Error().Err(err).Msg("SetExternalOauth2Cookie")
// redirect to error page
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_009)
}
getConfigResponse, err := s.oauth2Factory.GetConfig(ctx,
&contracts_oauth2factory.GetConfigRequest{
IDPHint: model.IDPHint,
})
if err != nil {
log.Error().Err(err).Msg("Failed to get oauth2Config")
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_010)
}
oauth2Config := getConfigResponse.Config
authCodeOptions := []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("nonce", nonce),
}
u := oauth2Config.AuthCodeURL(externalState, authCodeOptions...)
return c.Redirect(http.StatusFound, u)
}
}
}
return s.TeleportBackToLogin(c, InternalError_ExternalIDP_011)
}
func generateCodeChallenge() (string, string) {
// Generate a random 32-byte verifier string
verifierBytes := make([]byte, 32)
if _, err := rand.Read(verifierBytes); err != nil {
panic(err) // Handle error appropriately in production code
}
verifier := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(verifierBytes)
// Calculate the SHA256 hash of the verifier
hash := sha256.Sum256([]byte(verifier))
// Base64-encode the hash using URL-safe encoding without padding
challenge := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(hash[:])
// Replace any '+' or '/' characters with '-' and '_', respectively
challenge = strings.ReplaceAll(challenge, "+", "-")
challenge = strings.ReplaceAll(challenge, "/", "_")
return challenge, verifier
}
// ExternalIDP godoc
// @Summary todo
// @Description externalIDP.
// @Tags root
// @Accept */*
// @Produce json
// @Param code query string true "code"
// @Success 200 {object} string
// @Router /external-idp [post]
func (s *service) Do(c echo.Context) error {
r := c.Request()
// is the request get or post?
switch r.Method {
case http.MethodGet, http.MethodPost:
return s.DoPost(c)
}
// return not found
return c.NoContent(http.StatusNotFound)
}