This repository is currently being migrated. It's locked while the migration is in progress.
forked from beingmeta/framerd-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth.scm
1139 lines (1084 loc) · 40.6 KB
/
oauth.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;; -*- Mode: Scheme; Character-encoding: utf-8; -*-
;;; Copyright (C) 2010-2018 beingmeta, inc. All rights reserved
(in-module 'oauth)
(use-module '{fdweb reflection xhtml/auth varconfig opts})
(use-module '{texttools logger})
(define %used_modules '{varconfig xhtml/auth})
(define %volatile '{getuser oauth-sessionfn})
(define-init getuser #f)
(varconfig! oauth:getuser getuser)
(define-init default-json-flags 8)
(define-init default-callback #f)
(varconfig! oauth:callback default-callback)
(define-init default-endpoint #f)
(varconfig! oauth:endpoint default-endpoint)
(define-init default-verify-endpoint #f)
(varconfig! oauth:verifier default-verify-endpoint)
(define-init curlcache #f)
(varconfig! oauth:curlcache curlcache)
(define default-expect #f)
(define-init lograw #f)
(define (oauth-lograw-config var (val))
(cond ((not (bound? val)) lograw)
((not val) (set! lograw #f))
((eq? val 'reset) (set! lograw (make-hashtable)))
((and (eq? val #t) lograw)
(lognotice |OAUTH/lograw|
"Raw logging is already writing to " lograw))
((string? val)
(onerror (set! lograw (open-index val))
(lambda (ex)
(logcrit |OAUTH/lograw|
"Unexpected error " (error-condition ex) " in " (error-context ex)
(when (error-details ex)
(printout " [" (error-details ex) "]"))
(when (error-irritant? ex)
(printout " irritant:\n" (pprint (error-irritant ex))))))))
((or (hashtable? val) (index? val))
(set! lograw val))
(else (irritant val
|InvalidLogRaw| "Couldn't use the value for logging raw responses"))))
(config-def! 'oauth:lograw oauth-lograw-config)
(define-init keep-raw #f)
(varconfig! oauth:keepraw keep-raw config:boolean)
(module-export!
'{oauth oauth/spec oauth/start oauth/refresh!
oauth/request oauth/authurl oauth/verify
oauth/getaccess oauth/getclient
oauth/call oauth/call* oauth/call/req
oauth/get oauth/post oauth/put
oauth/sigstring oauth/callsig
oauth/getinfo oauth/setinfo! oauth/known?})
(define-init %loglevel %notice!)
;;(set! %loglevel %debug%)
(define (get-endpoint endpoint args spec)
(cond ((not endpoint)
(or (getopt args 'endpoint)
(getopt spec 'endpoint)
(irritant spec |NoEndpoint|)))
((not (string? endpoint))
(irritant endpoint |NotAString|))
((has-prefix endpoint {"https:" "http:"}) endpoint)
(else (let* ((base (or (getopt args 'endpoint)
(getopt spec 'endpoint)))
(parsed (and base (parseuri base))))
(if (not parsed)
(or base endpoint)
(if (has-prefix endpoint "/")
(glom (get parsed 'scheme) "://"
(get parsed 'hostname)
endpoint)
;; TODO: Smarts to strip prefix and suffix
(glom base
(and (not (has-suffix base "/")) "/")
endpoint)))))))
(define (getxmldata string)
(let ((parsed (xmlparse string '{data slotify})))
(reject (elts parsed) string?)))
(define (parsereqdata req (ctype) (content) (response))
(default! ctype (try (get req 'content-type) #f))
(default! content (try (get req '%content) #f))
(default! response (try (get req 'response) #f))
(debug%watch "PARSEREQDATA" response ctype content)
(if (and response ctype content
(number? response)
(>= response 200)
(< response 300))
(if (search "json" ctype)
(jsonparse content (getopt req 'jsonflags default-json-flags))
(if (search "xml" ctype)
(getxmldata content)
;; This comes across as text/plain from FB,
;; but should probably be something else.
(if (search "form" ctype)
(cgiparse content)
(if (textsearch #((bol) (spaces*) "<") content)
(getxmldata content)
(if (textsearch #((bol) (spaces*) {"{" "["})
content)
(jsonparse content (getopt req 'jsonflags default-json-flags))
(cgiparse content)))))
req)
(frame-create #f
'status response
'ctype (tryif ctype ctype)
'content (or content '()))))
(define (getreqdata req . args)
(if (and lograw (test req 'reqid))
(modify-frame
(if (null? args)
(parsereqdata req)
(apply parsereqdata req args))
'reqid (get req 'reqid))
(if (null? args)
(parsereqdata req)
(apply parsereqdata req args))))
;;; Server info
(define oauth-servers
`#[TWITTER
#[REQUEST "https://api.twitter.com/oauth/request_token"
VERIFY "https://api.twitter.com/oauth/access_token"
ACCESS "https://api.twitter.com/oauth/access_token"
AUTHORIZE "https://api.twitter.com/oauth/authorize"
AUTHENTICATE "https://api.twitter.com/oauth/authenticate"
KEY TWITTER:KEY SECRET TWITTER:SECRET
VERSION "1.0"
REALM TWITTER10
NAME "Twitter"]
TWITTER20
#[ACCESS "https://api.twitter.com/oauth2/token"
AUTHORIZE "https://api.twitter.com/oauth/authorize"
;; AUTHENTICATE "https://api.twitter.com/oauth/authenticate"
KEY TWITTER:KEY SECRET TWITTER:SECRET
;;ACCESS_TOKEN "oauth_token"
ACCESS_TOKEN HTTP
VERSION "2.0"
REALM TWITTER20
NAME "Twitter"]
LINKEDIN
#[AUTHORIZE "https://www.linkedin.com/uas/oauth2/authorization"
ACCESS "https://www.linkedin.com/uas/oauth2/accessToken"
KEY LINKEDIN:KEY SECRET LINKEDIN:SECRET
VERSION "2.0"
SCOPE "r_fullprofile r_network r_emailaddress rw_groups"
ACCESS_TOKEN "oauth2_access_token"
REALM LINKEDIN
NAME "LinkedIn"]
DROPBOX
#[AUTHORIZE "https://www.dropbox.com/1/oauth2/authorize"
ACCESS "https://api.dropbox.com/1/oauth2/token"
KEY DROPBOX:KEY SECRET DROPBOX:SECRET
;; ACCESS_TOKEN HTTP
VERSION "2.0"
REALM DROPBOX
NAME "Dropbox"]
GOOGLE
#[AUTHORIZE "https://accounts.google.com/o/oauth2/auth"
ACCESS "https://accounts.google.com/o/oauth2/token"
AUTH_ARGS #["access_type" "offline"]
KEY GOOGLE:KEY SECRET GOOGLE:SECRET
SCOPE "openid email profile"
VERSION "2.0"
REALM GOOGLE
ACCESS_TOKEN HTTP
NAME "Google"]
GDRIVE
#[AUTHORIZE "https://accounts.google.com/o/oauth2/auth"
ACCESS "https://accounts.google.com/o/oauth2/token"
AUTH_ARGS #["access_type" "offline"]
KEY GOOGLE:KEY SECRET GOOGLE:SECRET
SCOPE "openid email profile https://www.googleapis.com/auth/drive.file"
VERSION "2.0"
REALM GOOGLE
ACCESS_TOKEN HTTP
NAME "Google"]
GPLUS
#[AUTHORIZE "https://accounts.google.com/o/oauth2/auth"
ACCESS "https://accounts.google.com/o/oauth2/token"
KEY GPLUS:KEY SECRET GPLUS:SECRET
SCOPE "https://www.googleapis.com/auth/plus.me"
VERSION "2.0"
ACCESS_TOKEN HTTP
REALM GPLUS
NAME "Google+"]
FACEBOOK
#[AUTHORIZE "https://www.facebook.com/dialog/oauth"
ACCESS "https://graph.facebook.com/oauth/access_token"
KEY FB:KEY SECRET FB:SECRET
SCOPE "publish_actions,publish_stream,user_about_me,offline_access"
VERSION "2.0"
REALM FACEBOOK
NAME "Facebook"]
AMAZON
#[AUTHORIZE "https://www.amazon.com/ap/oa"
ACCESS "https://api.amazon.com/auth/o2/token"
KEY AMAZON:KEY SECRET AMAZON:SECRET
SCOPE "profile postal_code"
VERSION "2.0"
REALM AMAZON
NAME "Amazon"]
PAYPAL
#[AUTHORIZE "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize"
ACCESS "https://api.paypal.com/v1/identity/openidconnect/tokenservice"
KEY PP:LOGINKEY SECRET PP:LOGINSECRET
SCOPE "openid profile email"
VERSION "2.0"
REALM PAYPAL
ACCESS_TOKEN HTTP
NAME "Paypal"]
PAYPALTEST
#[AUTHORIZE
"https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize"
ACCESS
"https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice"
KEY PP:TESTKEY SECRET PP:TESTSECRET
SCOPE "openid profile email"
VERSION "2.0"
REALM PAYPAL
ACCESS_TOKEN HTTP
NAME "Paypal Test"]
PAYPALAPI
#[AUTHORIZE
"https://api.paypal.com/v1/oauth2/token"
ACCESS
"https://api.paypal.com/v1/oauth2/token"
KEY PP:KEY SECRET PP:SECRET
SCOPE ""
VERSION "2.0"
REALM PAYPAL
ACCESS_TOKEN HTTP
NAME "Paypal Test"]
PAYPALAPITEST
#[AUTHORIZE
"https://api.sandbox.paypal.com/v1/oauth2/token"
ACCESS
"https://api.sandbox.paypal.com/v1/oauth2/token"
KEY PP:TESTKEY SECRET PP:TESTSECRET
SCOPE ""
VERSION "2.0"
REALM PAYPAL
ACCESS_TOKEN HTTP
NAME "Paypal Test"]
DWOLLA
#[AUTHORIZE "https://www.dwolla.com/oauth/v2/authenticate"
ACCESS "https://www.dwolla.com/oauth/v2/token"
KEY DWOLLA:KEY SECRET DWOLLA:SECRET
SCOPE "openid profile email"
VERSION "2.0"
REALM DWOLLA
NAME "Dwolla"]
REDDIT
#[AUTHORIZE "https://www.reddit.com/api/v1/authorize"
ACCESS "https://www.reddit.com/api/v1/access_token"
KEY REDDIT:KEY SECRET REDDIT:SECRET
VERSION "2.0"
ENDPOINT "https://oauth.reddit.com/api/v1/"
;; SCOPE "r_fullprofile r_network r_emailaddress rw_groups"
;; ACCESS_TOKEN "oauth2_access_token"
ACCESS_TOKEN HTTP
REALM REDDIT
NAME "Reddit"]])
(define (oauth/provider spec) (get oauth-servers spec))
(module-export! 'oauth/provider)
(config-def! 'oauth:providers
(lambda (var (val))
(cond ((not (bound? val))
(get oauth-servers (getkeys oauth-servers)))
((and (or (slotmap? val) (schemap? val))
(exists? (get val 'realm)))
(when (and (exists? (get oauth-servers (get val 'realm)))
(not (test oauth-servers (get val 'realm) val)))
(logwarn OAUTH/REDEFINE "Redefining OAUTH specification for "
(get val 'realm) ", changes may be lost!"))
(do-choices val
(store! oauth-servers (get val 'realm) val)))
(else (irritant val OAUTH:BADSPEC
"Invalid OAUTH provider spec")))))
(define (thisurl)
(tryif (req/get 'request_uri #f)
(stringout (if (= (req/get 'SERVER_PORT) 443) "https://" "http://")
(req/get 'SERVER_NAME)
(when (req/test 'SERVER_PORT)
(unless (or (= (req/get 'SERVER_PORT) 80)
(= (req/get 'SERVER_PORT) 443))
(printout ":" (req/get 'SERVER_PORT))))
(uribase (try (req/get 'request_uri) (req/get 'path_info))))))
;;; Managing state
(define-init oauth-pending (make-hashtable))
(define-init oauth-sessionfn #f)
(varconfig! oauth:sessionstore oauth-sessionfn)
(define (oauth/pending id)
(try (get oauth-pending id)
(tryif oauth-sessionfn
(let ((pending (oauth-sessionfn id)))
(if (exists? pending)
(store! oauth-pending id (oauth/spec pending)))
pending))))
(define (oauth/pending! id (state))
(info%watch "OAUTH/PENDING!" id state oauth-sessionfn)
(if (and (bound? state) state)
(store! oauth-pending id state)
(drop! oauth-pending id))
(when oauth-sessionfn
(if (bound? state)
(if (pair? state)
(let ((copied (deep-copy (car state)))
(realm (getopt state 'realm)))
(store! copied 'realm realm)
(oauth-sessionfn id copied))
(if state
(oauth-sessionfn id state)
(oauth-sessionfn id #f)))
(oauth-sessionfn id #f))))
;;; Getting consumer/client keys and secrets
;;; The key/secret can either be literally on the provider definition or
;;; it can be a symbol which refers to a CONFIG setting for the key/secret
;;; As a best practice, the secret should be a FramerD secret, which is a
;;; packet whose contents are never displayed.
(define (getckey spec (val))
(default! val (getopt spec 'key))
(if (symbol? val) (getckey spec (config val))
(if (string? val) val
(if (packet? val) val
(irritant spec OAUTH:NOCKEY "Can't determine consumer key")))))
(define (getcsecret spec (val))
(default! val (getopt spec 'secret))
(->secret
(if (symbol? val) (getcsecret spec (config val))
(if (string? val) val
(if (packet? val) val
(irritant spec OAUTH:NOCSECRET
"Can't determine consumer secret"))))))
(define (getcallback spec)
(getopt spec 'callback
(req/get 'oauth_callback
(getopt spec 'default_callback
(or default-callback (thisurl))))))
;;; Computing signatures for the OAUTH1x implementations
(define (oauth/sigstring method uri . params)
"Compute the signature (for OAUTH1) of a call"
(debug%watch method uri params)
(let ((keys {}) (scan params) (args '())
(ptable (make-hashtable)))
;; Params are considered an alternating set of key/value pairs
;; with two exceptions:
;; + if a key is a pair whose cdr is a pair, we assume that it is
;; an embedded alternating set of key/value pairs
;; + if a key is a table, we assume that it's keys and values
;; are keys and values to use
(until (null? scan)
(if (null? (car scan))
(begin)
(if (and (pair? (car scan)) (pair? (cdr (car scan))))
(let ((args (car scan)))
(until (null? args)
(unless (overlaps? (car args) keys)
(set+! keys (car args))
(if (or (string? (cadr args)) (packet? (cadr args)))
(store! ptable (car args) (uriencode (cadr args)))
(store! ptable (car args)
(uriencode (stringout (cadr args))))))
(set! args (cddr args))))
(if (table? (car scan))
(do-choices (key (difference (getkeys (car scan)) keys))
(set+! keys key)
(if (or (string? (get (car scan) key))
(packet? (get (car scan) key)))
(store! ptable key (uriencode (get (car scan) key)))
(store! ptable key
(uriencode (stringout (get (car scan) key))))))
(begin (set+! keys (car scan))
(if (or (string? (cadr scan)) (packet? (cadr scan)))
(store! ptable (car scan) (uriencode (cadr scan)))
(store! ptable (car scan)
(uriencode (stringout (cadr scan)))))
(set! scan (cdr scan))))))
(set! scan (cdr scan)))
(doseq (key (lexsorted keys) i)
(let ((v (get ptable key)))
(when (exists? v)
(set! args (cons* v "%3D" (uriencode key) "%26" args)))))
(apply glom method "&" (uriencode uri) "&" (cdr (reverse args)))))
(define (oauth/spec spec)
"Expands provider references a spec"
(if (and (pair? spec) (symbol? (cdr spec))
(exists? (get oauth-servers (cdr spec))))
(cons (car spec) (get oauth-servers (cdr spec)))
(if (and (symbol? spec) (test oauth-servers spec))
(get oauth-servers spec)
(if (or (and (pair? spec) (getopt spec 'realm))
(and (table? spec) (getopt spec 'realm)
(getopt spec 'key)))
spec
(if (and (table? spec) (test spec 'realm)
(test oauth-servers (get spec 'realm)))
(cons spec (get oauth-servers (get spec 'realm)))
spec)))))
(define (oauth/request spec (ckey) (csecret))
;; Expand provider references in the spec
(set! spec (debug%watch (oauth/spec spec) spec))
(default! ckey (getckey spec))
(default! csecret (getcsecret spec))
(info%watch "OAUTH/REQUEST" spec ckey csecret)
(unless (and (getopt spec 'request)
(getopt spec 'authorize)
(getopt spec 'verify))
;; This should exit
(logwarn OAUTH/REQUEST/BADSPEC "Invalid OAUTH spec: " spec)
(irritant spec OAUTH:BADSPEC OAUTH/REQUEST
"Missing methods for OAuth 1.0 request"))
;; We allow the nonce, time, etc to come from the spec
;; to allow signature debugging
(let* ((nonce (getopt spec 'nonce (uuid->string (getuuid))))
(endpoint (getopt spec 'request))
(callback (uriencode (getcallback spec)))
(now (getopt spec 'time (time)))
(sigstring
(oauth/sigstring
(getopt spec 'method "POST") endpoint
"oauth_callback" callback
"oauth_consumer_key" ckey
"oauth_nonce" nonce
"oauth_signature_method" "HMAC-SHA1"
"oauth_timestamp" now
"oauth_version" (getopt spec 'version "1.0")))
(sig (hmac-sha1 (glom csecret "&") sigstring))
(sig64 (packet->base64 sig))
(auth-header
(glom "Authorization: OAuth "
"oauth_nonce=\"" nonce "\", "
"oauth_callback=\"" callback "\", "
"oauth_signature_method=\"" "HMAC-SHA1" "\", "
"oauth_timestamp=\"" now "\", "
"oauth_consumer_key=\"" ckey "\", "
"oauth_signature=\"" (uriencode sig64) "\", "
"oauth_version=\"" (getopt spec 'version "1.0") "\""))
(handle (curlopen 'header auth-header 'method 'POST
'useragent (getopt spec 'useragent #f)))
(req (urlget endpoint handle)))
(debug%watch "OAUTH/REQUEST"
sigstring sig sig64 auth-header
(get req 'response)
(get req '%content))
(if (test req 'response 200)
(cons (cgiparse (get req '%content)) spec)
(begin (warn%watch "Can't get request token" spec req)
(irritant req
OAUTH/REQFAILED OAUTH/REQUEST
"Can't get request token for " (getopt spec 'realm)
"given \n\t" spec)))))
(define (oauth/authurl spec (scope #f))
"Returns a URL for redirection and authorization and authentication. \
If a scope is provided, we assume that we're authorizing, not \
authenticating."
(set! spec (oauth/spec spec))
(info%watch "OAUTH/AUTHURL" spec (getcallback spec))
(unless (and (getopt spec 'authenticate (getopt spec 'authorize))
(or (getopt spec 'oauth_token) (getckey spec)))
(irritant spec OAUTH:BADSPEC OAUTH/AUTHURL "Incomplete OAUTH spec"))
(if (testopt spec 'version "1.0")
(scripturl+ (if scope
(getopt spec 'authorize (getopt spec 'authenticate))
(getopt spec 'authenticate (getopt spec 'authorize)))
(getopt spec 'auth_args)
"oauth_token" (getopt spec 'oauth_token)
"redirect_uri" (getcallback spec))
(scripturl+
(if scope
(getopt spec 'authorize (getopt spec 'authenticate))
(getopt spec 'authenticate (getopt spec 'authorize)))
(get-auth-args spec)
"client_id" (getckey spec)
"redirect_uri" (getcallback spec)
"scope"
(tryif (choice (tryif scope scope) (getopt spec 'scope))
(stringout (do-choices (scope (or scope (getopt spec 'scope)) i)
(printout (if (> i 0) " ") scope))))
"state" (getopt spec 'state (uuid->string (getuuid)))
"response_type" "code")))
(define (get-auth-args spec)
(let ((args (getopt spec 'auth_args))
(req_args (req/get 'oauth_args #f)))
(cond ((and args req_args)
(set! args (deep-copy args))
(do-choices (key (getkeys req_args))
(store! args key (get req_args key)))
args)
((not args) req_args)
(else args))))
(define (oauth/verify spec verifier (ckey) (csecret))
(set! spec (oauth/spec spec))
(unless (and (getopt spec 'request)
(getopt spec 'authorize)
(getopt spec 'verify))
(irritant spec OAUTH:BADSPEC OAUTH/VERIFY "Invalid OAUTH1.0 spec"))
(info%watch "OAUTH/VERIFY/1.0" verifier spec)
(default! ckey (getckey spec))
(default! csecret (getcsecret spec))
(unless (getopt spec 'oauth_token)
(logwarn OAUTH/VERIFY:NOTOKEN "No OAUTH token in " spec)
(irritant spec OAUTH:NOTOKEN OAUTH/VERIFY "No OAUTH token"))
(unless verifier
(logwarn OAUTH/VERIFY:NOVERIFIER "No OAUTH verifier for " spec)
(irritant spec OAUTH:NOVERIFIER OAUTH/VERIFY "No OAUTH verifier"))
(let* ((nonce (uuid->string (getuuid)))
(endpoint (getopt spec 'verify default-verify-endpoint))
(callback (uriencode (getcallback spec)))
(ckey (getckey spec))
(now (time))
(sigstring
(oauth/sigstring
(getopt spec 'method "POST") endpoint
"oauth_callback" callback
"oauth_consumer_key" ckey
"oauth_token" (getopt spec 'oauth_token)
"oauth_verifier" verifier
"oauth_nonce" nonce
"oauth_signature_method" "HMAC-SHA1"
"oauth_timestamp" now
"oauth_version" (getopt spec 'version "1.0")))
(sig (hmac-sha1 (glom csecret "&" (getopt spec 'oauth_secret))
sigstring))
(sig64 (packet->base64 sig))
(auth-header
(glom "Authorization: OAuth "
"oauth_nonce=\"" nonce "\", "
"oauth_token=\"" (getopt spec 'oauth_token) "\", "
"oauth_verifier=\"" verifier "\", "
"oauth_signature_method=\"" "HMAC-SHA1" "\", "
"oauth_timestamp=\"" now "\", "
"oauth_consumer_key=\"" ckey "\", "
"oauth_signature=\"" (uriencode sig64) "\", "
"oauth_version=\"" (getopt spec 'version "1.0") "\""))
(req (urlget endpoint (curlopen 'header auth-header 'method 'POST
'useragent (getopt spec 'useragent #f)))))
(debug%watch "OAUTH/VERIFY" sigstring sig sig64 auth-header)
(if (test req 'response 200)
(let ((info (cgiparse (get req '%content))))
(store! info 'token (get info 'OAUTH_TOKEN))
(store! info '{oauth_secret OAUTH_TOKEN_SECRET}
(->secret (get info 'OAUTH_TOKEN_SECRET)))
(cons info (cdr spec)))
(if (getopt spec 'noverify)
((getopt spec 'noverify) spec verifier req)
(begin
(logwarn OAUTH/VERIFY:REQFAIL spec req)
(irritant req OAUTH:REQFAIL OAUTH:VERIFY "Web call failed"))))))
(define (oauth/getaccess spec (code) (ckey) (csecret) (verifier))
(set! spec (oauth/spec spec))
(default! code
(and (or (testopt spec 'grant "authorization_code")
(not (testopt spec 'grant)))
(getopt spec 'code (req/get 'code))))
(default! ckey (getckey spec))
(default! csecret (getcsecret spec))
(default! verifier (getopt spec 'verifier))
(info%watch "OAUTH/GETACCESS" code spec)
(let* ((callback (getcallback spec))
(req (urlpost (getopt spec 'access)
`#[content-type "application/x-www-form-urlencoded"
header ,(and (getopt spec 'expect default-expect)
(cons "Expect"
(getopt spec 'expect default-expect)))]
(args->post
(list "code" (qc (tryif code code))
"fb_exchange_token"
(qc (tryif (and (testopt spec 'grant "fb_exchange_token")
(getopt spec 'token))
(getopt spec 'token)))
"client_id" ckey "client_secret" csecret
"grant_type"
(getopt spec 'grant "authorization_code")
"redirect_uri" (qc callback))))))
(when (getopt spec 'lograw lograw)
(let ((reqid (getuuid)))
(store! lograw reqid req)
(store! req 'reqid reqid)))
(if (test req 'response 200)
(let* ((parsed (getreqdata req))
(expires_in (->number
(try (get parsed 'expires_in)
(get parsed 'expires))))
(authinfo `#[token ,(get parsed 'access_token)]))
(debug%watch "OAUTH/GETACCESS" parsed spec req expires_in)
(when (exists? (get parsed 'token_type))
(unless (string-ci=? (get parsed 'token_type) "Bearer")
(logwarn |OAUTH/GETACESS/OddToken|
"Odd token type " (get parsed 'token_type) " "
"responding to " spec " "
"response=" parsed)))
(when (and (exists? expires_in) expires_in)
(store! authinfo 'expires (timestamp+ expires_in))
(when (exists? (get parsed 'refresh_token))
(store! authinfo 'refresh
(->secret (get parsed 'refresh_token)))))
(debug%watch "OAUTH/GETACCESS/RESULT" (cons authinfo spec))
(cons authinfo spec))
(begin
(logwarn |OATH/GETACCESS:Failure|
"OAUTH/GETACCESS failed " spec " ==> " req)
(if (getopt spec 'noverify)
((getopt spec 'noverify) spec verifier req)
(irritant req OAUTH:REQFAIL OAUTH/GETACCESS
"Web call failed"))))))
(define (oauth/getclient spec (ckey) (csecret))
(set! spec (oauth/spec spec))
(default! ckey (getckey spec))
(default! csecret (getcsecret spec))
(info%watch "OAUTH/GETACCESS" spec)
(let* ((callback (getcallback spec))
(req (urlpost (getopt spec 'access)
`#[content-type "application/x-www-form-urlencoded"
basicauth ,(glom ckey ":" csecret)
useragent ,(getopt spec 'useragent #f)
header ,(and (getopt spec 'expect default-expect)
(cons "Expect"
(getopt spec 'expect default-expect)))]
(args->post
(list "grant_type"
(getopt spec 'grant "client_credentials"))))))
(when (getopt spec 'lograw lograw) (store! req 'reqid (getuuid)))
(if (test req 'response 200)
(let* ((parsed (getreqdata req))
(expires_in (->number
(try (get parsed 'expires_in)
(get parsed 'expires))))
(authinfo `#[token ,(get parsed 'access_token)]))
(info%watch "OAUTH/GETCLIENT" parsed spec req expires_in)
(when (exists? (get parsed 'token_type))
(unless (string-ci=? (get parsed 'token_type) "Bearer")
(logwarn |OAUTH/GETACESS/OddToken|
"Odd token type " (get parsed 'token_type) " responding to " spec
" response=" parsed)))
(when (and (exists? expires_in) expires_in)
(store! authinfo 'expires (timestamp+ expires_in))
(when (exists? (get parsed 'refresh_token))
(store! authinfo 'refresh
(->secret (get parsed 'refresh_token)))))
(info%watch "OAUTH/GETACCESS/RESULT" (cons authinfo spec) )
(cons authinfo spec))
(begin
(logwarn |OATH/GETACCESS:Failure|
"OAUTH/GETACCESS failed " spec " ==> " req)
(irritant req OAUTH:REQFAIL OAUTH/GETACCESS
"Web call failed")))))
;;; Actually calling the API
(define (oauth/call10 spec method endpoint args body ctype raw ckey csecret)
(default! ctype
(and body
(if (pair? body) (cdr body)
(getopt spec 'ctype
(if (packet? body) "application" "text")))))
(info%watch "OAUTH/CALL1.0" method endpoint args ctype)
(unless (getopt spec 'token)
(irritant spec OAUTH:NOTOKEN OAUTH/CALL
"No OAUTH token for OAuth1.0 call"))
(unless (getopt spec 'oauth_secret)
(irritant spec OAUTH:NOSECRET OAUTH/CALL
"No OAUTH secret for OAuth1.0 call"))
(let* ((nonce (getopt spec 'nonce (uuid->string (getuuid))))
(endpoint (get-endpoint endpoint args spec))
(now (getopt spec 'timestamp (time)))
(sigstring
(oauth/sigstring
method endpoint
"oauth_consumer_key" ckey
"oauth_token" (->string (getopt spec 'token))
"oauth_nonce" nonce
"oauth_signature_method" "HMAC-SHA1"
"oauth_timestamp" now
"oauth_version" (getopt spec 'version "1.0")
(if (pair? args)
(map uriencode args)
(if (table? args)
(let ((newtable (frame-create #f)))
(do-choices (key (getkeys args))
(store! newtable
(if (string? key) (uriencode key) key)
(if (or (string? (get args key)) (packet? (get args key)))
(uriencode (get args key))
(get args key))))
newtable)
args))))
(sig (hmac-sha1 (glom csecret "&" (getopt spec 'oauth_secret))
sigstring))
(sig64 (packet->base64 sig))
(auth-header
(glom "Authorization: OAuth "
;; "realm=\"" (urischeme endpoint) "://" (urihost endpoint) "\", "
"oauth_consumer_key=\"" ckey "\", "
"oauth_nonce=\"" nonce "\", "
"oauth_signature=\"" (uriencode sig64) "\", "
"oauth_signature_method=\"" "HMAC-SHA1" "\", "
"oauth_timestamp=\"" now "\", "
"oauth_token=\"" (getopt spec 'token) "\", "
"oauth_version=\"" (getopt spec 'version "1.0") "\""))
(content (if (pair? body) (car body) body))
(handle (curlopen 'header
(and (getopt spec 'expect default-expect)
(cons "Expect"
(getopt spec 'expect default-expect)))
'useragent (getopt spec 'useragent #f)
'header auth-header
'method method))
(streamfn (getopt spec 'streamfn))
(useurl
(if (eq? method 'POST) endpoint
(if (pair? args)
(apply scripturl endpoint args)
(scripturl+ endpoint args))))
(req (cond (streamfn (urlstream useurl streamfn body handle))
((eq? method 'GET) (urlget useurl handle))
((eq? method 'HEAD) (urlhead useurl handle))
((eq? method 'POST) (urlpost useurl handle (args->post args)))
((eq? method 'PUT) (urlput useurl content ctype handle))
(else (error OAUTH:BADMETHOD OAUTH/CALL10
"Only GET, HEAD, PUT, and POST are allowed: "
method endpoint args)))))
(debug%watch now nonce sig64)
;; Keeping these watchpoints separate makes them easier to read
;; (maybe %watch needs a redesign?)
(debug%watch sigstring)
(debug%watch auth-header)
(when (getopt spec 'lograw lograw)
(let ((reqid (getuuid)))
(store! lograw reqid req)
(store! req 'reqid reqid)))
(when (getopt spec 'jsonflags)
(store! req 'jsonflags (getopt spec 'jsonflags)))
(if raw req
(if (and (test req 'response) (number? (get req 'response))
(<= 200 (get req 'response) 299))
(cons (getreqdata req) spec)
(irritant req OAUTH:REQFAIL OAUTH/CALL1.0
"Failed to " method " at " endpoint
" with " args "\n\t" spec)))))
(define (oauth/call20 spec method endpoint args
(body #f) (ctype) (raw) (ckey) (csecret) (expires))
(info%watch "OAUTH/CALL2.0" method endpoint args ckey csecret)
(unless (getopt spec 'token)
(irritant spec OAUTH:NOTOKEN OAUTH/CALL
"No OAUTH token for OAuth2 call"))
(default! expires (getopt spec 'expires))
(default! ctype
(and body
(if (pair? body) (cdr body)
(getopt spec 'ctype
(if (packet? body) "application" "text")))))
(when (and expires (past? expires)) (oauth/refresh! spec))
(let* ((endpoint (get-endpoint endpoint args spec))
(httpauth (testopt spec 'access_token 'http))
(auth-header
(if httpauth
(glom "Authorization: Bearer " (getopt spec 'token))
""))
(streamfn (getopt spec 'streamfn))
(content (if (pair? body) (car body) body))
(useurl
(if (or (eq? method 'get) (eq? method 'put)
(and (eq? method 'post) body))
(if httpauth
(if (or (not args) (null? args)) endpoint
(if (pair? args)
(apply scripturl endpoint args)
(apply scripturl+ endpoint (list args))))
(if (pair? args)
(apply scripturl endpoint
(getopt spec 'access_token "access_token")
(getopt spec 'token)
args)
(if (or (not args) (null? args))
(scripturl endpoint
(getopt spec 'access_token "access_token")
(getopt spec 'token))
(apply scripturl+ endpoint (list args)))))
endpoint))
(handle
(if httpauth
(curlopen 'header
(and (getopt spec 'expect default-expect)
(cons "Expect"
(getopt spec 'expect default-expect)))
'header auth-header
'useragent (getopt spec 'useragent #f)
'method method)
(curlopen 'header
(and (getopt spec 'expect default-expect)
(cons "Expect"
(getopt spec 'expect default-expect)))
'useragent (getopt spec 'useragent #f)
'method method)))
(response
(if streamfn
(urlstream useurl streamfn body handle)
(if (eq? method 'GET) (urlget useurl handle)
(if (eq? method 'HEAD) (urlget useurl handle)
(if (eq? method 'POST)
(if body
(urlput useurl content ctype handle)
(urlpost useurl handle (args->post args)))
(if (eq? method 'PUT)
(urlput useurl content ctype handle)
(error OAUTH:BADMETHOD OAUTH/CALL20
"Only GET, HEAD, PUT, and POST are allowed: "
method endpoint args))))))))
(debug%watch "OAUTH/CALL20" endpoint auth-header)
(logdebug |OAuth20/Response| (pprint response))
(when (getopt spec 'lograw lograw)
(let ((reqid (getuuid)))
(store! lograw reqid response)
(store! response 'reqid reqid)))
(when (getopt spec 'jsonflags)
(store! response 'jsonflags (getopt spec 'jsonflags)))
(if raw
response
(if (and (test response 'response)
(number? (get response 'response))
(<= 200 (get response 'response) 299))
(cons (getreqdata response)
(if (getopt spec 'keepraw keep-raw)
(cons response spec)
spec))
(if (and (<= 400 (get response 'response) 499)
(getopt spec 'refresh))
(begin
(debug%watch 'OAUTH/ERROR "RESPONSE" response spec)
(oauth/refresh! spec)
(oauth/call20 spec method endpoint args
body ctype raw ckey csecret))
(irritant response OAUTH:REQFAIL OAUTH/CALL20
method " at " endpoint " with " args
"\n\t" spec))))))
(define (args->post args (first #t) (elt #f))
(if (not (pair? args)) (set! args (list args)))
(stringout
(while (pair? args)
(set! elt (car args))
(cond ((table? elt)
(do-choices (key (getkeys elt) i)
(printout
(if first (set! first #f) "&")
(uriencode key) "="
(uriencode (get elt key))))
(set! args (cdr args)))
((and (pair? (cdr args)) (fail? (cadr args)))
(set! args (cddr args)))
((pair? (cdr args))
(printout
(if first (set! first #f) "&")
(uriencode (car args))
"="
(uriencode (cadr args)))
(set! args (cddr args)))
(else
(printout (uriencode elt))
(set! args (cdr args)))))))
(define (oauth/refresh! spec)
(unless (getopt spec 'refresh)
(irritant spec OAUTH:NOREFRESH OAUTH/REFRESH!
"No OAUTH2 refresh key"))
(unless (pair? spec) (set! spec (oauth/spec spec)))
(let* ((endpoint (getopt spec 'access (getopt spec 'authorize)))
(auth-header
(glom "Authorization: Bearer " (getopt spec 'token)))
(req (urlpost endpoint
(curlopen 'header
(and (getopt spec 'expect default-expect)
(cons "Expect"
(getopt spec 'expect default-expect)))
'header auth-header
'useragent (getopt spec 'useragent #f)
'method 'POST)
(scripturl+
#f `#["client_id" ,(getckey spec)
"client_secret" ,(getcsecret spec)
"grant_type" "refresh_token"
"refresh_token" ,(getopt spec 'refresh)]))))
(info%watch "OAUTH/REFRESH!" endpoint auth-header req)
(when (getopt spec 'lograw lograw) (store! req 'reqid (getuuid)))
(if (test req 'response 200)
(let* ((parsed (getreqdata req))
(expires_in (->number (try (get parsed 'expires_in)
(get parsed 'expires))))
(newtoken (get parsed 'access_token))
(head (car spec)))
(when (exists? newtoken) (store! head 'token newtoken))
(unless (equal? (get parsed 'token_type) "Bearer")
(logwarn |OAUTH/REFRESH!/OddToken|
"Odd token type " (get parsed 'token_type)
" responding to " spec " from " parsed))
(when expires_in
(store! head 'expires (timestamp+ expires_in))
(store! head 'refresh (get parsed 'refresh)))
(unless expires_in
(drop! head 'expires) (drop! head 'refresh))
(when getuser (getuser spec))
spec)
(irritant req OAUTH:NOREFRESH OAUTH/REFRESH!
"Can't refresh token" spec))))
;;; Generic call function
(define (oauth/call spec method endpoint (args '())
(body #f) (ctype) (raw) (ckey) (csecret))
(set! spec (oauth/spec spec))
(default! ctype
(and body
(if (pair? body) (cdr body)
(getopt spec 'ctype
(if (packet? body) "application" "text")))))
(default! ckey (getckey spec))
(default! csecret (getcsecret spec))
(default! raw (getopt spec 'noparse))
(unless (has-prefix endpoint {"http:" "https:"})
(set! endpoint (mkpath (getopt spec 'endpoint) (strip-prefix endpoint "/"))))
(if (testopt spec 'version "1.0")
(oauth/call10 spec method endpoint args body ctype raw ckey csecret)
(oauth/call20 spec method endpoint args body ctype raw ckey csecret)))
(define (oauth/call* spec method endpoint . args)
(oauth/call spec method endpoint args))
(define (oauth/call/req spec method endpoint
(args '()) (body #f) (ctype) (ckey) (csecret))
(set! spec (oauth/spec spec))
(default! ckey (getckey spec))
(default! csecret (getcsecret spec))
(default! ctype
(and body
(if (pair? body) (cdr body)
(getopt spec 'ctype
(if (packet? body) "application" "text")))))
(if (testopt spec 'version "1.0")
(oauth/call10 spec method endpoint args body ctype #t ckey csecret)
(oauth/call20 spec method endpoint args body ctype #t ckey csecret)))
;;; This is helpful for debugging OAUTH1
(define (oauth/callsig spec method endpoint . args)
(when (and (not (getopt spec 'secret))
(getopt spec 'realm)
(exists? (oauth/provider (getopt spec 'realm))))
(set! spec (cons spec (oauth/provider (getopt spec 'realm)))))
(let ((ckey (getckey spec))
(csecret (getcsecret spec)))
(unless (getopt spec 'oauth_token)
(irritant spec |OAUTH/Missing| OAUTH/CALLSIG "No OAUTH token"))
(unless (getopt spec 'oauth_secret)
(irritant spec |OAUTH/Missing| OAUTH/CALLSIG "No OAUTH secret"))
(let* ((nonce (getopt spec 'nonce (uuid->string (getuuid))))
(endpoint (or endpoint
(getopt args 'endpoint
(getopt spec 'endpoint
default-endpoint))))
(now (getopt spec 'timestamp (time)))
(sigstring
(oauth/sigstring
method endpoint
"oauth_consumer_key" ckey
"oauth_token" (->string (getopt spec 'oauth_token))