fix DLL assertion
[oweals/gnunet.git] / src / reclaim / plugin_rest_openid_connect.c
1 /*
2    This file is part of GNUnet.
3    Copyright (C) 2012-2018 GNUnet e.V.
4
5    GNUnet is free software: you can redistribute it and/or modify it
6    under the terms of the GNU Affero General Public License as published
7    by the Free Software Foundation, either version 3 of the License,
8    or (at your option) any later version.
9
10    GNUnet is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Affero General Public License for more details.
14
15    You should have received a copy of the GNU Affero General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18    SPDX-License-Identifier: AGPL3.0-or-later
19  */
20 /**
21  * @author Martin Schanzenbach
22  * @author Philippe Buschmann
23  * @file identity/plugin_rest_openid_connect.c
24  * @brief GNUnet Namestore REST plugin
25  *
26  */
27 #include "platform.h"
28 #include <inttypes.h>
29 #include <jansson.h>
30
31 #include "gnunet_gns_service.h"
32 #include "gnunet_gnsrecord_lib.h"
33 #include "gnunet_identity_service.h"
34 #include "gnunet_namestore_service.h"
35 #include "gnunet_reclaim_lib.h"
36 #include "gnunet_reclaim_service.h"
37 #include "gnunet_rest_lib.h"
38 #include "gnunet_rest_plugin.h"
39 #include "gnunet_signatures.h"
40 #include "microhttpd.h"
41 #include "oidc_helper.h"
42 /**
43  * REST root namespace
44  */
45 #define GNUNET_REST_API_NS_OIDC "/openid"
46
47 /**
48  * Authorize endpoint
49  */
50 #define GNUNET_REST_API_NS_AUTHORIZE "/openid/authorize"
51
52 /**
53  * Token endpoint
54  */
55 #define GNUNET_REST_API_NS_TOKEN "/openid/token"
56
57 /**
58  * UserInfo endpoint
59  */
60 #define GNUNET_REST_API_NS_USERINFO "/openid/userinfo"
61
62 /**
63  * Login namespace
64  */
65 #define GNUNET_REST_API_NS_LOGIN "/openid/login"
66
67 /**
68  * State while collecting all egos
69  */
70 #define ID_REST_STATE_INIT 0
71
72 /**
73  * Done collecting egos
74  */
75 #define ID_REST_STATE_POST_INIT 1
76
77 /**
78  * OIDC grant_type key
79  */
80 #define OIDC_GRANT_TYPE_KEY "grant_type"
81
82 /**
83  * OIDC grant_type key
84  */
85 #define OIDC_GRANT_TYPE_VALUE "authorization_code"
86
87 /**
88  * OIDC code key
89  */
90 #define OIDC_CODE_KEY "code"
91
92 /**
93  * OIDC response_type key
94  */
95 #define OIDC_RESPONSE_TYPE_KEY "response_type"
96
97 /**
98  * OIDC client_id key
99  */
100 #define OIDC_CLIENT_ID_KEY "client_id"
101
102 /**
103  * OIDC scope key
104  */
105 #define OIDC_SCOPE_KEY "scope"
106
107 /**
108  * OIDC redirect_uri key
109  */
110 #define OIDC_REDIRECT_URI_KEY "redirect_uri"
111
112 /**
113  * OIDC state key
114  */
115 #define OIDC_STATE_KEY "state"
116
117 /**
118  * OIDC nonce key
119  */
120 #define OIDC_NONCE_KEY "nonce"
121
122 /**
123  * OIDC claims key
124  */
125 #define OIDC_CLAIMS_KEY "claims"
126
127 /**
128  * OIDC PKCE code challenge
129  */
130 #define OIDC_CODE_CHALLENGE_KEY "code_challenge"
131
132 /**
133  * OIDC PKCE code verifier
134  */
135 #define OIDC_CODE_VERIFIER_KEY "code_verifier"
136
137 /**
138  * OIDC cookie expiration (in seconds)
139  */
140 #define OIDC_COOKIE_EXPIRATION 3
141
142 /**
143  * OIDC cookie header key
144  */
145 #define OIDC_COOKIE_HEADER_KEY "cookie"
146
147 /**
148  * OIDC cookie header information key
149  */
150 #define OIDC_AUTHORIZATION_HEADER_KEY "authorization"
151
152 /**
153  * OIDC cookie header information key
154  */
155 #define OIDC_COOKIE_HEADER_INFORMATION_KEY "Identity="
156
157 /**
158  * OIDC cookie header if user cancelled
159  */
160 #define OIDC_COOKIE_HEADER_ACCESS_DENIED "Identity=Denied"
161
162 /**
163  * OIDC expected response_type while authorizing
164  */
165 #define OIDC_EXPECTED_AUTHORIZATION_RESPONSE_TYPE "code"
166
167 /**
168  * OIDC expected scope part while authorizing
169  */
170 #define OIDC_EXPECTED_AUTHORIZATION_SCOPE "openid"
171
172 /**
173  * OIDC error key for invalid client
174  */
175 #define OIDC_ERROR_KEY_INVALID_CLIENT "invalid_client"
176
177 /**
178  * OIDC error key for invalid scopes
179  */
180 #define OIDC_ERROR_KEY_INVALID_SCOPE "invalid_scope"
181
182 /**
183  * OIDC error key for invalid requests
184  */
185 #define OIDC_ERROR_KEY_INVALID_REQUEST "invalid_request"
186
187 /**
188  * OIDC error key for invalid tokens
189  */
190 #define OIDC_ERROR_KEY_INVALID_TOKEN "invalid_token"
191
192 /**
193  * OIDC error key for invalid cookies
194  */
195 #define OIDC_ERROR_KEY_INVALID_COOKIE "invalid_cookie"
196
197 /**
198  * OIDC error key for generic server errors
199  */
200 #define OIDC_ERROR_KEY_SERVER_ERROR "server_error"
201
202 /**
203  * OIDC error key for unsupported grants
204  */
205 #define OIDC_ERROR_KEY_UNSUPPORTED_GRANT_TYPE "unsupported_grant_type"
206
207 /**
208  * OIDC error key for unsupported response types
209  */
210 #define OIDC_ERROR_KEY_UNSUPPORTED_RESPONSE_TYPE "unsupported_response_type"
211
212 /**
213  * OIDC error key for unauthorized clients
214  */
215 #define OIDC_ERROR_KEY_UNAUTHORIZED_CLIENT "unauthorized_client"
216
217 /**
218  * OIDC error key for denied access
219  */
220 #define OIDC_ERROR_KEY_ACCESS_DENIED "access_denied"
221
222
223 /**
224  * OIDC ignored parameter array
225  */
226 static char *OIDC_ignored_parameter_array[] = { "display",
227                                                 "prompt",
228                                                 "ui_locales",
229                                                 "response_mode",
230                                                 "id_token_hint",
231                                                 "login_hint",
232                                                 "acr_values" };
233
234 /**
235  * OIDC Hash map that keeps track of issued cookies
236  */
237 struct GNUNET_CONTAINER_MultiHashMap *OIDC_cookie_jar_map;
238
239 /**
240  * Hash map that links the issued access token to the corresponding ticket and
241  * ego
242  */
243 struct GNUNET_CONTAINER_MultiHashMap *OIDC_access_token_map;
244
245 /**
246  * The configuration handle
247  */
248 const struct GNUNET_CONFIGURATION_Handle *cfg;
249
250 /**
251  * HTTP methods allows for this plugin
252  */
253 static char *allow_methods;
254
255 /**
256  * @brief struct returned by the initialization function of the plugin
257  */
258 struct Plugin
259 {
260   const struct GNUNET_CONFIGURATION_Handle *cfg;
261 };
262
263 /**
264  * OIDC needed variables
265  */
266 struct OIDC_Variables
267 {
268   /**
269    * The RP client public key
270    */
271   struct GNUNET_CRYPTO_EcdsaPublicKey client_pkey;
272
273   /**
274    * The OIDC client id of the RP
275    */
276   char *client_id;
277
278   /**
279    * The OIDC redirect uri
280    */
281   char *redirect_uri;
282
283   /**
284    * The list of oidc scopes
285    */
286   char *scope;
287
288   /**
289    * The OIDC state
290    */
291   char *state;
292
293   /**
294    * The OIDC nonce
295    */
296   char *nonce;
297
298   /**
299    * The OIDC claims
300    */
301   char *claims;
302
303   /**
304    * The OIDC response type
305    */
306   char *response_type;
307
308   /**
309    * The identity chosen by the user to login
310    */
311   char *login_identity;
312
313   /**
314    * User cancelled authorization/login
315    */
316   int user_cancelled;
317
318   /**
319    * The PKCE code_challenge
320    */
321   char *code_challenge;
322
323   /**
324    * The PKCE code_verifier
325    */
326   char *code_verifier;
327
328   /**
329    * The response JSON
330    */
331   json_t *response;
332 };
333
334 /**
335  * The ego list
336  */
337 struct EgoEntry
338 {
339   /**
340    * DLL
341    */
342   struct EgoEntry *next;
343
344   /**
345    * DLL
346    */
347   struct EgoEntry *prev;
348
349   /**
350    * Ego Identifier
351    */
352   char *identifier;
353
354   /**
355    * Public key string
356    */
357   char *keystring;
358
359   /**
360    * The Ego
361    */
362   struct GNUNET_IDENTITY_Ego *ego;
363 };
364
365
366 struct RequestHandle
367 {
368   /**
369    * Ego list
370    */
371   struct EgoEntry *ego_head;
372
373   /**
374    * Ego list
375    */
376   struct EgoEntry *ego_tail;
377
378   /**
379    * Selected ego
380    */
381   struct EgoEntry *ego_entry;
382
383   /**
384    * Pointer to ego private key
385    */
386   struct GNUNET_CRYPTO_EcdsaPrivateKey priv_key;
387
388   /**
389    * OIDC variables
390    */
391   struct OIDC_Variables *oidc;
392
393   /**
394    * The processing state
395    */
396   int state;
397
398   /**
399    * Handle to Identity service.
400    */
401   struct GNUNET_IDENTITY_Handle *identity_handle;
402
403   /**
404    * Rest connection
405    */
406   struct GNUNET_REST_RequestHandle *rest_handle;
407
408   /**
409    * GNS handle
410    */
411   struct GNUNET_GNS_Handle *gns_handle;
412
413   /**
414    * GNS lookup op
415    */
416   struct GNUNET_GNS_LookupRequest *gns_op;
417
418   /**
419    * Handle to NAMESTORE
420    */
421   struct GNUNET_NAMESTORE_Handle *namestore_handle;
422
423   /**
424    * Iterator for NAMESTORE
425    */
426   struct GNUNET_NAMESTORE_ZoneIterator *namestore_handle_it;
427
428   /**
429    * Attribute claim list
430    */
431   struct GNUNET_RECLAIM_AttributeList *attr_list;
432
433   /**
434    * Attestation list
435    */
436   struct GNUNET_RECLAIM_AttestationList *attests_list;
437
438
439   /**
440    * IDENTITY Operation
441    */
442   struct GNUNET_IDENTITY_Operation *op;
443
444   /**
445    * Identity Provider
446    */
447   struct GNUNET_RECLAIM_Handle *idp;
448
449   /**
450    * Idp Operation
451    */
452   struct GNUNET_RECLAIM_Operation *idp_op;
453
454   /**
455    * Attribute iterator
456    */
457   struct GNUNET_RECLAIM_AttributeIterator *attr_it;
458
459   /**
460    * Attestation iterator
461    */
462   struct GNUNET_RECLAIM_AttestationIterator *attest_it;
463
464
465   /**
466    * Ticket iterator
467    */
468   struct GNUNET_RECLAIM_TicketIterator *ticket_it;
469
470   /**
471    * A ticket
472    */
473   struct GNUNET_RECLAIM_Ticket ticket;
474
475   /**
476    * Desired timeout for the lookup (default is no timeout).
477    */
478   struct GNUNET_TIME_Relative timeout;
479
480   /**
481    * ID of a task associated with the resolution process.
482    */
483   struct GNUNET_SCHEDULER_Task *timeout_task;
484
485   /**
486    * The plugin result processor
487    */
488   GNUNET_REST_ResultProcessor proc;
489
490   /**
491    * The closure of the result processor
492    */
493   void *proc_cls;
494
495   /**
496    * The url
497    */
498   char *url;
499
500   /**
501    * The tld for redirect
502    */
503   char *tld;
504
505   /**
506    * The redirect prefix
507    */
508   char *redirect_prefix;
509
510   /**
511    * The redirect suffix
512    */
513   char *redirect_suffix;
514
515   /**
516    * Error response message
517    */
518   char *emsg;
519
520   /**
521    * Error response description
522    */
523   char *edesc;
524
525   /**
526    * Reponse code
527    */
528   int response_code;
529 };
530
531 /**
532  * Cleanup lookup handle
533  * @param handle Handle to clean up
534  */
535 static void
536 cleanup_handle (struct RequestHandle *handle)
537 {
538   struct EgoEntry *ego_entry;
539
540   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n");
541   if (NULL != handle->timeout_task)
542     GNUNET_SCHEDULER_cancel (handle->timeout_task);
543   if (NULL != handle->identity_handle)
544     GNUNET_IDENTITY_disconnect (handle->identity_handle);
545   if (NULL != handle->attr_it)
546     GNUNET_RECLAIM_get_attributes_stop (handle->attr_it);
547   if (NULL != handle->attest_it)
548     GNUNET_RECLAIM_get_attestations_stop (handle->attest_it);
549   if (NULL != handle->ticket_it)
550     GNUNET_RECLAIM_ticket_iteration_stop (handle->ticket_it);
551   if (NULL != handle->idp_op)
552     GNUNET_RECLAIM_cancel (handle->idp_op);
553   if (NULL != handle->idp)
554     GNUNET_RECLAIM_disconnect (handle->idp);
555   GNUNET_free_non_null (handle->url);
556   GNUNET_free_non_null (handle->tld);
557   GNUNET_free_non_null (handle->redirect_prefix);
558   GNUNET_free_non_null (handle->redirect_suffix);
559   GNUNET_free_non_null (handle->emsg);
560   GNUNET_free_non_null (handle->edesc);
561   if (NULL != handle->gns_op)
562     GNUNET_GNS_lookup_cancel (handle->gns_op);
563   if (NULL != handle->gns_handle)
564     GNUNET_GNS_disconnect (handle->gns_handle);
565
566   if (NULL != handle->namestore_handle)
567     GNUNET_NAMESTORE_disconnect (handle->namestore_handle);
568   if (NULL != handle->oidc)
569   {
570     GNUNET_free_non_null (handle->oidc->client_id);
571     GNUNET_free_non_null (handle->oidc->login_identity);
572     GNUNET_free_non_null (handle->oidc->nonce);
573     GNUNET_free_non_null (handle->oidc->redirect_uri);
574     GNUNET_free_non_null (handle->oidc->response_type);
575     GNUNET_free_non_null (handle->oidc->scope);
576     GNUNET_free_non_null (handle->oidc->state);
577     json_decref (handle->oidc->response);
578     GNUNET_free (handle->oidc);
579   }
580   if (NULL!=handle->attr_list)
581     GNUNET_RECLAIM_attribute_list_destroy (handle->attr_list);
582   if (NULL!=handle->attests_list)
583     GNUNET_RECLAIM_attestation_list_destroy (handle->attests_list);
584
585   while (NULL != (ego_entry = handle->ego_head))
586   {
587     GNUNET_CONTAINER_DLL_remove (handle->ego_head,
588                                  handle->ego_tail,
589                                  ego_entry);
590     GNUNET_free_non_null (ego_entry->identifier);
591     GNUNET_free_non_null (ego_entry->keystring);
592     GNUNET_free (ego_entry);
593   }
594   GNUNET_free (handle);
595 }
596
597
598 static void
599 cleanup_handle_delayed (void *cls)
600 {
601   cleanup_handle (cls);
602 }
603
604
605 /**
606  * Task run on error, sends error message.  Cleans up everything.
607  *
608  * @param cls the `struct RequestHandle`
609  */
610 static void
611 do_error (void *cls)
612 {
613   struct RequestHandle *handle = cls;
614   struct MHD_Response *resp;
615   char *json_error;
616
617   GNUNET_asprintf (&json_error,
618                    "{ \"error\" : \"%s\", \"error_description\" : \"%s\"%s%s%s}",
619                    handle->emsg,
620                    (NULL != handle->edesc) ? handle->edesc : "",
621                    (NULL != handle->oidc->state) ? ", \"state\":\"" : "",
622                    (NULL != handle->oidc->state) ? handle->oidc->state : "",
623                    (NULL != handle->oidc->state) ? "\"" : "");
624   if (0 == handle->response_code)
625     handle->response_code = MHD_HTTP_BAD_REQUEST;
626   resp = GNUNET_REST_create_response (json_error);
627   if (MHD_HTTP_UNAUTHORIZED == handle->response_code)
628     MHD_add_response_header (resp, MHD_HTTP_HEADER_WWW_AUTHENTICATE, "Basic");
629   MHD_add_response_header (resp,
630                            MHD_HTTP_HEADER_CONTENT_TYPE,
631                            "application/json");
632   handle->proc (handle->proc_cls, resp, handle->response_code);
633   GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle);
634   GNUNET_free (json_error);
635 }
636
637
638 /**
639  * Task run on error in userinfo endpoint, sends error header. Cleans up
640  * everything
641  *
642  * @param cls the `struct RequestHandle`
643  */
644 static void
645 do_userinfo_error (void *cls)
646 {
647   struct RequestHandle *handle = cls;
648   struct MHD_Response *resp;
649   char *error;
650
651   GNUNET_asprintf (&error,
652                    "error=\"%s\", error_description=\"%s\"",
653                    handle->emsg,
654                    (NULL != handle->edesc) ? handle->edesc : "");
655   resp = GNUNET_REST_create_response ("");
656   MHD_add_response_header (resp, MHD_HTTP_HEADER_WWW_AUTHENTICATE, "Bearer");
657   handle->proc (handle->proc_cls, resp, handle->response_code);
658   GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle);
659   GNUNET_free (error);
660 }
661
662
663 /**
664  * Task run on error, sends error message and redirects. Cleans up everything.
665  *
666  * @param cls the `struct RequestHandle`
667  */
668 static void
669 do_redirect_error (void *cls)
670 {
671   struct RequestHandle *handle = cls;
672   struct MHD_Response *resp;
673   char *redirect;
674
675   GNUNET_asprintf (&redirect,
676                    "%s?error=%s&error_description=%s%s%s",
677                    handle->oidc->redirect_uri,
678                    handle->emsg,
679                    handle->edesc,
680                    (NULL != handle->oidc->state) ? "&state=" : "",
681                    (NULL != handle->oidc->state) ? handle->oidc->state : "");
682   resp = GNUNET_REST_create_response ("");
683   MHD_add_response_header (resp, "Location", redirect);
684   handle->proc (handle->proc_cls, resp, MHD_HTTP_FOUND);
685   GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle);
686   GNUNET_free (redirect);
687 }
688
689
690 /**
691  * Task run on timeout, sends error message.  Cleans up everything.
692  *
693  * @param cls the `struct RequestHandle`
694  */
695 static void
696 do_timeout (void *cls)
697 {
698   struct RequestHandle *handle = cls;
699
700   handle->timeout_task = NULL;
701   do_error (handle);
702 }
703
704
705 /**
706  * Return attributes for claim
707  *
708  * @param cls the request handle
709  */
710 static void
711 return_userinfo_response (void *cls)
712 {
713   char *result_str;
714   struct RequestHandle *handle = cls;
715   struct MHD_Response *resp;
716
717   result_str = json_dumps (handle->oidc->response, 0);
718   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"ID-Token: %s\n",result_str);
719   resp = GNUNET_REST_create_response (result_str);
720   handle->proc (handle->proc_cls, resp, MHD_HTTP_OK);
721   GNUNET_free (result_str);
722   cleanup_handle (handle);
723 }
724
725
726 /**
727  * Respond to OPTIONS request
728  *
729  * @param con_handle the connection handle
730  * @param url the url
731  * @param cls the RequestHandle
732  */
733 static void
734 options_cont (struct GNUNET_REST_RequestHandle *con_handle,
735               const char *url,
736               void *cls)
737 {
738   struct MHD_Response *resp;
739   struct RequestHandle *handle = cls;
740
741   // For now, independent of path return all options
742   resp = GNUNET_REST_create_response (NULL);
743   MHD_add_response_header (resp, "Access-Control-Allow-Methods", allow_methods);
744   handle->proc (handle->proc_cls, resp, MHD_HTTP_OK);
745   cleanup_handle (handle);
746   return;
747 }
748
749
750 /**
751  * Interprets cookie header and pass its identity keystring to handle
752  */
753 static void
754 cookie_identity_interpretation (struct RequestHandle *handle)
755 {
756   struct GNUNET_HashCode cache_key;
757   char *cookies;
758   struct GNUNET_TIME_Absolute current_time, *relog_time;
759   char delimiter[] = "; ";
760   char *tmp_cookies;
761   char *token;
762   char *value;
763
764   // gets identity of login try with cookie
765   GNUNET_CRYPTO_hash (OIDC_COOKIE_HEADER_KEY,
766                       strlen (OIDC_COOKIE_HEADER_KEY),
767                       &cache_key);
768   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle
769                                                            ->header_param_map,
770                                                            &cache_key))
771   {
772     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No cookie found\n");
773     return;
774   }
775   // splits cookies and find 'Identity' cookie
776   tmp_cookies =
777     GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->header_param_map,
778                                        &cache_key);
779   cookies = GNUNET_strdup (tmp_cookies);
780   token = strtok (cookies, delimiter);
781   handle->oidc->user_cancelled = GNUNET_NO;
782   handle->oidc->login_identity = NULL;
783   if (NULL == token)
784   {
785     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
786                 "Unable to parse cookie: %s\n",
787                 cookies);
788     GNUNET_free (cookies);
789     return;
790   }
791
792   while (NULL != token)
793   {
794     if (0 == strcmp (token, OIDC_COOKIE_HEADER_ACCESS_DENIED))
795     {
796       handle->oidc->user_cancelled = GNUNET_YES;
797       GNUNET_free (cookies);
798       return;
799     }
800     if (NULL != strstr (token, OIDC_COOKIE_HEADER_INFORMATION_KEY))
801       break;
802     token = strtok (NULL, delimiter);
803   }
804   if (NULL == token)
805   {
806     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
807                 "No cookie value to process: %s\n",
808                 cookies);
809     GNUNET_free (cookies);
810     return;
811   }
812   GNUNET_CRYPTO_hash (token, strlen (token), &cache_key);
813   if (GNUNET_NO ==
814       GNUNET_CONTAINER_multihashmap_contains (OIDC_cookie_jar_map, &cache_key))
815   {
816     GNUNET_log (
817       GNUNET_ERROR_TYPE_WARNING,
818       "Found cookie `%s', but no corresponding expiration entry present...\n",
819       token);
820     GNUNET_free (cookies);
821     return;
822   }
823   relog_time =
824     GNUNET_CONTAINER_multihashmap_get (OIDC_cookie_jar_map, &cache_key);
825   current_time = GNUNET_TIME_absolute_get ();
826   // 30 min after old login -> redirect to login
827   if (current_time.abs_value_us > relog_time->abs_value_us)
828   {
829     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
830                 "Found cookie `%s', but it is expired.\n",
831                 token);
832     GNUNET_free (cookies);
833     return;
834   }
835   value = strtok (token, OIDC_COOKIE_HEADER_INFORMATION_KEY);
836   GNUNET_assert (NULL != value);
837   handle->oidc->login_identity = GNUNET_strdup (value);
838   GNUNET_free (cookies);
839 }
840
841
842 /**
843  * Redirects to login page stored in configuration file
844  */
845 static void
846 login_redirect (void *cls)
847 {
848   char *login_base_url;
849   char *new_redirect;
850   struct MHD_Response *resp;
851   struct RequestHandle *handle = cls;
852
853   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg,
854                                                           "reclaim-rest-plugin",
855                                                           "address",
856                                                           &login_base_url))
857   {
858     GNUNET_asprintf (&new_redirect,
859                      "%s?%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s",
860                      login_base_url,
861                      OIDC_RESPONSE_TYPE_KEY,
862                      handle->oidc->response_type,
863                      OIDC_CLIENT_ID_KEY,
864                      handle->oidc->client_id,
865                      OIDC_REDIRECT_URI_KEY,
866                      handle->oidc->redirect_uri,
867                      OIDC_SCOPE_KEY,
868                      handle->oidc->scope,
869                      OIDC_STATE_KEY,
870                      (NULL != handle->oidc->state) ? handle->oidc->state : "",
871                      OIDC_CODE_CHALLENGE_KEY,
872                      (NULL != handle->oidc->code_challenge) ?
873                      handle->oidc->code_challenge : "",
874                      OIDC_NONCE_KEY,
875                      (NULL != handle->oidc->nonce) ? handle->oidc->nonce : "",
876                      OIDC_CLAIMS_KEY,
877                      (NULL != handle->oidc->claims) ? handle->oidc->claims :
878                      "");
879     resp = GNUNET_REST_create_response ("");
880     MHD_add_response_header (resp, "Location", new_redirect);
881     GNUNET_free (login_base_url);
882   }
883   else
884   {
885     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR);
886     handle->edesc = GNUNET_strdup ("gnunet configuration failed");
887     handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR;
888     GNUNET_SCHEDULER_add_now (&do_error, handle);
889     return;
890   }
891   handle->proc (handle->proc_cls, resp, MHD_HTTP_FOUND);
892   GNUNET_free (new_redirect);
893   GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle);
894 }
895
896
897 /**
898  * Does internal server error when iteration failed.
899  */
900 static void
901 oidc_iteration_error (void *cls)
902 {
903   struct RequestHandle *handle = cls;
904
905   handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR);
906   handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR;
907   GNUNET_SCHEDULER_add_now (&do_error, handle);
908 }
909
910
911 /**
912  * Issues ticket and redirects to relying party with the authorization code as
913  * parameter. Otherwise redirects with error
914  */
915 static void
916 oidc_ticket_issue_cb (void *cls, const struct GNUNET_RECLAIM_Ticket *ticket)
917 {
918   struct RequestHandle *handle = cls;
919   struct MHD_Response *resp;
920   char *ticket_str;
921   char *redirect_uri;
922   char *code_string;
923
924   handle->idp_op = NULL;
925   if (NULL == ticket)
926   {
927     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR);
928     handle->edesc = GNUNET_strdup ("Server cannot generate ticket.");
929     GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
930     return;
931   }
932   handle->ticket = *ticket;
933   ticket_str =
934     GNUNET_STRINGS_data_to_string_alloc (&handle->ticket,
935                                          sizeof(struct GNUNET_RECLAIM_Ticket));
936   code_string = OIDC_build_authz_code (&handle->priv_key,
937                                        &handle->ticket,
938                                        handle->attr_list,
939                                        handle->attests_list,
940                                        handle->oidc->nonce,
941                                        handle->oidc->code_challenge);
942   if ((NULL != handle->redirect_prefix) && (NULL != handle->redirect_suffix) &&
943       (NULL != handle->tld))
944   {
945     GNUNET_asprintf (&redirect_uri,
946                      "%s.%s/%s?%s=%s&state=%s",
947                      handle->redirect_prefix,
948                      handle->tld,
949                      handle->redirect_suffix,
950                      handle->oidc->response_type,
951                      code_string,
952                      handle->oidc->state);
953   }
954   else
955   {
956     GNUNET_asprintf (&redirect_uri,
957                      "%s?%s=%s&state=%s",
958                      handle->oidc->redirect_uri,
959                      handle->oidc->response_type,
960                      code_string,
961                      handle->oidc->state);
962   }
963   resp = GNUNET_REST_create_response ("");
964   MHD_add_response_header (resp, "Location", redirect_uri);
965   handle->proc (handle->proc_cls, resp, MHD_HTTP_FOUND);
966   GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle);
967   GNUNET_free (redirect_uri);
968   GNUNET_free (ticket_str);
969   GNUNET_free (code_string);
970 }
971
972
973 static void
974 oidc_attest_collect_finished_cb (void *cls)
975 {
976   struct RequestHandle *handle = cls;
977
978   handle->attest_it = NULL;
979   handle->idp_op = GNUNET_RECLAIM_ticket_issue (handle->idp,
980                                                 &handle->priv_key,
981                                                 &handle->oidc->client_pkey,
982                                                 handle->attr_list,
983                                                 &oidc_ticket_issue_cb,
984                                                 handle);
985 }
986
987
988 /**
989  * Collects all attributes for an ego if in scope parameter
990  */
991 static void
992 oidc_attest_collect (void *cls,
993                      const struct GNUNET_CRYPTO_EcdsaPublicKey *identity,
994                      const struct GNUNET_RECLAIM_Attestation *attest)
995 {
996   struct RequestHandle *handle = cls;
997   struct GNUNET_RECLAIM_AttributeListEntry *le;
998
999   for (le = handle->attr_list->list_head; NULL != le; le = le->next)
1000   {
1001     if (GNUNET_NO == GNUNET_RECLAIM_id_is_equal (&le->attribute->attestation,
1002                                                  &attest->id))
1003     {
1004       struct GNUNET_RECLAIM_AttestationListEntry *ale;
1005       ale = GNUNET_new (struct GNUNET_RECLAIM_AttestationListEntry);
1006       ale->attestation = GNUNET_RECLAIM_attestation_new (attest->name,
1007                                                          attest->type,
1008                                                          attest->data,
1009                                                          attest->data_size);
1010       GNUNET_CONTAINER_DLL_insert (handle->attests_list->list_head,
1011                                    handle->attests_list->list_tail,
1012                                    ale);
1013     }
1014   }
1015   GNUNET_RECLAIM_get_attestations_next (handle->attest_it);
1016 }
1017
1018
1019 static void
1020 oidc_attr_collect_finished_cb (void *cls)
1021 {
1022   struct RequestHandle *handle = cls;
1023
1024   handle->attr_it = NULL;
1025   handle->ticket_it = NULL;
1026   if (NULL == handle->attr_list->list_head)
1027   {
1028     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_SCOPE);
1029     handle->edesc = GNUNET_strdup ("The requested scope is not available.");
1030     GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
1031     return;
1032   }
1033   handle->attests_list = GNUNET_new (struct GNUNET_RECLAIM_AttestationList);
1034   handle->attest_it =
1035     GNUNET_RECLAIM_get_attestations_start (handle->idp,
1036                                            &handle->priv_key,
1037                                            &oidc_iteration_error,
1038                                            handle,
1039                                            &oidc_attest_collect,
1040                                            handle,
1041                                            &oidc_attest_collect_finished_cb,
1042                                            handle);
1043
1044 }
1045
1046
1047 /**
1048  * Collects all attributes for an ego if in scope parameter
1049  */
1050 static void
1051 oidc_attr_collect (void *cls,
1052                    const struct GNUNET_CRYPTO_EcdsaPublicKey *identity,
1053                    const struct GNUNET_RECLAIM_Attribute *attr)
1054 {
1055   struct RequestHandle *handle = cls;
1056   struct GNUNET_RECLAIM_AttributeListEntry *le;
1057   char *scope_variables;
1058   char *scope_variable;
1059   char delimiter[] = " ";
1060
1061   scope_variables = GNUNET_strdup (handle->oidc->scope);
1062   scope_variable = strtok (scope_variables, delimiter);
1063   while (NULL != scope_variable)
1064   {
1065     if (0 == strcmp (attr->name, scope_variable))
1066       break;
1067     scope_variable = strtok (NULL, delimiter);
1068   }
1069   if (NULL == scope_variable)
1070   {
1071     GNUNET_RECLAIM_get_attributes_next (handle->attr_it);
1072     GNUNET_free (scope_variables);
1073     // We can ignore this
1074     return;
1075   }
1076   GNUNET_free (scope_variables);
1077   le = GNUNET_new (struct GNUNET_RECLAIM_AttributeListEntry);
1078   le->attribute = GNUNET_RECLAIM_attribute_new (attr->name,
1079                                                 &attr->attestation,
1080                                                 attr->type,
1081                                                 attr->data,
1082                                                 attr->data_size);
1083   le->attribute->id = attr->id;
1084   le->attribute->flag = attr->flag;
1085   le->attribute->attestation = attr->attestation;
1086   GNUNET_CONTAINER_DLL_insert (handle->attr_list->list_head,
1087                                handle->attr_list->list_tail,
1088                                le);
1089   GNUNET_RECLAIM_get_attributes_next (handle->attr_it);
1090 }
1091
1092
1093 /**
1094  * Checks time and cookie and redirects accordingly
1095  */
1096 static void
1097 code_redirect (void *cls)
1098 {
1099   struct RequestHandle *handle = cls;
1100   struct GNUNET_TIME_Absolute current_time;
1101   struct GNUNET_TIME_Absolute *relog_time;
1102   struct GNUNET_CRYPTO_EcdsaPublicKey pubkey;
1103   struct GNUNET_CRYPTO_EcdsaPublicKey ego_pkey;
1104   struct GNUNET_HashCode cache_key;
1105   char *identity_cookie;
1106
1107   GNUNET_asprintf (&identity_cookie,
1108                    "Identity=%s",
1109                    handle->oidc->login_identity);
1110   GNUNET_CRYPTO_hash (identity_cookie, strlen (identity_cookie), &cache_key);
1111   GNUNET_free (identity_cookie);
1112   // No login time for identity -> redirect to login
1113   if (GNUNET_YES ==
1114       GNUNET_CONTAINER_multihashmap_contains (OIDC_cookie_jar_map, &cache_key))
1115   {
1116     relog_time =
1117       GNUNET_CONTAINER_multihashmap_get (OIDC_cookie_jar_map, &cache_key);
1118     current_time = GNUNET_TIME_absolute_get ();
1119     // 30 min after old login -> redirect to login
1120     if (current_time.abs_value_us <= relog_time->abs_value_us)
1121     {
1122       if (GNUNET_OK !=
1123           GNUNET_CRYPTO_ecdsa_public_key_from_string (handle->oidc
1124                                                       ->login_identity,
1125                                                       strlen (
1126                                                         handle->oidc
1127                                                         ->login_identity),
1128                                                       &pubkey))
1129       {
1130         handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_COOKIE);
1131         handle->edesc =
1132           GNUNET_strdup ("The cookie of a login identity is not valid");
1133         GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
1134         return;
1135       }
1136       // iterate over egos and compare their public key
1137       for (handle->ego_entry = handle->ego_head; NULL != handle->ego_entry;
1138            handle->ego_entry = handle->ego_entry->next)
1139       {
1140         GNUNET_IDENTITY_ego_get_public_key (handle->ego_entry->ego, &ego_pkey);
1141         if (0 == GNUNET_memcmp (&ego_pkey, &pubkey))
1142         {
1143           handle->priv_key =
1144             *GNUNET_IDENTITY_ego_get_private_key (handle->ego_entry->ego);
1145           handle->idp = GNUNET_RECLAIM_connect (cfg);
1146           handle->attr_list =
1147             GNUNET_new (struct GNUNET_RECLAIM_AttributeList);
1148           handle->attr_it =
1149             GNUNET_RECLAIM_get_attributes_start (handle->idp,
1150                                                  &handle->priv_key,
1151                                                  &oidc_iteration_error,
1152                                                  handle,
1153                                                  &oidc_attr_collect,
1154                                                  handle,
1155                                                  &oidc_attr_collect_finished_cb,
1156                                                  handle);
1157           return;
1158         }
1159       }
1160       GNUNET_SCHEDULER_add_now (&login_redirect, handle);
1161       return;
1162     }
1163   }
1164 }
1165
1166
1167 static void
1168 build_redirect (void *cls)
1169 {
1170   struct RequestHandle *handle = cls;
1171   struct MHD_Response *resp;
1172   char *redirect_uri;
1173
1174   if (GNUNET_YES == handle->oidc->user_cancelled)
1175   {
1176     if ((NULL != handle->redirect_prefix) &&
1177         (NULL != handle->redirect_suffix) && (NULL != handle->tld))
1178     {
1179       GNUNET_asprintf (&redirect_uri,
1180                        "%s.%s/%s?error=%s&error_description=%s&state=%s",
1181                        handle->redirect_prefix,
1182                        handle->tld,
1183                        handle->redirect_suffix,
1184                        "access_denied",
1185                        "User denied access",
1186                        handle->oidc->state);
1187     }
1188     else
1189     {
1190       GNUNET_asprintf (&redirect_uri,
1191                        "%s?error=%s&error_description=%s&state=%s",
1192                        handle->oidc->redirect_uri,
1193                        "access_denied",
1194                        "User denied access",
1195                        handle->oidc->state);
1196     }
1197     resp = GNUNET_REST_create_response ("");
1198     MHD_add_response_header (resp, "Location", redirect_uri);
1199     handle->proc (handle->proc_cls, resp, MHD_HTTP_FOUND);
1200     GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle);
1201     GNUNET_free (redirect_uri);
1202     return;
1203   }
1204   GNUNET_SCHEDULER_add_now (&code_redirect, handle);
1205 }
1206
1207
1208 static void
1209 lookup_redirect_uri_result (void *cls,
1210                             uint32_t rd_count,
1211                             const struct GNUNET_GNSRECORD_Data *rd)
1212 {
1213   struct RequestHandle *handle = cls;
1214   char *tmp;
1215   char *tmp_key_str;
1216   char *pos;
1217   struct GNUNET_CRYPTO_EcdsaPublicKey redirect_zone;
1218
1219   handle->gns_op = NULL;
1220   if (0 == rd_count)
1221   {
1222     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR);
1223     handle->edesc =
1224       GNUNET_strdup ("Server cannot generate ticket, redirect uri not found.");
1225     GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
1226     return;
1227   }
1228   for (int i = 0; i < rd_count; i++)
1229   {
1230     if (GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT != rd[i].record_type)
1231       continue;
1232     if (0 != strncmp (rd[i].data, handle->oidc->redirect_uri, rd[i].data_size))
1233       continue;
1234     tmp = GNUNET_strndup (rd[i].data, rd[i].data_size);
1235     if (NULL == strstr (tmp, handle->oidc->client_id))
1236     {
1237       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1238                   "Redirect uri %s does not contain client_id %s\n",
1239                   tmp,
1240                   handle->oidc->client_id);
1241     }
1242     else
1243     {
1244       pos = strrchr (tmp, (unsigned char) '.');
1245       if (NULL == pos)
1246       {
1247         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1248                     "Redirect uri %s contains client_id but is malformed\n",
1249                     tmp);
1250         GNUNET_free (tmp);
1251         continue;
1252       }
1253       *pos = '\0';
1254       handle->redirect_prefix = GNUNET_strdup (tmp);
1255       tmp_key_str = pos + 1;
1256       pos = strchr (tmp_key_str, (unsigned char) '/');
1257       if (NULL == pos)
1258       {
1259         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1260                     "Redirect uri %s contains client_id but is malformed\n",
1261                     tmp);
1262         GNUNET_free (tmp);
1263         continue;
1264       }
1265       *pos = '\0';
1266       handle->redirect_suffix = GNUNET_strdup (pos + 1);
1267
1268       GNUNET_STRINGS_string_to_data (tmp_key_str,
1269                                      strlen (tmp_key_str),
1270                                      &redirect_zone,
1271                                      sizeof(redirect_zone));
1272     }
1273     GNUNET_SCHEDULER_add_now (&build_redirect, handle);
1274     GNUNET_free (tmp);
1275     return;
1276   }
1277   handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR);
1278   handle->edesc =
1279     GNUNET_strdup ("Server cannot generate ticket, redirect uri not found.");
1280   GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
1281 }
1282
1283
1284 /**
1285  * Initiate redirect back to client.
1286  */
1287 static void
1288 client_redirect (void *cls)
1289 {
1290   struct RequestHandle *handle = cls;
1291
1292   /* Lookup client redirect uri to verify request */
1293   handle->gns_op =
1294     GNUNET_GNS_lookup (handle->gns_handle,
1295                        GNUNET_GNS_EMPTY_LABEL_AT,
1296                        &handle->oidc->client_pkey,
1297                        GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT,
1298                        GNUNET_GNS_LO_DEFAULT,
1299                        &lookup_redirect_uri_result,
1300                        handle);
1301 }
1302
1303
1304 static char *
1305 get_url_parameter_copy (const struct RequestHandle *handle, const char *key)
1306 {
1307   struct GNUNET_HashCode hc;
1308   char *value;
1309
1310   GNUNET_CRYPTO_hash (key, strlen (key), &hc);
1311   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle
1312                                                             ->url_param_map,
1313                                                             &hc))
1314     return NULL;
1315   value =
1316     GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->url_param_map, &hc);
1317   if (NULL == value)
1318     return NULL;
1319   return GNUNET_strdup (value);
1320 }
1321
1322
1323 /**
1324  * Iteration over all results finished, build final
1325  * response.
1326  *
1327  * @param cls the `struct RequestHandle`
1328  */
1329 static void
1330 build_authz_response (void *cls)
1331 {
1332   struct RequestHandle *handle = cls;
1333   struct GNUNET_HashCode cache_key;
1334
1335   char *expected_scope;
1336   char delimiter[] = " ";
1337   int number_of_ignored_parameter, iterator;
1338
1339
1340   // REQUIRED value: redirect_uri
1341   handle->oidc->redirect_uri =
1342     get_url_parameter_copy (handle, OIDC_REDIRECT_URI_KEY);
1343   if (NULL == handle->oidc->redirect_uri)
1344   {
1345     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST);
1346     handle->edesc = GNUNET_strdup ("missing parameter redirect_uri");
1347     GNUNET_SCHEDULER_add_now (&do_error, handle);
1348     return;
1349   }
1350
1351   // REQUIRED value: response_type
1352   handle->oidc->response_type =
1353     get_url_parameter_copy (handle, OIDC_RESPONSE_TYPE_KEY);
1354   if (NULL == handle->oidc->response_type)
1355   {
1356     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST);
1357     handle->edesc = GNUNET_strdup ("missing parameter response_type");
1358     GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
1359     return;
1360   }
1361
1362   // REQUIRED value: scope
1363   handle->oidc->scope = get_url_parameter_copy (handle, OIDC_SCOPE_KEY);
1364   if (NULL == handle->oidc->scope)
1365   {
1366     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_SCOPE);
1367     handle->edesc = GNUNET_strdup ("missing parameter scope");
1368     GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
1369     return;
1370   }
1371
1372   // OPTIONAL value: nonce
1373   handle->oidc->nonce = get_url_parameter_copy (handle, OIDC_NONCE_KEY);
1374
1375   // OPTIONAL value: claims
1376   handle->oidc->claims = get_url_parameter_copy (handle, OIDC_CLAIMS_KEY);
1377
1378   // TODO check other values if needed
1379   number_of_ignored_parameter =
1380     sizeof(OIDC_ignored_parameter_array) / sizeof(char *);
1381   for (iterator = 0; iterator < number_of_ignored_parameter; iterator++)
1382   {
1383     GNUNET_CRYPTO_hash (OIDC_ignored_parameter_array[iterator],
1384                         strlen (OIDC_ignored_parameter_array[iterator]),
1385                         &cache_key);
1386     if (GNUNET_YES ==
1387         GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle
1388                                                 ->url_param_map,
1389                                                 &cache_key))
1390     {
1391       handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_ACCESS_DENIED);
1392       GNUNET_asprintf (&handle->edesc,
1393                        "Server will not handle parameter: %s",
1394                        OIDC_ignored_parameter_array[iterator]);
1395       GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
1396       return;
1397     }
1398   }
1399
1400   // We only support authorization code flows.
1401   if (0 != strcmp (handle->oidc->response_type,
1402                    OIDC_EXPECTED_AUTHORIZATION_RESPONSE_TYPE))
1403   {
1404     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_UNSUPPORTED_RESPONSE_TYPE);
1405     handle->edesc = GNUNET_strdup ("The authorization server does not support "
1406                                    "obtaining this authorization code.");
1407     GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
1408     return;
1409   }
1410
1411   // Checks if scope contains 'openid'
1412   expected_scope = GNUNET_strdup (handle->oidc->scope);
1413   char *test;
1414   test = strtok (expected_scope, delimiter);
1415   while (NULL != test)
1416   {
1417     if (0 == strcmp (OIDC_EXPECTED_AUTHORIZATION_SCOPE, expected_scope))
1418       break;
1419     test = strtok (NULL, delimiter);
1420   }
1421   if (NULL == test)
1422   {
1423     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_SCOPE);
1424     handle->edesc =
1425       GNUNET_strdup ("The requested scope is invalid, unknown, or malformed.");
1426     GNUNET_SCHEDULER_add_now (&do_redirect_error, handle);
1427     GNUNET_free (expected_scope);
1428     return;
1429   }
1430
1431   GNUNET_free (expected_scope);
1432   if ((NULL == handle->oidc->login_identity) &&
1433       (GNUNET_NO == handle->oidc->user_cancelled))
1434     GNUNET_SCHEDULER_add_now (&login_redirect, handle);
1435   else
1436     GNUNET_SCHEDULER_add_now (&client_redirect, handle);
1437 }
1438
1439
1440 /**
1441  * Iterate over tlds in config
1442  */
1443 static void
1444 tld_iter (void *cls, const char *section, const char *option, const char *value)
1445 {
1446   struct RequestHandle *handle = cls;
1447   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
1448
1449   if (GNUNET_OK !=
1450       GNUNET_CRYPTO_ecdsa_public_key_from_string (value, strlen (value), &pkey))
1451   {
1452     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Skipping non key %s\n", value);
1453     return;
1454   }
1455   if (0 == GNUNET_memcmp (&pkey, &handle->oidc->client_pkey))
1456     handle->tld = GNUNET_strdup (option + 1);
1457 }
1458
1459
1460 /**
1461  * Responds to authorization GET and url-encoded POST request
1462  *
1463  * @param con_handle the connection handle
1464  * @param url the url
1465  * @param cls the RequestHandle
1466  */
1467 static void
1468 authorize_endpoint (struct GNUNET_REST_RequestHandle *con_handle,
1469                     const char *url,
1470                     void *cls)
1471 {
1472   struct RequestHandle *handle = cls;
1473   struct EgoEntry *tmp_ego;
1474   const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv_key;
1475   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
1476
1477   cookie_identity_interpretation (handle);
1478
1479   // RECOMMENDED value: state - REQUIRED for answers
1480   handle->oidc->state = get_url_parameter_copy (handle, OIDC_STATE_KEY);
1481
1482   // REQUIRED value: client_id
1483   handle->oidc->client_id = get_url_parameter_copy (handle, OIDC_CLIENT_ID_KEY);
1484   if (NULL == handle->oidc->client_id)
1485   {
1486     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST);
1487     handle->edesc = GNUNET_strdup ("missing parameter client_id");
1488     handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR;
1489     GNUNET_SCHEDULER_add_now (&do_error, handle);
1490     return;
1491   }
1492
1493   // OPTIONAL value: code_challenge
1494   handle->oidc->code_challenge = get_url_parameter_copy (handle,
1495                                                          OIDC_CODE_CHALLENGE_KEY);
1496   if (NULL == handle->oidc->code_challenge)
1497   {
1498     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1499                 "OAuth authorization request does not contain PKCE parameters!\n");
1500   }
1501
1502   if (GNUNET_OK !=
1503       GNUNET_CRYPTO_ecdsa_public_key_from_string (handle->oidc->client_id,
1504                                                   strlen (
1505                                                     handle->oidc->client_id),
1506                                                   &handle->oidc->client_pkey))
1507   {
1508     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_UNAUTHORIZED_CLIENT);
1509     handle->edesc = GNUNET_strdup ("The client is not authorized to request an "
1510                                    "authorization code using this method.");
1511     handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR;
1512     GNUNET_SCHEDULER_add_now (&do_error, handle);
1513     return;
1514   }
1515
1516   // If we know this identity, translated the corresponding TLD
1517   // TODO: We might want to have a reverse lookup functionality for TLDs?
1518   for (tmp_ego = handle->ego_head; NULL != tmp_ego; tmp_ego = tmp_ego->next)
1519   {
1520     priv_key = GNUNET_IDENTITY_ego_get_private_key (tmp_ego->ego);
1521     GNUNET_CRYPTO_ecdsa_key_get_public (priv_key, &pkey);
1522     if (0 == GNUNET_memcmp (&pkey, &handle->oidc->client_pkey))
1523     {
1524       handle->tld = GNUNET_strdup (tmp_ego->identifier);
1525       handle->ego_entry = handle->ego_tail;
1526     }
1527   }
1528   handle->oidc->scope = get_url_parameter_copy (handle, OIDC_SCOPE_KEY);
1529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Scope: %s\n", handle->oidc->scope);
1530   if (NULL == handle->tld)
1531     GNUNET_CONFIGURATION_iterate_section_values (cfg, "gns", tld_iter, handle);
1532   if (NULL == handle->tld)
1533     handle->tld = GNUNET_strdup (handle->oidc->client_id);
1534   GNUNET_SCHEDULER_add_now (&build_authz_response, handle);
1535 }
1536
1537
1538 /**
1539  * Combines an identity with a login time and responds OK to login request
1540  *
1541  * @param con_handle the connection handle
1542  * @param url the url
1543  * @param cls the RequestHandle
1544  */
1545 static void
1546 login_cont (struct GNUNET_REST_RequestHandle *con_handle,
1547             const char *url,
1548             void *cls)
1549 {
1550   struct MHD_Response *resp = GNUNET_REST_create_response ("");
1551   struct RequestHandle *handle = cls;
1552   struct GNUNET_HashCode cache_key;
1553   struct GNUNET_TIME_Absolute *current_time;
1554   struct GNUNET_TIME_Absolute *last_time;
1555   char *cookie;
1556   char *header_val;
1557   json_t *root;
1558   json_error_t error;
1559   json_t *identity;
1560   char term_data[handle->rest_handle->data_size + 1];
1561
1562   term_data[handle->rest_handle->data_size] = '\0';
1563   GNUNET_memcpy (term_data,
1564                  handle->rest_handle->data,
1565                  handle->rest_handle->data_size);
1566   root = json_loads (term_data, JSON_DECODE_ANY, &error);
1567   identity = json_object_get (root, "identity");
1568   if (! json_is_string (identity))
1569   {
1570     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1571                 "Error parsing json string from %s\n",
1572                 term_data);
1573     handle->proc (handle->proc_cls, resp, MHD_HTTP_BAD_REQUEST);
1574     json_decref (root);
1575     GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle);
1576     return;
1577   }
1578   GNUNET_asprintf (&cookie, "Identity=%s", json_string_value (identity));
1579   GNUNET_asprintf (&header_val,
1580                    "%s;Max-Age=%d",
1581                    cookie,
1582                    OIDC_COOKIE_EXPIRATION);
1583   MHD_add_response_header (resp, "Set-Cookie", header_val);
1584   MHD_add_response_header (resp, "Access-Control-Allow-Methods", "POST");
1585   GNUNET_CRYPTO_hash (cookie, strlen (cookie), &cache_key);
1586
1587   if (0 != strcmp (json_string_value (identity), "Denied"))
1588   {
1589     current_time = GNUNET_new (struct GNUNET_TIME_Absolute);
1590     *current_time = GNUNET_TIME_relative_to_absolute (
1591       GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_get_second_ (),
1592                                      OIDC_COOKIE_EXPIRATION));
1593     last_time =
1594       GNUNET_CONTAINER_multihashmap_get (OIDC_cookie_jar_map, &cache_key);
1595     GNUNET_free_non_null (last_time);
1596     GNUNET_CONTAINER_multihashmap_put (OIDC_cookie_jar_map,
1597                                        &cache_key,
1598                                        current_time,
1599                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1600   }
1601   handle->proc (handle->proc_cls, resp, MHD_HTTP_OK);
1602   GNUNET_free (cookie);
1603   GNUNET_free (header_val);
1604   json_decref (root);
1605   GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle);
1606 }
1607
1608
1609 static int
1610 check_authorization (struct RequestHandle *handle,
1611                      struct GNUNET_CRYPTO_EcdsaPublicKey *cid)
1612 {
1613   struct GNUNET_HashCode cache_key;
1614   char *authorization;
1615   char *credentials;
1616   char *basic_authorization;
1617   char *client_id;
1618   char *pass;
1619   char *expected_pass;
1620
1621   GNUNET_CRYPTO_hash (OIDC_AUTHORIZATION_HEADER_KEY,
1622                       strlen (OIDC_AUTHORIZATION_HEADER_KEY),
1623                       &cache_key);
1624   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle
1625                                                            ->header_param_map,
1626                                                            &cache_key))
1627   {
1628     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT);
1629     handle->edesc = GNUNET_strdup ("missing authorization");
1630     handle->response_code = MHD_HTTP_UNAUTHORIZED;
1631     return GNUNET_SYSERR;
1632   }
1633   authorization =
1634     GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->header_param_map,
1635                                        &cache_key);
1636
1637   // split header in "Basic" and [content]
1638   credentials = strtok (authorization, " ");
1639   if ((NULL == credentials) || (0 != strcmp ("Basic", credentials)))
1640   {
1641     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT);
1642     handle->response_code = MHD_HTTP_UNAUTHORIZED;
1643     return GNUNET_SYSERR;
1644   }
1645   credentials = strtok (NULL, " ");
1646   if (NULL == credentials)
1647   {
1648     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT);
1649     handle->response_code = MHD_HTTP_UNAUTHORIZED;
1650     return GNUNET_SYSERR;
1651   }
1652   GNUNET_STRINGS_base64_decode (credentials,
1653                                 strlen (credentials),
1654                                 (void **) &basic_authorization);
1655
1656   if (NULL == basic_authorization)
1657   {
1658     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT);
1659     handle->response_code = MHD_HTTP_UNAUTHORIZED;
1660     return GNUNET_SYSERR;
1661   }
1662   client_id = strtok (basic_authorization, ":");
1663   if (NULL == client_id)
1664   {
1665     GNUNET_free_non_null (basic_authorization);
1666     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT);
1667     handle->response_code = MHD_HTTP_UNAUTHORIZED;
1668     return GNUNET_SYSERR;
1669   }
1670   pass = strtok (NULL, ":");
1671   if (NULL == pass)
1672   {
1673     GNUNET_free_non_null (basic_authorization);
1674     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT);
1675     handle->response_code = MHD_HTTP_UNAUTHORIZED;
1676     return GNUNET_SYSERR;
1677   }
1678
1679   // check client password
1680   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg,
1681                                                           "reclaim-rest-plugin",
1682                                                           "OIDC_CLIENT_SECRET",
1683                                                           &expected_pass))
1684   {
1685     if (0 != strcmp (expected_pass, pass))
1686     {
1687       GNUNET_free_non_null (basic_authorization);
1688       GNUNET_free (expected_pass);
1689       handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT);
1690       handle->response_code = MHD_HTTP_UNAUTHORIZED;
1691       return GNUNET_SYSERR;
1692     }
1693     GNUNET_free (expected_pass);
1694   }
1695   else
1696   {
1697     GNUNET_free_non_null (basic_authorization);
1698     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR);
1699     handle->edesc = GNUNET_strdup ("gnunet configuration failed");
1700     handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR;
1701     return GNUNET_SYSERR;
1702   }
1703
1704   // check client_id
1705   for (handle->ego_entry = handle->ego_head; NULL != handle->ego_entry;
1706        handle->ego_entry = handle->ego_entry->next)
1707   {
1708     if (0 == strcmp (handle->ego_entry->keystring, client_id))
1709       break;
1710   }
1711   if (NULL == handle->ego_entry)
1712   {
1713     GNUNET_free_non_null (basic_authorization);
1714     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT);
1715     handle->response_code = MHD_HTTP_UNAUTHORIZED;
1716     return GNUNET_SYSERR;
1717   }
1718   GNUNET_STRINGS_string_to_data (client_id,
1719                                  strlen (client_id),
1720                                  cid,
1721                                  sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey));
1722
1723   GNUNET_free (basic_authorization);
1724   return GNUNET_OK;
1725 }
1726
1727
1728 const struct EgoEntry *
1729 find_ego (struct RequestHandle *handle,
1730           struct GNUNET_CRYPTO_EcdsaPublicKey *test_key)
1731 {
1732   struct EgoEntry *ego_entry;
1733   struct GNUNET_CRYPTO_EcdsaPublicKey pub_key;
1734
1735   for (ego_entry = handle->ego_head; NULL != ego_entry;
1736        ego_entry = ego_entry->next)
1737   {
1738     GNUNET_IDENTITY_ego_get_public_key (ego_entry->ego, &pub_key);
1739     if (0 == GNUNET_memcmp (&pub_key, test_key))
1740       return ego_entry;
1741   }
1742   return NULL;
1743 }
1744
1745
1746 static void
1747 persist_access_token (const struct RequestHandle *handle,
1748                       const char *access_token,
1749                       const struct GNUNET_RECLAIM_Ticket *ticket)
1750 {
1751   struct GNUNET_HashCode hc;
1752   struct GNUNET_RECLAIM_Ticket *ticketbuf;
1753
1754   GNUNET_CRYPTO_hash (access_token, strlen (access_token), &hc);
1755   ticketbuf = GNUNET_new (struct GNUNET_RECLAIM_Ticket);
1756   *ticketbuf = *ticket;
1757   GNUNET_assert (GNUNET_SYSERR !=
1758                  GNUNET_CONTAINER_multihashmap_put (
1759                    OIDC_access_token_map,
1760                    &hc,
1761                    ticketbuf,
1762                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1763 }
1764
1765
1766 /**
1767  * Responds to token url-encoded POST request
1768  *
1769  * @param con_handle the connection handle
1770  * @param url the url
1771  * @param cls the RequestHandle
1772  */
1773 static void
1774 token_endpoint (struct GNUNET_REST_RequestHandle *con_handle,
1775                 const char *url,
1776                 void *cls)
1777 {
1778   struct RequestHandle *handle = cls;
1779   const struct EgoEntry *ego_entry;
1780   struct GNUNET_TIME_Relative expiration_time;
1781   struct GNUNET_RECLAIM_AttributeList *cl = NULL;
1782   struct GNUNET_RECLAIM_AttestationList *al = NULL;
1783   struct GNUNET_RECLAIM_Ticket ticket;
1784   struct GNUNET_CRYPTO_EcdsaPublicKey cid;
1785   const struct GNUNET_CRYPTO_EcdsaPrivateKey *privkey;
1786   struct GNUNET_HashCode cache_key;
1787   struct MHD_Response *resp;
1788   char *grant_type;
1789   char *code;
1790   char *json_response;
1791   char *id_token;
1792   char *access_token;
1793   char *jwt_secret;
1794   char *nonce;
1795   char *code_verifier;
1796
1797   /*
1798    * Check Authorization
1799    */
1800   if (GNUNET_SYSERR == check_authorization (handle, &cid))
1801   {
1802     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1803                 "OIDC authorization for token endpoint failed\n");
1804     GNUNET_SCHEDULER_add_now (&do_error, handle);
1805     return;
1806   }
1807
1808   /*
1809    * Check parameter
1810    */
1811
1812   // TODO Do not allow multiple equal parameter names
1813   // REQUIRED grant_type
1814   GNUNET_CRYPTO_hash (OIDC_GRANT_TYPE_KEY,
1815                       strlen (OIDC_GRANT_TYPE_KEY),
1816                       &cache_key);
1817   grant_type = get_url_parameter_copy (handle, OIDC_GRANT_TYPE_KEY);
1818   if (NULL == grant_type)
1819   {
1820     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST);
1821     handle->edesc = GNUNET_strdup ("missing parameter grant_type");
1822     handle->response_code = MHD_HTTP_BAD_REQUEST;
1823     GNUNET_SCHEDULER_add_now (&do_error, handle);
1824     return;
1825   }
1826
1827   // Check parameter grant_type == "authorization_code"
1828   if (0 != strcmp (OIDC_GRANT_TYPE_VALUE, grant_type))
1829   {
1830     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_UNSUPPORTED_GRANT_TYPE);
1831     handle->response_code = MHD_HTTP_BAD_REQUEST;
1832     GNUNET_free (grant_type);
1833     GNUNET_SCHEDULER_add_now (&do_error, handle);
1834     return;
1835   }
1836   GNUNET_free (grant_type);
1837   // REQUIRED code
1838   code = get_url_parameter_copy (handle, OIDC_CODE_KEY);
1839   if (NULL == code)
1840   {
1841     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST);
1842     handle->edesc = GNUNET_strdup ("missing parameter code");
1843     handle->response_code = MHD_HTTP_BAD_REQUEST;
1844     GNUNET_SCHEDULER_add_now (&do_error, handle);
1845     return;
1846   }
1847   ego_entry = find_ego (handle, &cid);
1848   if (NULL == ego_entry)
1849   {
1850     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST);
1851     handle->edesc = GNUNET_strdup ("Unknown client");
1852     handle->response_code = MHD_HTTP_BAD_REQUEST;
1853     GNUNET_free (code);
1854     GNUNET_SCHEDULER_add_now (&do_error, handle);
1855     return;
1856   }
1857   privkey = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego);
1858
1859   // REQUIRED code verifier
1860   code_verifier = get_url_parameter_copy (handle, OIDC_CODE_VERIFIER_KEY);
1861   if (NULL == code_verifier)
1862   {
1863     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1864                 "OAuth authorization request does not contain PKCE parameters!\n");
1865
1866   }
1867
1868   // decode code
1869   if (GNUNET_OK != OIDC_parse_authz_code (privkey, code, code_verifier, &ticket,
1870                                           &cl, &al, &nonce))
1871   {
1872     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST);
1873     handle->edesc = GNUNET_strdup ("invalid code");
1874     handle->response_code = MHD_HTTP_BAD_REQUEST;
1875     GNUNET_free (code);
1876     GNUNET_SCHEDULER_add_now (&do_error, handle);
1877     return;
1878   }
1879   GNUNET_free (code);
1880
1881   // create jwt
1882   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg,
1883                                                         "reclaim-rest-plugin",
1884                                                         "expiration_time",
1885                                                         &expiration_time))
1886   {
1887     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR);
1888     handle->edesc = GNUNET_strdup ("gnunet configuration failed");
1889     handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR;
1890     GNUNET_SCHEDULER_add_now (&do_error, handle);
1891     return;
1892   }
1893
1894
1895   // TODO OPTIONAL acr,amr,azp
1896   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg,
1897                                                           "reclaim-rest-plugin",
1898                                                           "jwt_secret",
1899                                                           &jwt_secret))
1900   {
1901     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST);
1902     handle->edesc = GNUNET_strdup ("No signing secret configured!");
1903     handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR;
1904     GNUNET_SCHEDULER_add_now (&do_error, handle);
1905     return;
1906   }
1907   id_token = OIDC_id_token_new (&ticket.audience,
1908                                 &ticket.identity,
1909                                 cl,
1910                                 al,
1911                                 &expiration_time,
1912                                 (NULL != nonce) ? nonce : NULL,
1913                                 jwt_secret);
1914   access_token = OIDC_access_token_new ();
1915   OIDC_build_token_response (access_token,
1916                              id_token,
1917                              &expiration_time,
1918                              &json_response);
1919
1920   persist_access_token (handle, access_token, &ticket);
1921   resp = GNUNET_REST_create_response (json_response);
1922   MHD_add_response_header (resp, "Cache-Control", "no-store");
1923   MHD_add_response_header (resp, "Pragma", "no-cache");
1924   MHD_add_response_header (resp, "Content-Type", "application/json");
1925   handle->proc (handle->proc_cls, resp, MHD_HTTP_OK);
1926   GNUNET_RECLAIM_attribute_list_destroy (cl);
1927   GNUNET_RECLAIM_attestation_list_destroy (al);
1928   GNUNET_free (access_token);
1929   GNUNET_free (json_response);
1930   GNUNET_free (id_token);
1931   GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle);
1932 }
1933
1934
1935 /**
1936  * Collects claims and stores them in handle
1937  */
1938 static void
1939 consume_ticket (void *cls,
1940                 const struct GNUNET_CRYPTO_EcdsaPublicKey *identity,
1941                 const struct GNUNET_RECLAIM_Attribute *attr,
1942                 const struct GNUNET_RECLAIM_Attestation *attest)
1943 {
1944   struct RequestHandle *handle = cls;
1945   handle->idp_op = NULL;
1946
1947   if (NULL == identity)
1948   {
1949     GNUNET_SCHEDULER_add_now (&return_userinfo_response, handle);
1950     return;
1951   }
1952   if (GNUNET_YES == GNUNET_RECLAIM_id_is_zero (&attr->attestation))
1953   {
1954     char *tmp_value;
1955     json_t *value;
1956     tmp_value = GNUNET_RECLAIM_attribute_value_to_string (attr->type,
1957                                                           attr->data,
1958                                                           attr->data_size);
1959     value = json_string (tmp_value);
1960     json_object_set_new (handle->oidc->response, attr->name, value);
1961     GNUNET_free (tmp_value);
1962     return;
1963   }
1964   json_t *claim_sources;
1965   json_t *claim_sources_jwt;
1966   json_t *claim_names;
1967   char *attest_val_str;
1968   claim_sources = json_object_get (handle->oidc->response,"_claim_sources");
1969   claim_names = json_object_get (handle->oidc->response,"_claim_names");
1970   attest_val_str =
1971     GNUNET_RECLAIM_attestation_value_to_string (attest->type,
1972                                                 attest->data,
1973                                                 attest->data_size);
1974   if ((NULL == claim_sources) && (NULL == claim_names) )
1975   {
1976     claim_sources = json_object ();
1977     claim_names = json_object ();
1978   }
1979   char *source_name;
1980   int i = 0;
1981   GNUNET_asprintf (&source_name, "src%d", i);
1982   while (NULL != (claim_sources_jwt = json_object_get (claim_sources,
1983                                                        source_name)))
1984   {
1985     if (0 == strcmp (json_string_value (json_object_get (claim_sources_jwt,
1986                                                          "JWT")),
1987                      attest_val_str))
1988     {
1989       // Adapt only the claim names
1990       json_object_set_new (claim_names, attr->data,
1991                            json_string (source_name));
1992       json_object_set (handle->oidc->response,
1993                        "_claim_names", claim_names);
1994       break;
1995     }
1996     i++;
1997     GNUNET_free (source_name);
1998     GNUNET_asprintf (&source_name, "src%d", i);
1999   }
2000
2001   // Create new one
2002   if (NULL == claim_sources_jwt)
2003   {
2004     claim_sources_jwt = json_object ();
2005     // Set the JWT for names
2006     json_object_set_new (claim_names, attr->data,
2007                          json_string (source_name));
2008     // Set the JWT for the inner source
2009     json_object_set_new (claim_sources_jwt, "JWT",
2010                          json_string (attest_val_str));
2011     // Set the JWT for the source
2012     json_object_set_new (claim_sources, source_name, claim_sources_jwt);
2013     // Set as claims
2014     json_object_set (handle->oidc->response, "_claim_names", claim_names);
2015     json_object_set (handle->oidc->response, "_claim_sources",claim_sources);
2016   }
2017
2018   json_decref (claim_sources);
2019   json_decref (claim_names);
2020   json_decref (claim_sources_jwt);
2021   GNUNET_free (attest_val_str);
2022 }
2023
2024
2025 /**
2026  * Responds to userinfo GET and url-encoded POST request
2027  *
2028  * @param con_handle the connection handle
2029  * @param url the url
2030  * @param cls the RequestHandle
2031  */
2032 static void
2033 userinfo_endpoint (struct GNUNET_REST_RequestHandle *con_handle,
2034                    const char *url,
2035                    void *cls)
2036 {
2037   // TODO expiration time
2038   struct RequestHandle *handle = cls;
2039   char delimiter[] = " ";
2040   struct GNUNET_HashCode cache_key;
2041   char *authorization;
2042   char *authorization_type;
2043   char *authorization_access_token;
2044   struct GNUNET_RECLAIM_Ticket *ticket;
2045   const struct EgoEntry *ego_entry;
2046   const struct GNUNET_CRYPTO_EcdsaPrivateKey *privkey;
2047
2048   GNUNET_CRYPTO_hash (OIDC_AUTHORIZATION_HEADER_KEY,
2049                       strlen (OIDC_AUTHORIZATION_HEADER_KEY),
2050                       &cache_key);
2051   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle
2052                                                            ->header_param_map,
2053                                                            &cache_key))
2054   {
2055     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN);
2056     handle->edesc = GNUNET_strdup ("No Access Token");
2057     handle->response_code = MHD_HTTP_UNAUTHORIZED;
2058     GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle);
2059     return;
2060   }
2061   authorization =
2062     GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->header_param_map,
2063                                        &cache_key);
2064
2065   // split header in "Bearer" and access_token
2066   authorization = GNUNET_strdup (authorization);
2067   authorization_type = strtok (authorization, delimiter);
2068   if ((NULL == authorization_type) ||
2069       (0 != strcmp ("Bearer", authorization_type)))
2070   {
2071     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN);
2072     handle->edesc = GNUNET_strdup ("No Access Token");
2073     handle->response_code = MHD_HTTP_UNAUTHORIZED;
2074     GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle);
2075     GNUNET_free (authorization);
2076     return;
2077   }
2078   authorization_access_token = strtok (NULL, delimiter);
2079   if (NULL == authorization_access_token)
2080   {
2081     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN);
2082     handle->edesc = GNUNET_strdup ("Access token missing");
2083     handle->response_code = MHD_HTTP_UNAUTHORIZED;
2084     GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle);
2085     GNUNET_free (authorization);
2086     return;
2087   }
2088
2089   GNUNET_CRYPTO_hash (authorization_access_token,
2090                       strlen (authorization_access_token),
2091                       &cache_key);
2092   if (GNUNET_NO ==
2093       GNUNET_CONTAINER_multihashmap_contains (OIDC_access_token_map,
2094                                               &cache_key))
2095   {
2096     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN);
2097     handle->edesc = GNUNET_strdup ("The access token expired");
2098     handle->response_code = MHD_HTTP_UNAUTHORIZED;
2099     GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle);
2100     GNUNET_free (authorization);
2101     return;
2102   }
2103   ticket =
2104     GNUNET_CONTAINER_multihashmap_get (OIDC_access_token_map, &cache_key);
2105   GNUNET_assert (NULL != ticket);
2106   ego_entry = find_ego (handle, &ticket->audience);
2107   if (NULL == ego_entry)
2108   {
2109     handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN);
2110     handle->edesc = GNUNET_strdup ("The access token expired");
2111     handle->response_code = MHD_HTTP_UNAUTHORIZED;
2112     GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle);
2113     GNUNET_free (authorization);
2114     return;
2115   }
2116
2117   handle->idp = GNUNET_RECLAIM_connect (cfg);
2118   handle->oidc->response = json_object ();
2119   json_object_set_new (handle->oidc->response,
2120                        "sub",
2121                        json_string (ego_entry->keystring));
2122   privkey = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego);
2123   handle->idp_op = GNUNET_RECLAIM_ticket_consume (handle->idp,
2124                                                   privkey,
2125                                                   ticket,
2126                                                   consume_ticket,
2127                                                   handle);
2128   GNUNET_free (authorization);
2129 }
2130
2131
2132 /**
2133  * Handle rest request
2134  *
2135  * @param handle the request handle
2136  */
2137 static void
2138 init_cont (struct RequestHandle *handle)
2139 {
2140   struct GNUNET_REST_RequestHandlerError err;
2141   static const struct GNUNET_REST_RequestHandler handlers[] =
2142   { { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_AUTHORIZE, &authorize_endpoint },
2143     { MHD_HTTP_METHOD_POST,
2144       GNUNET_REST_API_NS_AUTHORIZE,
2145       &authorize_endpoint },   // url-encoded
2146     { MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_LOGIN, &login_cont },
2147     { MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_TOKEN, &token_endpoint },
2148     { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_USERINFO, &userinfo_endpoint },
2149     { MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_USERINFO, &userinfo_endpoint },
2150     { MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_OIDC, &options_cont },
2151     GNUNET_REST_HANDLER_END };
2152
2153   if (GNUNET_NO ==
2154       GNUNET_REST_handle_request (handle->rest_handle, handlers, &err, handle))
2155   {
2156     handle->response_code = err.error_code;
2157     GNUNET_SCHEDULER_add_now (&do_error, handle);
2158   }
2159 }
2160
2161
2162 /**
2163  * If listing is enabled, prints information about the egos.
2164  *
2165  * This function is initially called for all egos and then again
2166  * whenever a ego's identifier changes or if it is deleted.  At the
2167  * end of the initial pass over all egos, the function is once called
2168  * with 'NULL' for 'ego'. That does NOT mean that the callback won't
2169  * be invoked in the future or that there was an error.
2170  *
2171  * When used with 'GNUNET_IDENTITY_create' or 'GNUNET_IDENTITY_get',
2172  * this function is only called ONCE, and 'NULL' being passed in
2173  * 'ego' does indicate an error (i.e. name is taken or no default
2174  * value is known).  If 'ego' is non-NULL and if '*ctx'
2175  * is set in those callbacks, the value WILL be passed to a subsequent
2176  * call to the identity callback of 'GNUNET_IDENTITY_connect' (if
2177  * that one was not NULL).
2178  *
2179  * When an identity is renamed, this function is called with the
2180  * (known) ego but the NEW identifier.
2181  *
2182  * When an identity is deleted, this function is called with the
2183  * (known) ego and "NULL" for the 'identifier'.  In this case,
2184  * the 'ego' is henceforth invalid (and the 'ctx' should also be
2185  * cleaned up).
2186  *
2187  * @param cls closure
2188  * @param ego ego handle
2189  * @param ctx context for application to store data for this ego
2190  *                 (during the lifetime of this process, initially NULL)
2191  * @param identifier identifier assigned by the user for this ego,
2192  *                   NULL if the user just deleted the ego and it
2193  *                   must thus no longer be used
2194  */
2195 static void
2196 list_ego (void *cls,
2197           struct GNUNET_IDENTITY_Ego *ego,
2198           void **ctx,
2199           const char *identifier)
2200 {
2201   struct RequestHandle *handle = cls;
2202   struct EgoEntry *ego_entry;
2203   struct GNUNET_CRYPTO_EcdsaPublicKey pk;
2204
2205   if ((NULL == ego) && (ID_REST_STATE_INIT == handle->state))
2206   {
2207     handle->state = ID_REST_STATE_POST_INIT;
2208     init_cont (handle);
2209     return;
2210   }
2211   GNUNET_assert (NULL != ego);
2212   if (ID_REST_STATE_INIT == handle->state)
2213
2214   {
2215     ego_entry = GNUNET_new (struct EgoEntry);
2216     GNUNET_IDENTITY_ego_get_public_key (ego, &pk);
2217     ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk);
2218     ego_entry->ego = ego;
2219     ego_entry->identifier = GNUNET_strdup (identifier);
2220     GNUNET_CONTAINER_DLL_insert_tail (handle->ego_head,
2221                                       handle->ego_tail,
2222                                       ego_entry);
2223     return;
2224   }
2225   /* Ego renamed or added */
2226   if (identifier != NULL)
2227   {
2228     for (ego_entry = handle->ego_head; NULL != ego_entry;
2229          ego_entry = ego_entry->next)
2230     {
2231       if (ego_entry->ego == ego)
2232       {
2233         /* Rename */
2234         GNUNET_free (ego_entry->identifier);
2235         ego_entry->identifier = GNUNET_strdup (identifier);
2236         break;
2237       }
2238     }
2239     if (NULL == ego_entry)
2240     {
2241       /* Add */
2242       ego_entry = GNUNET_new (struct EgoEntry);
2243       GNUNET_IDENTITY_ego_get_public_key (ego, &pk);
2244       ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk);
2245       ego_entry->ego = ego;
2246       ego_entry->identifier = GNUNET_strdup (identifier);
2247       GNUNET_CONTAINER_DLL_insert_tail (handle->ego_head,
2248                                         handle->ego_tail,
2249                                         ego_entry);
2250     }
2251   }
2252   else
2253   {
2254     /* Delete */
2255     for (ego_entry = handle->ego_head; NULL != ego_entry;
2256          ego_entry = ego_entry->next)
2257     {
2258       if (ego_entry->ego == ego)
2259         break;
2260     }
2261     if (NULL == ego_entry)
2262       return; /* Not found */
2263
2264     GNUNET_CONTAINER_DLL_remove (handle->ego_head,
2265                                  handle->ego_tail,
2266                                  ego_entry);
2267     GNUNET_free (ego_entry->identifier);
2268     GNUNET_free (ego_entry->keystring);
2269     GNUNET_free (ego_entry);
2270     return;
2271   }
2272 }
2273
2274
2275 static void
2276 rest_identity_process_request (struct GNUNET_REST_RequestHandle *rest_handle,
2277                                GNUNET_REST_ResultProcessor proc,
2278                                void *proc_cls)
2279 {
2280   struct RequestHandle *handle = GNUNET_new (struct RequestHandle);
2281
2282   handle->oidc = GNUNET_new (struct OIDC_Variables);
2283   if (NULL == OIDC_cookie_jar_map)
2284     OIDC_cookie_jar_map = GNUNET_CONTAINER_multihashmap_create (10,
2285                                                                 GNUNET_NO);
2286   if (NULL == OIDC_access_token_map)
2287     OIDC_access_token_map =
2288       GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
2289   handle->response_code = 0;
2290   handle->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
2291   handle->proc_cls = proc_cls;
2292   handle->proc = proc;
2293   handle->state = ID_REST_STATE_INIT;
2294   handle->rest_handle = rest_handle;
2295
2296   handle->url = GNUNET_strdup (rest_handle->url);
2297   if (handle->url[strlen (handle->url) - 1] == '/')
2298     handle->url[strlen (handle->url) - 1] = '\0';
2299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n");
2300   handle->identity_handle = GNUNET_IDENTITY_connect (cfg, &list_ego, handle);
2301   handle->gns_handle = GNUNET_GNS_connect (cfg);
2302   handle->namestore_handle = GNUNET_NAMESTORE_connect (cfg);
2303   handle->timeout_task =
2304     GNUNET_SCHEDULER_add_delayed (handle->timeout, &do_timeout, handle);
2305   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected\n");
2306 }
2307
2308
2309 /**
2310    * Entry point for the plugin.
2311    *
2312    * @param cls Config info
2313    * @return NULL on error, otherwise the plugin context
2314    */
2315 void *
2316 libgnunet_plugin_rest_openid_connect_init (void *cls)
2317 {
2318   static struct Plugin plugin;
2319   struct GNUNET_REST_Plugin *api;
2320
2321   cfg = cls;
2322   if (NULL != plugin.cfg)
2323     return NULL;     /* can only initialize once! */
2324   memset (&plugin, 0, sizeof(struct Plugin));
2325   plugin.cfg = cfg;
2326   api = GNUNET_new (struct GNUNET_REST_Plugin);
2327   api->cls = &plugin;
2328   api->name = GNUNET_REST_API_NS_OIDC;
2329   api->process_request = &rest_identity_process_request;
2330   GNUNET_asprintf (&allow_methods,
2331                    "%s, %s, %s, %s, %s",
2332                    MHD_HTTP_METHOD_GET,
2333                    MHD_HTTP_METHOD_POST,
2334                    MHD_HTTP_METHOD_PUT,
2335                    MHD_HTTP_METHOD_DELETE,
2336                    MHD_HTTP_METHOD_OPTIONS);
2337
2338   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339               _ ("OpenID Connect REST API initialized\n"));
2340   return api;
2341 }
2342
2343
2344 /**
2345    * Exit point from the plugin.
2346    *
2347    * @param cls the plugin context (as returned by "init")
2348    * @return always NULL
2349    */
2350 void *
2351 libgnunet_plugin_rest_openid_connect_done (void *cls)
2352 {
2353   struct GNUNET_REST_Plugin *api = cls;
2354   struct Plugin *plugin = api->cls;
2355
2356   plugin->cfg = NULL;
2357
2358   struct GNUNET_CONTAINER_MultiHashMapIterator *hashmap_it;
2359   void *value = NULL;
2360   hashmap_it =
2361     GNUNET_CONTAINER_multihashmap_iterator_create (OIDC_cookie_jar_map);
2362   while (GNUNET_YES ==
2363          GNUNET_CONTAINER_multihashmap_iterator_next (hashmap_it, NULL,
2364                                                       value))
2365     GNUNET_free_non_null (value);
2366   GNUNET_CONTAINER_multihashmap_iterator_destroy (hashmap_it);
2367   GNUNET_CONTAINER_multihashmap_destroy (OIDC_cookie_jar_map);
2368
2369   hashmap_it =
2370     GNUNET_CONTAINER_multihashmap_iterator_create (OIDC_access_token_map);
2371   while (GNUNET_YES ==
2372          GNUNET_CONTAINER_multihashmap_iterator_next (hashmap_it, NULL,
2373                                                       value))
2374     GNUNET_free_non_null (value);
2375   GNUNET_CONTAINER_multihashmap_destroy (OIDC_access_token_map);
2376   GNUNET_CONTAINER_multihashmap_iterator_destroy (hashmap_it);
2377   GNUNET_free_non_null (allow_methods);
2378   GNUNET_free (api);
2379   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380               "OpenID Connect REST plugin is finished\n");
2381   return NULL;
2382 }
2383
2384
2385 /* end of plugin_rest_openid_connect.c */