forked from r-lib/httr2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoauth.R
More file actions
278 lines (259 loc) · 7.73 KB
/
Copy pathoauth.R
File metadata and controls
278 lines (259 loc) · 7.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#' OAuth authentication
#'
#' This is a low-level helper for automatically authenticating a request with
#' an OAuth flow, caching the access token and refreshing it where possible.
#' You should only need to use this function if you're implementing your own
#' OAuth flow.
#'
#' @inheritParams req_perform
#' @param cache An object that controls how the token is cached. This should
#' be a list containing three functions:
#' * `get()` retrieves the token from the cache, returning `NULL` if not
#' cached yet.
#' * `set()` saves the token to the cache.
#' * `clear()` removes the token from the cache
#' @param flow An `oauth_flow_` function used to generate the access token.
#' @param flow_params Parameters for the flow. This should be a named list
#' whose names match the argument names of `flow`.
#' @param expiry_margin Number of seconds before a token's stated expiry that
#' it should be treated as expired. Increase this for servers that reject
#' tokens shortly before they expire. Defaults to 30 seconds.
#' @returns An [oauth_token].
#' @keywords internal
#' @export
req_oauth <- function(req, flow, flow_params, cache, expiry_margin = 30) {
check_number_whole(expiry_margin, min = 0)
# Want req object to contain meaningful objects, not just a closure
req <- req_auth_sign(
req,
fun = auth_oauth_sign,
params = list(
flow = flow,
flow_params = flow_params,
expiry_margin = expiry_margin
),
cache = cache
)
req <- req_policies(req, auth_oauth = TRUE)
req
}
auth_oauth_sign <- function(
req,
cache,
flow,
flow_params,
expiry_margin = 30
) {
token <- auth_oauth_token_get(
cache = cache,
flow = flow,
flow_params = flow_params,
expiry_margin = expiry_margin
)
req_auth_bearer_token(req, token$access_token)
}
auth_oauth_token_get <- function(
cache,
flow,
flow_params = list(),
expiry_margin = 30
) {
token <- cache$get()
if (is.null(token)) {
token <- exec(flow, !!!flow_params)
cache$set(token)
} else if (token_has_expired(token, delay = expiry_margin)) {
cache$clear()
if (is.null(token$refresh_token)) {
token <- exec(flow, !!!flow_params)
} else {
token <- tryCatch(
token_refresh(
flow_params$client,
token$refresh_token,
token_params = flow_params$token_params %||% list()
),
httr2_oauth = function(cnd) {
# If refresh fails, try to auth from scratch
exec(flow, !!!flow_params)
}
)
}
cache$set(token)
}
token
}
#' Retrieve an OAuth token using the cache
#'
#' This function wraps around a `oauth_flow_` function to retrieve a token
#' from the cache, or to generate and cache a token if needed. Use this for
#' manual token management that still takes advantage of httr2's caching
#' system. You should only need to use this function if you're passing
#' the token
#'
#' @keywords internal
#' @inheritParams req_oauth
#' @inheritParams req_oauth_auth_code
#' @param reauth Set to `TRUE` to force re-authentication via flow, regardless
#' of whether or not token is expired.
#' @export
#' @examples
#' \dontrun{
#' token <- oauth_token_cached(
#' client = example_github_client(),
#' flow = oauth_flow_auth_code,
#' flow_params = list(
#' auth_url = "https://github.com/login/oauth/authorize"
#' ),
#' cache_disk = TRUE
#' )
#' token
#' }
oauth_token_cached <- function(
client,
flow,
flow_params = list(),
cache_disk = FALSE,
cache_key = NULL,
reauth = FALSE
) {
check_bool(reauth)
cache <- cache_choose(client, cache_disk, cache_key)
if (reauth) {
cache$clear()
}
flow_params$client <- client
auth_oauth_token_get(
cache = cache,
flow = flow,
flow_params = flow_params
)
}
resp_is_invalid_oauth_token <- function(req, resp) {
if (!req_policy_exists(req, "auth_oauth")) {
return(FALSE)
}
if (is_error(resp) || resp_status(resp) != 401) {
return(FALSE)
}
auth <- resp_header(resp, "WWW-Authenticate")
if (is.null(auth)) {
return(FALSE)
}
# https://datatracker.ietf.org/doc/html/rfc6750#section-3.1
# invalid_token:
# The access token provided is expired, revoked, malformed, or
# invalid for other reasons. The resource SHOULD respond with
# the HTTP 401 (Unauthorized) status code. The client MAY
# request a new access token and retry the protected resource
# request.
grepl('error="invalid_token"', auth, fixed = TRUE)
}
# Caches -------------------------------------------------------------------
cache_choose <- function(client, cache_disk = FALSE, cache_key = NULL) {
if (cache_disk) {
cache_disk(client, cache_key)
} else {
cache_mem(client, cache_key)
}
}
# Used for auth endoints that don't have a cache
cache_noop <- function() {
list(
get = function() {
abort("get() was called on cache_noop")
invisible()
},
set = function(token) {
abort("set() was called on cache_noop")
invisible()
},
clear = function() {}
)
}
cache_mem <- function(client, key = NULL) {
key <- hash(c(client$name, key))
list(
get = function() env_get(the$token_cache, key, default = NULL),
set = function(token) env_poke(the$token_cache, key, token),
clear = function() env_unbind(the$token_cache, key)
)
}
cache_disk <- function(client, key = NULL) {
app_path <- file.path(oauth_cache_path(), client$name)
dir.create(app_path, showWarnings = FALSE, recursive = TRUE)
path <- file.path(app_path, paste0(hash(key), "-token.rds.enc"))
list(
get = function() {
if (file.exists(path)) secret_read_rds(path, obfuscate_key()) else NULL
},
set = function(token) {
cli::cli_inform("Caching httr2 token in {.path {path}}.")
secret_write_rds(token, path, obfuscate_key())
},
clear = function() if (file.exists(path)) file.remove(path)
)
}
# Update req_oauth_auth_code() docs if change default from 30
cache_disk_prune <- function(
days = 30,
paths = c(oauth_cache_path(), oauth_cache_path_legacy())
) {
files <- dir(
paths,
recursive = TRUE,
full.names = TRUE,
pattern = "-token\\.rds\\.enc$"
)
mtime <- file.mtime(files)
old <- mtime < (Sys.time() - days * 86400)
unlink(files[old])
}
#' httr2 OAuth cache location
#'
#' When opted-in to, httr2 caches OAuth tokens in this directory. By default,
#' it uses a OS-standard cache directory, but, if needed, you can override the
#' location by setting the `HTTR2_OAUTH_CACHE` env var.
#'
#' @export
oauth_cache_path <- function() {
path <- Sys.getenv("HTTR2_OAUTH_CACHE")
if (nzchar(path)) {
path
} else {
tools::R_user_dir("httr2", which = "cache")
}
}
# Equivalent to rappdirs::user_cache_dir("httr2"), inlined so httr2 doesn't
# depend on rappdirs solely to find tokens cached by older versions. The
# appname is nested twice and gains a "Cache" subdir on Windows because that's
# what rappdirs did with its default `appauthor` and `opinion` arguments.
oauth_cache_path_legacy <- function() {
base <- Sys.getenv("R_USER_CACHE_DIR")
if (nzchar(base)) {
if (.Platform$OS.type == "windows") {
return(file.path(base, "httr2", "httr2", "Cache"))
} else {
return(file.path(base, "httr2"))
}
}
if (.Platform$OS.type == "windows") {
base <- Sys.getenv("LOCALAPPDATA", Sys.getenv("APPDATA"))
file.path(base, "httr2", "httr2", "Cache")
} else if (Sys.info()[["sysname"]] == "Darwin") {
"~/Library/Caches/httr2"
} else {
file.path(Sys.getenv("XDG_CACHE_HOME", "~/.cache"), "httr2")
}
}
#' Clear OAuth cache
#'
#' Use this function to clear cached credentials.
#'
#' @export
#' @inheritParams req_oauth_auth_code
oauth_cache_clear <- function(client, cache_disk = FALSE, cache_key = NULL) {
cache <- cache_choose(client, cache_disk, cache_key)
cache$clear()
invisible()
}