Debian Codegraph @

pkg/op/server.go

raw
1 package op
2
3 import (
4 "context"
5 "net/http"
6 "net/url"
7
8 "github.com/muhlemmer/gu"
9 httphelper "github.com/zitadel/oidc/v3/pkg/http"
10 "github.com/zitadel/oidc/v3/pkg/oidc"
11 )
12
13 // Server describes the interface that needs to be implemented to serve
14 // OpenID Connect and Oauth2 standard requests.
15 //
16 // Methods are called after the HTTP route is resolved and
17 // the request body is parsed into the Request's Data field.
18 // When a method is called, it can be assumed that required fields,
19 // as described in their relevant standard, are validated already.
20 // The Response Data field may be of any type to allow flexibility
21 // to extend responses with custom fields. There are however requirements
22 // in the standards regarding the response models. Where applicable
23 // the method documentation gives a recommended type which can be used
24 // directly or extended upon.
25 //
26 // The addition of new methods is not considered a breaking change
27 // as defined by semver rules.
28 // Implementations MUST embed [UnimplementedServer] to maintain
29 // forward compatibility.
30 //
31 // EXPERIMENTAL: may change until v4
32 type Server interface {
33 // Health returns a status of "ok" once the Server is listening.
34 // The recommended Response Data type is [Status].
35 Health(context.Context, *Request[struct{}]) (*Response, error)
36
37 // Ready returns a status of "ok" once all dependencies,
38 // such as database storage, are ready.
39 // An error can be returned to explain what is not ready.
40 // The recommended Response Data type is [Status].
41 Ready(context.Context, *Request[struct{}]) (*Response, error)
42
43 // Discovery returns the OpenID Provider Configuration Information for this server.
44 // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig
45 // The recommended Response Data type is [oidc.DiscoveryConfiguration].
46 Discovery(context.Context, *Request[struct{}]) (*Response, error)
47
48 // Keys serves the JWK set which the client can use verify signatures from the op.
49 // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata `jwks_uri` key.
50 // The recommended Response Data type is [jose.JSONWebKeySet].
51 Keys(context.Context, *Request[struct{}]) (*Response, error)
52
53 // VerifyAuthRequest verifies the Auth Request and
54 // adds the Client to the request.
55 //
56 // When the `request` field is populated with a
57 // "Request Object" JWT, it needs to be Validated
58 // and its claims overwrite any fields in the AuthRequest.
59 // If the implementation does not support "Request Object",
60 // it MUST return an [oidc.ErrRequestNotSupported].
61 // https://openid.net/specs/openid-connect-core-1_0.html#RequestObject
62 VerifyAuthRequest(context.Context, *Request[oidc.AuthRequest]) (*ClientRequest[oidc.AuthRequest], error)
63
64 // Authorize initiates the authorization flow and redirects to a login page.
65 // See the various https://openid.net/specs/openid-connect-core-1_0.html
66 // authorize endpoint sections (one for each type of flow).
67 Authorize(context.Context, *ClientRequest[oidc.AuthRequest]) (*Redirect, error)
68
69 // DeviceAuthorization initiates the device authorization flow.
70 // https://datatracker.ietf.org/doc/html/rfc8628#section-3.1
71 // The recommended Response Data type is [oidc.DeviceAuthorizationResponse].
72 DeviceAuthorization(context.Context, *ClientRequest[oidc.DeviceAuthorizationRequest]) (*Response, error)
73
74 // VerifyClient is called on most oauth/token handlers to authenticate,
75 // using either a secret (POST, Basic) or assertion (JWT).
76 // If no secrets are provided, the client must be public.
77 // This method is called before each method that takes a
78 // [ClientRequest] argument.
79 VerifyClient(context.Context, *Request[ClientCredentials]) (Client, error)
80
81 // CodeExchange returns Tokens after an authorization code
82 // is obtained in a successful Authorize flow.
83 // It is called by the Token endpoint handler when
84 // grant_type has the value authorization_code
85 // https://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
86 // The recommended Response Data type is [oidc.AccessTokenResponse].
87 CodeExchange(context.Context, *ClientRequest[oidc.AccessTokenRequest]) (*Response, error)
88
89 // RefreshToken returns new Tokens after verifying a Refresh token.
90 // It is called by the Token endpoint handler when
91 // grant_type has the value refresh_token
92 // https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens
93 // The recommended Response Data type is [oidc.AccessTokenResponse].
94 RefreshToken(context.Context, *ClientRequest[oidc.RefreshTokenRequest]) (*Response, error)
95
96 // JWTProfile handles the OAuth 2.0 JWT Profile Authorization Grant
97 // It is called by the Token endpoint handler when
98 // grant_type has the value urn:ietf:params:oauth:grant-type:jwt-bearer
99 // https://datatracker.ietf.org/doc/html/rfc7523#section-2.1
100 // The recommended Response Data type is [oidc.AccessTokenResponse].
101 JWTProfile(context.Context, *Request[oidc.JWTProfileGrantRequest]) (*Response, error)
102
103 // TokenExchange handles the OAuth 2.0 token exchange grant
104 // It is called by the Token endpoint handler when
105 // grant_type has the value urn:ietf:params:oauth:grant-type:token-exchange
106 // https://datatracker.ietf.org/doc/html/rfc8693
107 // The recommended Response Data type is [oidc.AccessTokenResponse].
108 TokenExchange(context.Context, *ClientRequest[oidc.TokenExchangeRequest]) (*Response, error)
109
110 // ClientCredentialsExchange handles the OAuth 2.0 client credentials grant
111 // It is called by the Token endpoint handler when
112 // grant_type has the value client_credentials
113 // https://datatracker.ietf.org/doc/html/rfc6749#section-4.4
114 // The recommended Response Data type is [oidc.AccessTokenResponse].
115 ClientCredentialsExchange(context.Context, *ClientRequest[oidc.ClientCredentialsRequest]) (*Response, error)
116
117 // DeviceToken handles the OAuth 2.0 Device Authorization Grant
118 // It is called by the Token endpoint handler when
119 // grant_type has the value urn:ietf:params:oauth:grant-type:device_code.
120 // It is typically called in a polling fashion and appropriate errors
121 // should be returned to signal authorization_pending or access_denied etc.
122 // https://datatracker.ietf.org/doc/html/rfc8628#section-3.4,
123 // https://datatracker.ietf.org/doc/html/rfc8628#section-3.5.
124 // The recommended Response Data type is [oidc.AccessTokenResponse].
125 DeviceToken(context.Context, *ClientRequest[oidc.DeviceAccessTokenRequest]) (*Response, error)
126
127 // Introspect handles the OAuth 2.0 Token Introspection endpoint.
128 // https://datatracker.ietf.org/doc/html/rfc7662
129 // The recommended Response Data type is [oidc.IntrospectionResponse].
130 Introspect(context.Context, *Request[IntrospectionRequest]) (*Response, error)
131
132 // UserInfo handles the UserInfo endpoint and returns Claims about the authenticated End-User.
133 // https://openid.net/specs/openid-connect-core-1_0.html#UserInfo
134 // The recommended Response Data type is [oidc.UserInfo].
135 UserInfo(context.Context, *Request[oidc.UserInfoRequest]) (*Response, error)
136
137 // Revocation handles token revocation using an access or refresh token.
138 // https://datatracker.ietf.org/doc/html/rfc7009
139 // There are no response requirements. Data may remain empty.
140 Revocation(context.Context, *ClientRequest[oidc.RevocationRequest]) (*Response, error)
141
142 // EndSession handles the OpenID Connect RP-Initiated Logout.
143 // https://openid.net/specs/openid-connect-rpinitiated-1_0.html
144 // There are no response requirements. Data may remain empty.
145 EndSession(context.Context, *Request[oidc.EndSessionRequest]) (*Redirect, error)
146
147 // mustImpl forces implementations to embed the UnimplementedServer for forward
148 // compatibility with the interface.
149 mustImpl()
150 }
151
152 // Request contains the [http.Request] informational fields
153 // and parsed Data from the request body (POST) or URL parameters (GET).
154 // Data can be assumed to be validated according to the applicable
155 // standard for the specific endpoints.
156 //
157 // EXPERIMENTAL: may change until v4
158 type Request[T any] struct {
159 Method string
160 URL *url.URL
161 Header http.Header
162 Form url.Values
163 PostForm url.Values
164 Data *T
165 }
166
167 func (r *Request[_]) path() string {
168 return r.URL.Path
169 }
170
171 func newRequest[T any](r *http.Request, data *T) *Request[T] {
172 return &Request[T]{
173 Method: r.Method,
174 URL: r.URL,
175 Header: r.Header,
176 Form: r.Form,
177 PostForm: r.PostForm,
178 Data: data,
179 }
180 }
181
182 // ClientRequest is a Request with a verified client attached to it.
183 // Methods that receive this argument may assume the client was authenticated,
184 // or verified to be a public client.
185 //
186 // EXPERIMENTAL: may change until v4
187 type ClientRequest[T any] struct {
188 *Request[T]
189 Client Client
190 }
191
192 func newClientRequest[T any](r *http.Request, data *T, client Client) *ClientRequest[T] {
193 return &ClientRequest[T]{
194 Request: newRequest[T](r, data),
195 Client: client,
196 }
197 }
198
199 // Response object for most [Server] methods.
200 //
201 // EXPERIMENTAL: may change until v4
202 type Response struct {
203 // Header map will be merged with the
204 // header on the [http.ResponseWriter].
205 Header http.Header
206
207 // Data will be JSON marshaled to
208 // the response body.
209 // We allow any type, so that implementations
210 // can extend the standard types as they wish.
211 // However, each method will recommend which
212 // (base) type to use as model, in order to
213 // be compliant with the standards.
214 Data any
215 }
216
217 // NewResponse creates a new response for data,
218 // without custom headers.
219 func NewResponse(data any) *Response {
220 return &Response{
221 Header: make(http.Header),
222 Data: data,
223 }
224 }
225
226 func (resp *Response) writeOut(w http.ResponseWriter) {
227 gu.MapMerge(resp.Header, w.Header())
228 httphelper.MarshalJSON(w, resp.Data)
229 }
230
231 // Redirect is a special response type which will
232 // initiate a [http.StatusFound] redirect.
233 // The Params field will be encoded and set to the
234 // URL's RawQuery field before building the URL.
235 //
236 // EXPERIMENTAL: may change until v4
237 type Redirect struct {
238 // Header map will be merged with the
239 // header on the [http.ResponseWriter].
240 Header http.Header
241
242 URL string
243 }
244
245 func NewRedirect(url string) *Redirect {
246 return &Redirect{
247 Header: make(http.Header),
248 URL: url,
249 }
250 }
251
252 func (red *Redirect) writeOut(w http.ResponseWriter, r *http.Request) {
253 gu.MapMerge(red.Header, w.Header())
254 http.Redirect(w, r, red.URL, http.StatusFound)
255 }
256
257 type UnimplementedServer struct{}
258
259 // UnimplementedStatusCode is the status code returned for methods
260 // that are not yet implemented.
261 // Note that this means methods in the sense of the Go interface,
262 // and not http methods covered by "501 Not Implemented".
263 var UnimplementedStatusCode = http.StatusNotFound
264
265 func unimplementedError(r interface{ path() string }) StatusError {
266 err := oidc.ErrServerError().WithDescription("%s not implemented on this server", r.path())
267 return NewStatusError(err, UnimplementedStatusCode)
268 }
269
270 func unimplementedGrantError(gt oidc.GrantType) StatusError {
271 err := oidc.ErrUnsupportedGrantType().WithDescription("%s not supported", gt)
272 return NewStatusError(err, http.StatusBadRequest) // https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
273 }
274
275 func (UnimplementedServer) mustImpl() {}
276
277 func (UnimplementedServer) Health(ctx context.Context, r *Request[struct{}]) (*Response, error) {
278 return nil, unimplementedError(r)
279 }
280
281 func (UnimplementedServer) Ready(ctx context.Context, r *Request[struct{}]) (*Response, error) {
282 return nil, unimplementedError(r)
283 }
284
285 func (UnimplementedServer) Discovery(ctx context.Context, r *Request[struct{}]) (*Response, error) {
286 return nil, unimplementedError(r)
287 }
288
289 func (UnimplementedServer) Keys(ctx context.Context, r *Request[struct{}]) (*Response, error) {
290 return nil, unimplementedError(r)
291 }
292
293 func (UnimplementedServer) VerifyAuthRequest(ctx context.Context, r *Request[oidc.AuthRequest]) (*ClientRequest[oidc.AuthRequest], error) {
294 if r.Data.RequestParam != "" {
295 return nil, oidc.ErrRequestNotSupported()
296 }
297 return nil, unimplementedError(r)
298 }
299
300 func (UnimplementedServer) Authorize(ctx context.Context, r *ClientRequest[oidc.AuthRequest]) (*Redirect, error) {
301 return nil, unimplementedError(r)
302 }
303
304 func (UnimplementedServer) DeviceAuthorization(ctx context.Context, r *ClientRequest[oidc.DeviceAuthorizationRequest]) (*Response, error) {
305 return nil, unimplementedError(r)
306 }
307
308 func (UnimplementedServer) VerifyClient(ctx context.Context, r *Request[ClientCredentials]) (Client, error) {
309 return nil, unimplementedError(r)
310 }
311
312 func (UnimplementedServer) CodeExchange(ctx context.Context, r *ClientRequest[oidc.AccessTokenRequest]) (*Response, error) {
313 return nil, unimplementedGrantError(oidc.GrantTypeCode)
314 }
315
316 func (UnimplementedServer) RefreshToken(ctx context.Context, r *ClientRequest[oidc.RefreshTokenRequest]) (*Response, error) {
317 return nil, unimplementedGrantError(oidc.GrantTypeRefreshToken)
318 }
319
320 func (UnimplementedServer) JWTProfile(ctx context.Context, r *Request[oidc.JWTProfileGrantRequest]) (*Response, error) {
321 return nil, unimplementedGrantError(oidc.GrantTypeBearer)
322 }
323
324 func (UnimplementedServer) TokenExchange(ctx context.Context, r *ClientRequest[oidc.TokenExchangeRequest]) (*Response, error) {
325 return nil, unimplementedGrantError(oidc.GrantTypeTokenExchange)
326 }
327
328 func (UnimplementedServer) ClientCredentialsExchange(ctx context.Context, r *ClientRequest[oidc.ClientCredentialsRequest]) (*Response, error) {
329 return nil, unimplementedGrantError(oidc.GrantTypeClientCredentials)
330 }
331
332 func (UnimplementedServer) DeviceToken(ctx context.Context, r *ClientRequest[oidc.DeviceAccessTokenRequest]) (*Response, error) {
333 return nil, unimplementedGrantError(oidc.GrantTypeDeviceCode)
334 }
335
336 func (UnimplementedServer) Introspect(ctx context.Context, r *Request[IntrospectionRequest]) (*Response, error) {
337 return nil, unimplementedError(r)
338 }
339
340 func (UnimplementedServer) UserInfo(ctx context.Context, r *Request[oidc.UserInfoRequest]) (*Response, error) {
341 return nil, unimplementedError(r)
342 }
343
344 func (UnimplementedServer) Revocation(ctx context.Context, r *ClientRequest[oidc.RevocationRequest]) (*Response, error) {
345 return nil, unimplementedError(r)
346 }
347
348 func (UnimplementedServer) EndSession(ctx context.Context, r *Request[oidc.EndSessionRequest]) (*Redirect, error) {
349 return nil, unimplementedError(r)
350 }