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
  | 
package handlers
import (
	"database/sql"
	"encoding/json"
	"fmt"
	"net/url"
	"path"
	"authelia.com/provider/oauth2"
	"github.com/google/uuid"
	"github.com/authelia/authelia/v4/internal/authorization"
	"github.com/authelia/authelia/v4/internal/middlewares"
	"github.com/authelia/authelia/v4/internal/model"
	"github.com/authelia/authelia/v4/internal/oidc"
	"github.com/authelia/authelia/v4/internal/session"
)
// OpenIDConnectConsentGET handles requests to provide consent for OpenID Connect.
func OpenIDConnectConsentGET(ctx *middlewares.AutheliaCtx) {
	var (
		consentID uuid.UUID
		err       error
	)
	if consentID, err = uuid.ParseBytes(ctx.RequestCtx.QueryArgs().PeekBytes(qryArgID)); err != nil {
		ctx.Logger.Errorf("Unable to convert '%s' into a UUID: %+v", ctx.RequestCtx.QueryArgs().PeekBytes(qryArgID), err)
		ctx.ReplyForbidden()
		return
	}
	var (
		consent *model.OAuth2ConsentSession
		form    url.Values
		client  oidc.Client
		handled bool
	)
	if _, consent, client, handled = handleOpenIDConnectConsentGetSessionsAndClient(ctx, consentID); handled {
		return
	}
	if form, err = handleGetFormFromConsent(ctx, consent); err != nil {
		ctx.Logger.WithError(err).Errorf("Unable to get form from consent session with id '%s': %+v", consent.ChallengeID, err)
		ctx.SetJSONError(messageOperationFailed)
		return
	}
	if err = ctx.SetJSONBody(client.GetConsentResponseBody(consent, form)); err != nil {
		ctx.Error(fmt.Errorf("unable to set JSON body: %w", err), "Operation failed")
	}
}
// OpenIDConnectConsentPOST handles consent responses for OpenID Connect.
//
//nolint:gocyclo
func OpenIDConnectConsentPOST(ctx *middlewares.AutheliaCtx) {
	var (
		consentID uuid.UUID
		bodyJSON  oidc.ConsentPostRequestBody
		err       error
	)
	if err = json.Unmarshal(ctx.Request.Body(), &bodyJSON); err != nil {
		ctx.Logger.Errorf("Failed to parse JSON bodyJSON in consent POST: %+v", err)
		ctx.SetJSONError(messageOperationFailed)
		return
	}
	if consentID, err = uuid.Parse(bodyJSON.ConsentID); err != nil {
		ctx.Logger.Errorf("Unable to convert '%s' into a UUID: %+v", bodyJSON.ConsentID, err)
		ctx.ReplyForbidden()
		return
	}
	var (
		userSession session.UserSession
		consent     *model.OAuth2ConsentSession
		client      oidc.Client
		handled     bool
	)
	if userSession, consent, client, handled = handleOpenIDConnectConsentGetSessionsAndClient(ctx, consentID); handled {
		return
	}
	if consent.ClientID != bodyJSON.ClientID {
		ctx.Logger.Errorf("User '%s' consented to scopes of another client (%s) than expected (%s). Beware this can be a sign of attack",
			userSession.Username, bodyJSON.ClientID, consent.ClientID)
		ctx.SetJSONError(messageOperationFailed)
		return
	}
	if !client.IsAuthenticationLevelSufficient(userSession.AuthenticationLevel(ctx.Configuration.WebAuthn.EnablePasskey2FA), authorization.Subject{Username: userSession.Username, Groups: userSession.Groups, IP: ctx.RemoteIP()}) {
		ctx.Logger.Errorf("User '%s' can't consent to authorization request for client with id '%s' as they are not sufficiently authenticated",
			userSession.Username, consent.ClientID)
		ctx.SetJSONError(messageOperationFailed)
		return
	}
	var form url.Values
	if form, err = consent.GetForm(); err != nil {
		ctx.Logger.WithError(err).Errorf("Error occurred getting request form from consent session for user '%s' and client with id '%s'", userSession.Username, consent.ClientID)
		ctx.SetJSONError(messageOperationFailed)
		return
	}
	if bodyJSON.Consent {
		consent.GrantWithClaims(bodyJSON.Claims)
		if bodyJSON.PreConfigure {
			if client.GetConsentPolicy().Mode == oidc.ClientConsentModePreConfigured {
				config := model.OAuth2ConsentPreConfig{
					ClientID:      consent.ClientID,
					Subject:       consent.Subject.UUID,
					CreatedAt:     ctx.Clock.Now(),
					ExpiresAt:     sql.NullTime{Time: ctx.Clock.Now().Add(client.GetConsentPolicy().Duration), Valid: true},
					Scopes:        consent.GrantedScopes,
					Audience:      consent.GrantedAudience,
					GrantedClaims: bodyJSON.Claims,
				}
				var (
					requests   *oidc.ClaimsRequests
					actualForm url.Values
				)
				if actualForm, err = handleGetFormFromConsentForm(ctx, form); err != nil {
					ctx.Logger.WithError(err).Debug("Error occurred resolving the actual form from the consent form")
				} else if requests, err = oidc.NewClaimRequests(actualForm); err != nil {
					ctx.Logger.WithError(err).Debug("Error occurred parsing claims parameter from request form for claims signature")
				} else if config.RequestedClaims.String, config.SignatureClaims.String, err = requests.Serialized(); err != nil {
					ctx.Logger.WithError(err).Debug("Error occurred calculating claims signature")
				} else {
					config.RequestedClaims.Valid = true
					config.SignatureClaims.Valid = true
				}
				var id int64
				if id, err = ctx.Providers.StorageProvider.SaveOAuth2ConsentPreConfiguration(ctx, config); err != nil {
					ctx.Logger.Errorf("Failed to save the consent pre-configuration to the database: %+v", err)
					ctx.SetJSONError(messageOperationFailed)
					return
				}
				consent.PreConfiguration = sql.NullInt64{Int64: id, Valid: true}
				ctx.Logger.Debugf("Consent session with id '%s' for user '%s': pre-configured and set to expire at %v", consent.ChallengeID, userSession.Username, config.ExpiresAt.Time)
			} else {
				ctx.Logger.Warnf("Consent session with id '%s' for user '%s': consent pre-configuration was requested and was ignored because it is not permitted on this client", consent.ChallengeID, userSession.Username)
			}
		}
	}
	if err = ctx.Providers.StorageProvider.SaveOAuth2ConsentSessionResponse(ctx, consent, bodyJSON.Consent); err != nil {
		ctx.Logger.Errorf("Failed to save the consent session response to the database: %+v", err)
		ctx.SetJSONError(messageOperationFailed)
		return
	}
	var (
		redirectURI *url.URL
		query       url.Values
	)
	redirectURI = ctx.RootURL()
	if query, err = url.ParseQuery(consent.Form); err != nil {
		ctx.Logger.Errorf("Failed to parse the consent form values: %+v", err)
		ctx.SetJSONError(messageOperationFailed)
		return
	}
	query.Set(queryArgConsentID, consent.ChallengeID.String())
	redirectURI.Path = path.Join(redirectURI.Path, oidc.EndpointPathAuthorization)
	redirectURI.RawQuery = query.Encode()
	response := oidc.ConsentPostResponseBody{RedirectURI: redirectURI.String()}
	if err = ctx.SetJSONBody(response); err != nil {
		ctx.Error(fmt.Errorf("unable to set JSON bodyJSON in response"), "Operation failed")
	}
}
func handleOpenIDConnectConsentGetSessionsAndClient(ctx *middlewares.AutheliaCtx, consentID uuid.UUID) (userSession session.UserSession, consent *model.OAuth2ConsentSession, client oidc.Client, handled bool) {
	var (
		err error
	)
	if userSession, err = ctx.GetSession(); err != nil {
		ctx.Logger.Errorf("Unable to load user session for challenge id '%s': %v", consentID, err)
		ctx.ReplyForbidden()
		return userSession, nil, nil, true
	}
	if consent, err = ctx.Providers.StorageProvider.LoadOAuth2ConsentSessionByChallengeID(ctx, consentID); err != nil {
		ctx.Logger.Errorf("Unable to load consent session with challenge id '%s': %v", consentID, err)
		ctx.ReplyForbidden()
		return userSession, nil, nil, true
	}
	if client, err = ctx.Providers.OpenIDConnect.GetRegisteredClient(ctx, consent.ClientID); err != nil {
		ctx.Logger.Errorf("Unable to find related client configuration with name '%s': %v", consent.ClientID, err)
		ctx.ReplyForbidden()
		return userSession, nil, nil, true
	}
	if err = verifyOIDCUserAuthorizedForConsent(ctx, client, userSession, consent, uuid.UUID{}); err != nil {
		ctx.Logger.Errorf("Could not authorize the user '%s' for the consent session with challenge id '%s' on client with id '%s': %v", userSession.Username, consent.ChallengeID, client.GetID(), err)
		ctx.ReplyForbidden()
		return userSession, nil, nil, true
	}
	switch client.GetConsentPolicy().Mode {
	case oidc.ClientConsentModeImplicit:
		ctx.Logger.Errorf("Unable to perform OpenID Connect Consent for user '%s' and client id '%s': the client is using the implicit consent mode", userSession.Username, consent.ClientID)
		ctx.ReplyForbidden()
		return
	default:
		switch {
		case consent.Responded():
			ctx.Logger.Errorf("Unable to perform OpenID Connect Consent for user '%s' and client id '%s': the client is using the explicit consent mode and this consent session has already been responded to", userSession.Username, consent.ClientID)
			ctx.ReplyForbidden()
			return userSession, nil, nil, true
		case !consent.CanGrant():
			ctx.Logger.Errorf("Unable to perform OpenID Connect Consent for user '%s' and client id '%s': the specified consent session cannot be granted", userSession.Username, consent.ClientID)
			ctx.ReplyForbidden()
			return userSession, nil, nil, true
		}
	}
	if !client.IsAuthenticationLevelSufficient(userSession.AuthenticationLevel(ctx.Configuration.WebAuthn.EnablePasskey2FA), authorization.Subject{Username: userSession.Username, Groups: userSession.Groups, IP: ctx.RemoteIP()}) {
		ctx.Logger.Errorf("Unable to perform OpenID Connect Consent for user '%s' and client id '%s': the user is not sufficiently authenticated", userSession.Username, consent.ClientID)
		ctx.ReplyForbidden()
		return userSession, nil, nil, true
	}
	return userSession, consent, client, false
}
func handleGetFormFromConsent(ctx *middlewares.AutheliaCtx, consent *model.OAuth2ConsentSession) (form url.Values, err error) {
	if form, err = consent.GetForm(); err != nil {
		return nil, err
	}
	return handleGetFormFromConsentForm(ctx, form)
}
func handleGetFormFromConsentForm(ctx *middlewares.AutheliaCtx, original url.Values) (form url.Values, err error) {
	var requester oauth2.AuthorizeRequester
	if requester, err = handleGetPushedAuthorizationRequesterFromForm(ctx, original); err != nil {
		return nil, err
	} else if requester != nil {
		return requester.GetRequestForm(), nil
	}
	return form, err
}
func handleGetPushedAuthorizationRequesterFromForm(ctx *middlewares.AutheliaCtx, form url.Values) (requester oauth2.AuthorizeRequester, err error) {
	if oidc.IsPushedAuthorizedRequestForm(form, ctx.Providers.OpenIDConnect.GetPushedAuthorizeRequestURIPrefix(ctx)) {
		if requester, err = ctx.Providers.OpenIDConnect.GetPARSession(ctx, form.Get(oidc.FormParameterRequestURI)); err != nil {
			return nil, err
		}
		return requester, nil
	}
	return nil, nil
}
  |