-
Notifications
You must be signed in to change notification settings - Fork 619
Expand file tree
/
Copy pathauthentik.go
More file actions
319 lines (278 loc) · 7.6 KB
/
Copy pathauthentik.go
File metadata and controls
319 lines (278 loc) · 7.6 KB
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
package authentik
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/versent/saml2aws/v2/pkg/cfg"
"github.com/versent/saml2aws/v2/pkg/creds"
"github.com/versent/saml2aws/v2/pkg/provider"
)
// Client wrapper around authentik.
type Client struct {
provider.ValidateBase
client *provider.HTTPClient
// fido performs WebAuthn (FIDO U2F) assertions against a hardware security
// key. It is an interface so tests can substitute a fake device.
fido fidoAuthenticator
}
var logger = logrus.WithField("provider", "authentik")
// New create a new client
func New(idpAccount *cfg.IDPAccount) (*Client, error) {
tr := provider.NewDefaultTransport(idpAccount.SkipVerify)
client, err := provider.NewHTTPClient(tr, provider.BuildHttpClientOpts(idpAccount))
if err != nil {
return nil, errors.Wrap(err, "error building http client")
}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
return &Client{
client: client,
fido: u2fAuthenticator{},
}, nil
}
// Authenticate Log into authentik and returns a SAML response
func (kc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) {
ctx := &authentikContext{
loginDetails: loginDetails,
url: loginDetails.URL,
}
samlResponse, err := kc.auth(ctx)
if err != nil {
return "", errors.Wrap(err, "error retrieving saml response from idp")
}
return samlResponse, err
}
// auth Authentication
func (kc *Client) auth(ctx *authentikContext) (string, error) {
logger.Debug("[GET] ", ctx.url)
res, err := kc.client.Get(ctx.url)
if err != nil {
return "", errors.Wrap(err, "error retrieving initial url")
}
if res.StatusCode == http.StatusFound {
var location *url.URL
location, err = res.Location()
if err != nil {
return "", err
}
err = ctx.updateURL(location.String())
if err != nil {
return "", err
}
return kc.auth(ctx)
}
requestURL := res.Request.URL
if len(res.Cookies()) > 0 {
baseURL := &url.URL{Scheme: requestURL.Scheme, Host: requestURL.Host, Path: "/"}
kc.client.Jar.SetCookies(baseURL, res.Cookies())
}
next, err := kc.processQuery(ctx)
if err != nil {
return "", err
}
if ctx.samlResponse != "" {
return ctx.samlResponse, nil
}
err = ctx.updateURL(next)
if err != nil {
return "", err
}
return kc.auth(ctx)
}
// processQuery Loop to get the authentik credentials
func (kc *Client) processQuery(ctx *authentikContext) (string, error) {
var shouldContinue bool
var next string
var err error
next, err = queryNextURL(ctx.url)
if err != nil {
return "", err
}
err = ctx.updateURL(next)
if err != nil {
return "", err
}
for {
shouldContinue, next, err = kc.queryNext(ctx)
if err != nil {
return "", err
}
if next != "" {
err = ctx.updateURL(next)
if err != nil {
return "", err
}
}
if !shouldContinue {
break
}
}
return next, nil
}
// queryNext Do query and submit infos
func (kc *Client) queryNext(ctx *authentikContext) (bool, string, error) {
logger.Debug("[GET] ", ctx.url)
res, err := kc.client.Get(ctx.url)
if err != nil {
return false, "", err
}
if res.StatusCode == http.StatusFound {
next, err1 := res.Location()
if err1 != nil {
return false, "", err1
}
err = ctx.updateURL(next.String())
if err != nil {
return false, "", err
}
return kc.queryNext(ctx)
}
var payload *authentikPayload
payload, err = parseResponsePayload(res)
if err != nil {
return false, "", err
}
if payload.isTypeRedirect() || payload.isComponentFlowRedirect() {
// login success if there is a redirect
logger.Debug("Login success, redirect to saml response")
return false, payload.RedirectTo, nil
} else if !payload.isTypeNative() && !payload.isTypeEmpty() {
return false, "", errors.New("Unknown type: " + payload.Type)
}
if payload.isComponentStageAutosubmit() {
ctx.setSAMLResponse(payload.Attrs["SAMLResponse"])
return false, "", nil
}
next, err := kc.doPostQuery(ctx, payload)
return true, next, err
}
// doPostQuery For all data setting operations
func (kc *Client) doPostQuery(ctx *authentikContext, payload *authentikPayload) (string, error) {
var data []byte
var err error
// Prefer a hardware security key for the authenticator-validate stage when no
// explicit MFA token was supplied and the stage offers a webauthn device.
if payload.Component == "ak-stage-authenticator-validate" && ctx.loginDetails.MFAToken == "" {
var opts *webAuthnRequestOptions
opts, err = payload.webAuthnChallenge()
if err != nil {
return "", err
}
if opts != nil {
data, err = kc.signWebAuthnAssertion(payload.Component, opts)
if err != nil {
return "", err
}
}
}
if data == nil {
data, err = getLoginJSON(ctx.loginDetails, payload)
if err != nil {
return "", err
}
}
logger.Debug("[POST]", ctx.url)
res, err := kc.client.Post(ctx.url, "application/json", bytes.NewReader(data))
if err != nil {
return "", err
}
if res.StatusCode == http.StatusOK {
var payload *authentikPayload
payload, err = parseResponsePayload(res)
if err != nil {
return "", err
}
var errMsg string
if len(payload.Errors) > 0 {
errMsg = prepareErrors(payload.Component, payload.Errors)
} else {
errMsg = "Unexpected"
}
return "", errors.New(errMsg)
}
loc, err := res.Location()
if err != nil {
return "", errors.Wrapf(err, "unexpected response (status %d) from authentik flow", res.StatusCode)
}
return loc.String(), nil
}
// getLoginJSON Generate the login json
func getLoginJSON(loginDetails *creds.LoginDetails, payload *authentikPayload) ([]byte, error) {
component := payload.Component
m := map[string]string{
"component": component,
}
switch component {
case "ak-stage-identification":
m["uid_field"] = loginDetails.Username
if payload.HasPasswordField {
m["password"] = loginDetails.Password
}
case "ak-stage-password":
m["password"] = loginDetails.Password
case "ak-stage-authenticator-validate":
m["code"] = loginDetails.MFAToken
default:
return []byte(""), errors.New("unknown component: " + component)
}
return json.Marshal(m)
}
// queryNextURL Get the next api url
func queryNextURL(u string) (string, error) {
next, err := url.Parse(u)
if err != nil {
return "", errors.New("Invalid url")
}
result := strings.Split(next.Path, "/")
flow := result[len(result)-2]
return fmt.Sprintf("%s://%s/api/v3/flows/executor/%s/?query=%s", next.Scheme, next.Host, flow, url.QueryEscape(next.RawQuery)), nil
}
// getFieldName Get name of component
func getFieldName(component string) (string, error) {
prefix := "ak-stage-"
if strings.Index(component, prefix) != 0 {
return "", errors.New("")
}
s := strings.Split(component, "ak-stage-")
return s[len(s)-1], nil
}
// prepareErrors Transform errors to string
func prepareErrors(component string, errs map[string][]map[string]string) string {
field, err := getFieldName(component)
if err != nil {
return "Invalid component"
}
key := "non_field_errors"
if field == "password" {
key = "password"
}
if field == "authenticator-validate" {
key = "code"
}
msgs := make([]string, 0, len(errs[key]))
for _, err := range errs[key] {
msgs = append(msgs, fmt.Sprintf("%s %s: %s", field, err["code"], err["string"]))
}
return strings.Join(msgs, "; ")
}
// parseResponsePayload Parse response from authentik api
func parseResponsePayload(res *http.Response) (*authentikPayload, error) {
var payload authentikPayload
defer res.Body.Close()
b, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &payload)
if err != nil {
return nil, err
}
return &payload, nil
}