-
Notifications
You must be signed in to change notification settings - Fork 1
/
idp.go
353 lines (289 loc) · 9.39 KB
/
idp.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package main
import (
"encoding/hex"
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/Microkubes/identity-provider/app"
"github.com/Microkubes/identity-provider/config"
"github.com/Microkubes/identity-provider/db"
jormungandrSamlIdp "github.com/Microkubes/identity-provider/samlidp"
"github.com/Microkubes/identity-provider/service"
"github.com/crewjam/saml"
"github.com/crewjam/saml/samlidp"
"github.com/keitaroinc/goa"
)
var sessionMaxAge = time.Hour * 24
var badRequestFile = "public/bad-request.html"
var errorFile = "public/error.html"
var loginFile = "public/login/login-form.html"
// IdpController implements the idp resource.
type IdpController struct {
*goa.Controller
Repository db.Repository
IDP *saml.IdentityProvider
Config *config.Config
}
type SamlIdentityProvider struct {
*saml.IdentityProvider
}
// NewIdpController creates a idp controller.
func NewIdpController(service *goa.Service, repository db.Repository, idp *saml.IdentityProvider, config *config.Config) *IdpController {
return &IdpController{
Controller: service.NewController("IdpController"),
Repository: repository,
IDP: idp,
Config: config,
}
}
// GetGoogleMetadata runs the getGoogleMetadata action.
func (c *IdpController) GetGoogleMetadata(ctx *app.GetGoogleMetadataIdpContext) error {
dat, err := ioutil.ReadFile("google-metadata.xml")
if err != nil {
return err
}
return ctx.OK(dat)
}
// Metadata runs the getMetadata action.
func (c *IdpController) GetMetadata(ctx *app.GetMetadataIdpContext) error {
buf, err := xml.MarshalIndent(c.IDP.Metadata(), "", " ")
if err != nil {
return nil
}
return ctx.OK(buf)
}
// LoginUser shows login form
func (c *IdpController) LoginUser(ctx *app.LoginUserIdpContext) error {
r := ctx.Request
w := ctx.ResponseData
c.IDP.ServiceProviderProvider = c.Repository
req := &saml.IdpAuthnRequest{
IDP: c.IDP,
HTTPRequest: r,
RelayState: "relayState",
}
jormungandrSamlIdp.LoginForm(w, r, req, fmt.Sprintf("%s/saml/idp/login", c.Config.GatewayURL), "", loginFile)
return nil
}
// ServeLoginUser runs login user action
func (c *IdpController) ServeLoginUser(ctx *app.ServeLoginUserIdpContext) error {
r := ctx.Request
w := ctx.ResponseData
c.IDP.ServiceProviderProvider = c.Repository
req := &saml.IdpAuthnRequest{
IDP: c.IDP,
HTTPRequest: r,
RelayState: "relayState",
}
email, password, err := service.CheckUserCredentials(r, w, req)
if err != nil {
jormungandrSamlIdp.LoginForm(w, r, req, fmt.Sprintf("%s/saml/idp/login", c.Config.GatewayURL), err.Error(), loginFile)
return nil
}
user, err := service.FindUser(email, password, c.IDP, c.Config)
if err != nil {
jormungandrSamlIdp.LoginForm(w, r, req, fmt.Sprintf("%s/saml/idp/login", c.Config.GatewayURL), "Wrong email or password!", loginFile)
return nil
}
tokenStr, err := service.GenerateSignedSAMLToken(c.IDP, user)
if err != nil {
jormungandrSamlIdp.ErrorForm(w, r, fmt.Sprintf("A server error has occured. %s", err.Error()), 500, errorFile)
}
roles := []string{}
for _, v := range user["roles"].([]interface{}) {
roles = append(roles, v.(string))
}
session := &saml.Session{
ID: tokenStr,
CreateTime: saml.TimeNow(),
ExpireTime: saml.TimeNow().Add(sessionMaxAge),
Index: hex.EncodeToString(jormungandrSamlIdp.RandomBytes(32)),
UserName: user["id"].(string),
Groups: roles,
UserEmail: user["email"].(string),
}
if err = c.Repository.AddSession(session); err != nil {
jormungandrSamlIdp.ErrorForm(w, r, fmt.Sprintf("A server error has occured. %s", err.Error()), 500, errorFile)
return nil
}
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: session.ID,
MaxAge: int(sessionMaxAge.Seconds()),
HttpOnly: true,
Secure: r.URL.Scheme == "https",
Path: "/",
})
http.Redirect(w, r, c.Config.Client["redirect-from-login"], http.StatusFound)
return nil
}
// ServeSSO runs the serveSSO action.
func (c *IdpController) ServeSSO(ctx *app.ServeSSOIdpContext) error {
r := ctx.Request
w := ctx.ResponseData
c.IDP.ServiceProviderProvider = c.Repository
req, err := jormungandrSamlIdp.ValidateSamlRequest(c.IDP, r)
if err != nil {
jormungandrSamlIdp.BadRequestForm(w, r, err.Error(), badRequestFile)
return nil
}
session, _ := c.Repository.GetSession(w, r, req)
if session == nil {
jormungandrSamlIdp.LoginForm(w, r, req, req.IDP.SSOURL.String(), "", loginFile)
return nil
}
if err = jormungandrSamlIdp.MakeAssertion(req, c.IDP, session); err != nil {
jormungandrSamlIdp.ErrorForm(w, r, fmt.Sprintf("A server error has occured. %s", err.Error()), 500, errorFile)
return nil
}
if err := req.WriteResponse(w); err != nil {
jormungandrSamlIdp.ErrorForm(w, r, fmt.Sprintf("A server error has occured. %s", err.Error()), 500, errorFile)
return nil
}
return nil
}
// ServeLogin runs the login action.
func (c *IdpController) ServeLogin(ctx *app.ServeLoginIdpContext) error {
r := ctx.Request
w := ctx.ResponseData
c.IDP.ServiceProviderProvider = c.Repository
relayState := strings.TrimSpace(r.FormValue("RelayState"))
SAMLRequest := strings.TrimSpace(r.FormValue("SAMLRequest"))
req, err := jormungandrSamlIdp.ValidateSamlRequest(c.IDP, r)
if err != nil {
jormungandrSamlIdp.BadRequestForm(w, r, err.Error(), badRequestFile)
return nil
}
email, password, err := service.CheckUserCredentials(r, w, req)
if err != nil {
jormungandrSamlIdp.LoginForm(w, r, req, fmt.Sprintf("%s?RelayState=%s&SAMLRequest=%s", req.IDP.SSOURL.String(), relayState, SAMLRequest), err.Error(), loginFile)
return nil
}
user, err := service.FindUser(email, password, c.IDP, c.Config)
if err != nil {
jormungandrSamlIdp.LoginForm(w, r, req, fmt.Sprintf("%s?RelayState=%s&SAMLRequest=%s", req.IDP.SSOURL.String(), relayState, SAMLRequest), "Wrong email or password!", loginFile)
return nil
}
roles := []string{}
for _, v := range user["roles"].([]interface{}) {
roles = append(roles, v.(string))
}
tokenStr, err := service.GenerateSignedSAMLToken(c.IDP, user)
if err != nil {
jormungandrSamlIdp.ErrorForm(w, r, fmt.Sprintf("A server error has occured. %s", err.Error()), 500, errorFile)
}
session := &saml.Session{
ID: tokenStr,
CreateTime: saml.TimeNow(),
ExpireTime: saml.TimeNow().Add(sessionMaxAge),
Index: hex.EncodeToString(jormungandrSamlIdp.RandomBytes(32)),
UserName: user["id"].(string),
Groups: roles,
UserEmail: user["email"].(string),
}
if err = c.Repository.AddSession(session); err != nil {
jormungandrSamlIdp.ErrorForm(w, r, fmt.Sprintf("A server error has occured. %s", err.Error()), 500, errorFile)
return nil
}
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: session.ID,
MaxAge: int(sessionMaxAge.Seconds()),
HttpOnly: true,
Secure: r.URL.Scheme == "https",
Path: "/",
})
if err = jormungandrSamlIdp.MakeAssertion(req, c.IDP, session); err != nil {
jormungandrSamlIdp.ErrorForm(w, r, fmt.Sprintf("A server error has occured. %s", err.Error()), 500, errorFile)
return nil
}
if err := req.WriteResponse(w); err != nil {
jormungandrSamlIdp.ErrorForm(w, r, fmt.Sprintf("A server error has occured. %s", err.Error()), 500, errorFile)
return nil
}
return nil
}
// AddService runs the add service action.
func (c *IdpController) AddServiceProvider(ctx *app.AddServiceProviderIdpContext) error {
r := ctx.Request
service := samlidp.Service{}
metadata, err := jormungandrSamlIdp.GetSPMetadata(r.Body)
if err != nil {
return ctx.BadRequest(err)
}
service.Metadata = *metadata
service.Name = service.Metadata.EntityID
err = c.Repository.AddServiceProvider(&service)
if err != nil {
ctx.InternalServerError(err)
}
return ctx.Created()
}
// DeleteServiceProvider runs the delete SP action.
func (c *IdpController) DeleteServiceProvider(ctx *app.DeleteServiceProviderIdpContext) error {
err := c.Repository.DeleteServiceProvider(ctx.Payload.ServiceID)
if err != nil {
e := err.(*goa.ErrorResponse)
switch e.Status {
case 404:
return ctx.NotFound(err)
default:
return ctx.InternalServerError(err)
}
}
return ctx.OK([]byte("OK"))
}
// GetServiceProviders runs the get Service Providers action.
func (c *IdpController) GetServiceProviders(ctx *app.GetServiceProvidersIdpContext) error {
services, err := c.Repository.GetServiceProviders()
if err != nil {
e := err.(*goa.ErrorResponse)
switch e.Status {
case 404:
return ctx.NotFound(err)
default:
return ctx.InternalServerError(err)
}
}
resp, err := json.Marshal(services)
if err != nil {
return ctx.InternalServerError(goa.ErrInternal(err))
}
return ctx.OK(resp)
}
// DeleteSession runs the delete session action.
func (c *IdpController) DeleteSession(ctx *app.DeleteSessionIdpContext) error {
err := c.Repository.DeleteSession(ctx.Payload.SessionID)
if err != nil {
e := err.(*goa.ErrorResponse)
switch e.Status {
case 404:
return ctx.NotFound(err)
default:
return ctx.InternalServerError(err)
}
}
return ctx.OK([]byte("OK"))
}
// GetSessions runs the get sessions action.
func (c *IdpController) GetSessions(ctx *app.GetSessionsIdpContext) error {
sessions, err := c.Repository.GetSessions()
if err != nil {
e := err.(*goa.ErrorResponse)
switch e.Status {
case 404:
return ctx.NotFound(err)
default:
return ctx.InternalServerError(err)
}
}
resp, err := json.Marshal(sessions)
if err != nil {
return ctx.InternalServerError(goa.ErrInternal(err))
}
return ctx.OK(resp)
}