Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions R/get_auth_token.R
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@
#'
#' # Get a token for a specific resource and tenant
#' token <- get_auth_token(
#' resource = "https://graph.microsoft.com",
#' tenant = "my-tenant-id"
#' resource = "https://graph.microsoft.com",
#' tenant = "my-tenant-id"
#' )
#'
#' # Get a token using a specific app ID
Expand Down Expand Up @@ -93,7 +93,7 @@ get_auth_token <- function(
token_error <- token_resp[["error"]]

# 2. Try to get a managed token (for example on Azure VM, App Service)
if (is.null(token)) {
if (is.null(token) && imds_available()) {
token <- rlang::inject(possibly_get_mtk(resource, !!!dots))
}

Expand Down Expand Up @@ -273,3 +273,45 @@ generate_resource <- function(
#' @returns An Azure authentication token
#' @export
refresh_token <- \(token) token$refresh()

#' Check if Azure Instance Metadata Service (IMDS) is Available
#'
#' This function checks if the Azure Instance Metadata Service (IMDS) is
#' available by attempting to make a request to the IMDS endpoint. The result is
#' cached in an environment variable for future use, saving the need for
#' repeated checks.
#'
#' You can also set the `IMDS_AVAILABLE` environment variable manually to
#' "TRUE" or "FALSE" to override the automatic check, which can be useful for
#' testing or in environments where the check may not work correctly.
imds_available <- function() {
available <- Sys.getenv("IMDS_AVAILABLE")

if (available == "") {
available <- tryCatch(
{
Sys.getenv(
"MSI_ENDPOINT",
"http://169.254.169.254/metadata/identity/oauth2"
) |>
httr2::request() |>
httr2::req_headers(Metadata = "true") |>
httr2::req_timeout(0.2) |>
httr2::req_perform()

TRUE
},
error = function(e) FALSE
)
Sys.setenv(IMDS_AVAILABLE = available)
}

switch(toupper(available), "TRUE" = TRUE, "FALSE" = FALSE, {
warning(
"Invalid value for IMDS_AVAILABLE environment variable: ",
available,
". Expected 'true' or 'false'. Defaulting to FALSE."
)
FALSE
})
}
4 changes: 2 additions & 2 deletions man/get_auth_token.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions man/imds_available.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading