commit 4a36b22c2a10e3d7d3d1bf7ee9b4466868037a7f Author: Hong Ooi Date: Thu Mar 14 20:28:37 2019 +1100 init from AzureRMR diff --git a/.Rbuildignore b/.Rbuildignore new file mode 100644 index 0000000..362a7b2 --- /dev/null +++ b/.Rbuildignore @@ -0,0 +1,10 @@ +^misc$ +^\.vs$ +\.sln$ +\.Rproj$ +\.Rxproj$ +^\.Rproj\.user$ +.travis.yml +CONTRIBUTING.md +drat.sh +^LICENSE\.md$ diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1bd84a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,265 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +#*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +.RHistory +misc/ +.Rproj.user diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..5bbbb4d --- /dev/null +++ b/.travis.yml @@ -0,0 +1,10 @@ +language: r +sudo: false +cache: packages +#r_packages: +#- covr +#- drat +#after_success: +#- Rscript -e 'library("covr");codecov()' +#- test $TRAVIS_PULL_REQUEST == "false" && test $TRAVIS_BRANCH == "master" && bash +# drat.sh diff --git a/DESCRIPTION b/DESCRIPTION new file mode 100644 index 0000000..27a2ece --- /dev/null +++ b/DESCRIPTION @@ -0,0 +1,27 @@ +Package: AzureGraph +Title: Interface to 'Azure Active Directory Graph' +Version: 0.0.1 +Authors@R: c( + person("Hong", "Ooi", , "hongooi@microsoft.com", role = c("aut", "cre")), + person("Microsoft", role="cph") + ) +Description: A lightweight R interface to the 'Azure Active Directory Graph' REST API. +URL: https://github.com/cloudyr/AzureGraph +BugReports: https://github.com/cloudyr/AzureGraph/issues +License: MIT + file LICENSE +VignetteBuilder: knitr +Depends: + R (>= 3.3) +Imports: + AzureAuth, + utils, + httr (>= 1.3), + jsonlite, + R6, + xml2 +Suggests: + knitr, + testthat, + httpuv +Roxygen: list(markdown=TRUE) +RoxygenNote: 6.1.1 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..bbfe484 --- /dev/null +++ b/LICENSE @@ -0,0 +1,2 @@ +YEAR: 2018 +COPYRIGHT HOLDER: Microsoft diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..b5c208b --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright (c) 2018 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NAMESPACE b/NAMESPACE new file mode 100644 index 0000000..2c7f9ce --- /dev/null +++ b/NAMESPACE @@ -0,0 +1,7 @@ +# Generated by roxygen2: do not edit by hand + +export(az_app) +export(az_graph) +export(az_service_principal) +export(call_azure_graph) +export(call_azure_url) diff --git a/R/az_app.r b/R/az_app.r new file mode 100644 index 0000000..22830b3 --- /dev/null +++ b/R/az_app.r @@ -0,0 +1,115 @@ +#' @export +az_app <- R6::R6Class("az_app", + +public=list( + + token=NULL, + tenant=NULL, + + # app data from server + properties=NULL, + + initialize=function(token, tenant=NULL, app_id=NULL, object_id=NULL, password=NULL, password_duration=1, ..., + deployed_properties=list()) + { + self$token <- token + self$tenant <- tenant + + self$properties <- if(!is_empty(list(...))) + private$init_and_deploy(..., password=password, password_duration=password_duration) + else if(!is_empty(deployed_properties)) + private$init_from_parms(deployed_properties) + else private$init_from_host(app_id, object_id) + }, + + delete=function(confirm=TRUE) + { + if(confirm && interactive()) + { + msg <- paste0("Do you really want to delete the '", self$properties$displayName, "' app? (y/N) ") + yn <- readline(msg) + if(tolower(substr(yn, 1, 1)) != "y") + return(invisible(NULL)) + } + + op <- file.path("applications", self$properties$objectId) + call_azure_graph(self$token, self$tenant, op, http_verb="DELETE") + invisible(NULL) + }, + + update=function(...) + {}, + + sync_fields=function() + { + self$properties <- private$init_from_host(app_id=NULL, object_id=self$properties$objectId) + invisible(self) + }, + + create_service_principal=function(...) + { + az_service_principal$new(self$token, self$tenant, app_id=self$properties$appId, ..., mode="create") + }, + + get_service_principal=function() + { + az_service_principal$new(self$token, self$tenant, app_id=self$properties$appId, mode="get") + }, + + delete_service_principal=function(confirm=TRUE) + { + az_service_principal$new(self$token, self$tenant, app_id=self$properties$appId, + deployed_properties=list(NULL), mode="get")$ + delete(confirm=confirm) + } +), + +private=list( + + password=NULL, + + init_and_deploy=function(..., password, password_duration) + { + properties <- list(...) + if(is.null(password) || password != FALSE) + { + key <- "awBlAHkAMQA=" # base64/UTF-16LE encoded "key1" + if(is.null(password)) + { + chars <- c(letters, LETTERS, 0:9, "~", "!", "@", "#", "$", "%", "&", "*", "(", ")", "-", "+") + password <- paste0(sample(chars, 50, replace=TRUE), collapse="") + } + + end_date <- if(is.finite(password_duration)) + { + now <- as.POSIXlt(Sys.time()) + now$year <- now$year + password_duration + format(as.POSIXct(now), "%Y-%m-%dT%H:%M:%SZ", tz="GMT") + } + else "2299-12-30T12:00:00Z" + + private$password <- password + properties <- modifyList(properties, list(passwordCredentials=list(list( + customKeyIdentifier=key, + endDate=end_date, + value=password + )))) + } + + call_azure_graph(self$token, self$tenant, "applications", body=properties, encode="json", http_verb="POST") + }, + + init_from_parms=function(parms) + { + parms + }, + + init_from_host=function(app_id, object_id) + { + op <- if(is.null(object_id)) + file.path("applicationsByAppId", app_id) + else file.path("applications", object_id) + + call_azure_graph(self$token, self$tenant, op) + } +)) diff --git a/R/az_graph.R b/R/az_graph.R new file mode 100644 index 0000000..af1aabd --- /dev/null +++ b/R/az_graph.R @@ -0,0 +1,166 @@ +#' Azure Active Directory Graph +#' +#' Base class for interacting with Azure AD Graph API. +#' +#' @docType class +#' @section Methods: +#' - `new(tenant, app, ...)`: Initialize a new ARM connection with the given credentials. See 'Authentication` for more details. +#' - `create_app(name, ..., password=NULL, create_service_principal=TRUE)`: Creates a new registered app in Azure Active Directory. By default the app will have a randomly generated strong password with a duration of 1 year, and an associated service principal will also be created. +#' - `get_app(app_id, object_id)`: Retrieves an existing registered app, via either its app ID or object ID. +#' - `delete_app(app_id, object_id, confirm=TRUE)`: Deletes an existing registered app. Any associated service principal will also be deleted. +#' - `create_service_principal(app_id, ...)`: Creates a service principal for a registered app. +#' - `get_service_principal()`: Retrieves an existing service principal. +#' - `delete_service_principal()`: Deletes an existing service principal. +#' +#' @section Authentication: +#' The recommended way to authenticate with Azure AD Graph is via the [create_graph_login] function, which creates a new instance of this class. +#' +#' To authenticate with the `az_graph` class directly, provide the following arguments to the `new` method: +#' - `tenant`: Your tenant ID. This can be a name ("myaadtenant"), a fully qualified domain name ("myaadtenant.onmicrosoft.com" or "mycompanyname.com"), or a GUID. +#' - `app`: The client/app ID to use to authenticate with Azure Active Directory. The default is to login interactively using the Azure CLI cross-platform app, but it's recommended to supply your own app credentials if possible. +#' - `password`: if `auth_type == "client_credentials"`, the app secret; if `auth_type == "resource_owner"`, your account password. +#' - `username`: if `auth_type == "resource_owner"`, your username. +#' - `auth_type`: The OAuth authentication method to use, one of "client_credentials", "authorization_code", "device_code" or "resource_owner". See [get_azure_token] for how the default method is chosen, along with some caveats. +#' - `host`: your Azure AD Graph host. Defaults to `https://graph.windows.net/`. Change this if you are using a government or private cloud. +#' - `aad_host`: Azure Active Directory host for authentication. Defaults to `https://login.microsoftonline.com/`. Change this if you are using a government or private cloud. +#' - `config_file`: Optionally, a JSON file containing any of the arguments listed above. Arguments supplied in this file take priority over those supplied on the command line. You can also use the output from the Azure CLI `az ad sp create-for-rbac` command. +#' - `token`: Optionally, an OAuth 2.0 token, of class [AzureToken]. This allows you to reuse the authentication details for an existing session. If supplied, all other arguments will be ignored. +#' +#' @seealso +#' [create_graph_login], [get_graph_login] +#' +#' [Azure AD Graph overview](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-graph-api), +#' [REST API reference](https://docs.microsoft.com/en-au/previous-versions/azure/ad/graph/api/api-catalog) +#' +#' @examples +#' \dontrun{ +#' +#' # start a new Resource Manager session +#' gr <- az_graph$new(tenant="myaadtenant.onmicrosoft.com", app="app_id", password="password") +#' +#' # authenticate with credentials in a file +#' gr <- az_graph$new(config_file="creds.json") +#' +#' # authenticate with device code +#' gr <- az_graph$new(tenant="myaadtenant.onmicrosoft.com", app="app_id", auth_type="device_code") +#' +#' # retrieve a registered app +#' gr$get_app(app_id="myappid") +#' +#' # create a new app and associated service principal, set password duration to 10 years +#' app <- gr$create_app("mynewapp", password_duration=10) +#' +#' svc <- gr$get_service_principal(app_id=app$properties$appId) +#' +#' # delete the app +#' gr$delete_app(app_id=app$properties$appId) +#' # ... but better to call the object's delete method directly +#' app$delete() +#' +#' } +#' @format An R6 object of class `az_graph`. +#' @export +az_graph <- R6::R6Class("az_graph", + +public=list( + host=NULL, + tenant=NULL, + token=NULL, + + # authenticate and get subscriptions + initialize=function(tenant, app=.az_cli_app_id, password=NULL, username=NULL, auth_type=NULL, + host="https://graph.windows.net/", aad_host="https://login.microsoftonline.com/", + config_file=NULL, token=NULL) + { + if(is_azure_token(token)) + { + self$host <- if(token$version == 1) + token$resource + else token$scope + self$tenant <- if(token$tenant == "common") + "myorganization" + else token$tenant + self$token <- token + return(NULL) + } + + if(!is.null(config_file)) + { + conf <- jsonlite::fromJSON(config_file) + if(!is.null(conf$tenant)) tenant <- conf$tenant + if(!is.null(conf$app)) app <- conf$app + if(!is.null(conf$auth_type)) auth_type <- conf$auth_type + if(!is.null(conf$password)) password <- conf$password + if(!is.null(conf$graph_host)) host <- conf$graph_host + if(!is.null(conf$aad_host)) aad_host <- conf$aad_host + } + + self$host <- host + self$tenant <- normalize_graph_tenant(tenant) + tenant <- normalize_tenant(tenant) + app <- normalize_guid(app) + + self$token <- get_azure_token(self$host, + tenant=tenant, + app=app, + password=password, + username=username, + auth_type=auth_type, + aad_host=aad_host) + NULL + }, + + create_app=function(name, ..., password=NULL, password_duration=1, create_service_principal=TRUE) + { + res <- az_app$new(self$token, self$tenant, displayName=name, + password=password, password_duration=password_duration, ...) + if(create_service_principal) + res$create_service_principal() + res + }, + + get_app=function(app_id=NULL, object_id=NULL) + { + az_app$new(self$token, self$tenant, app_id, object_id) + }, + + delete_app=function(app_id=NULL, object_id=NULL, confirm=TRUE) + { + self$get_app(app_id, object_id)$delete(confirm=confirm) + }, + + create_service_principal=function(app_id, ...) + { + az_service_principal$new(self$token, self$tenant, app_id=app_id, ..., mode="create") + }, + + get_service_principal=function(app_id=NULL, object_id=NULL) + { + az_service_principal$new(self$token, self$tenant, app_id, object_id, mode="get") + }, + + delete_service_principal=function(app_id=NULL, object_id=NULL, confirm=TRUE) + { + self$get_service_principal(app_id, object_id)$delete(confirm=confirm) + }, + + print=function(...) + { + cat("\n") + cat("\n") + fmt_token <- gsub("\n ", "\n ", format_auth_header(self$token)) + cat(" ", fmt_token) + cat("---\n") + cat(format_public_methods(self)) + invisible(self) + } +)) + + +normalize_graph_tenant <- function(tenant) +{ + tenant <- tolower(tenant) + if(tenant == "common") + "myorganization" + else normalize_tenant(tenant) +} diff --git a/R/az_svc_principal.R b/R/az_svc_principal.R new file mode 100644 index 0000000..135e23d --- /dev/null +++ b/R/az_svc_principal.R @@ -0,0 +1,64 @@ +#' @export +az_service_principal <- R6::R6Class("az_service_principal", + +public=list( + + token=NULL, + tenant=NULL, + + # app data from server + properties=NULL, + + # need explicit mode arg because initialize(app_id) can either create a new SP or get an existing one + initialize=function(token, tenant=NULL, app_id=NULL, object_id=NULL, ..., deployed_properties=list(), mode="get") + { + self$token <- token + self$tenant <- tenant + + self$properties <- if(!is_empty(list(...)) || mode == "create") + private$init_and_deploy(appId=app_id, ...) + else if(!is_empty(deployed_properties)) + private$init_from_parms(deployed_properties) + else private$init_from_host(app_id, object_id) + }, + + delete=function(confirm=TRUE) + { + if(confirm && interactive()) + { + msg <- paste0("Do you really want to delete the '", self$properties$displayName, + "' service principal? (y/N) ") + yn <- readline(msg) + if(tolower(substr(yn, 1, 1)) != "y") + return(invisible(NULL)) + } + + op <- file.path("servicePrincipals", self$properties$objectId) + call_azure_graph(self$token, self$tenant, op, http_verb="DELETE") + invisible(NULL) + } +), + +private=list( + + init_and_deploy=function(...) + { + properties <- list(...) + + call_azure_graph(self$token, self$tenant, "servicePrincipals", body=properties, encode="json", http_verb="POST") + }, + + init_from_parms=function(parms) + { + parms + }, + + init_from_host=function(app_id, object_id) + { + op <- if(is.null(object_id)) + file.path("servicePrincipalsByAppId", app_id) + else file.path("servicePrincipals", object_id) + + call_azure_graph(self$token, self$tenant, op) + } +)) diff --git a/R/call_azure.R b/R/call_azure.R new file mode 100644 index 0000000..3253222 --- /dev/null +++ b/R/call_azure.R @@ -0,0 +1,115 @@ +#' Call the Azure AD Graph REST API +#' +#' @param token An Azure OAuth token, of class [AzureToken]. +#' @param tenant An Azure Active Directory tenant. Can be a GUID, a domain name, or "myorganization" to use the tenant of the logged-in user. +#' @param operation The operation to perform, which will form part of the URL path. +#' @param options A named list giving the URL query parameters. +#' @param api_version The API version to use, which will form part of the URL sent to the host. +#' @param url A complete URL to send to the host. +#' @param http_verb The HTTP verb as a string, one of `GET`, `PUT`, `POST`, `DELETE`, `HEAD` or `PATCH`. +#' @param http_status_handler How to handle in R the HTTP status code of a response. `"stop"`, `"warn"` or `"message"` will call the appropriate handlers in httr, while `"pass"` ignores the status code. +#' @param auto_refresh Whether to refresh/renew the OAuth token if it is no longer valid. +#' @param ... Other arguments passed to lower-level code, ultimately to the appropriate functions in httr. +#' +#' @details +#' These functions form the low-level interface between R and Azure. `call_azure_graph` builds a URL from its arguments and passes it to `call_azure_url`. Authentication is handled automatically. +#' +#' @return +#' If `http_status_handler` is one of `"stop"`, `"warn"` or `"message"`, the status code of the response is checked. If an error is not thrown, the parsed content of the response is returned with the status code attached as the "status" attribute. +#' +#' If `http_status_handler` is `"pass"`, the entire response is returned without modification. +#' +#' @seealso +#' [httr::GET], [httr::PUT], [httr::POST], [httr::DELETE], [httr::stop_for_status], [httr::content] +#' @rdname call_azure +#' @export +call_azure_graph <- function(token, tenant="myorganization", operation, ..., + options=list(), + api_version=getOption("azure_graph_api_version")) +{ + url <- httr::parse_url(token$credentials$resource) + url$path <- construct_path(tenant, operation) + url$query <- modifyList(list(`api-version`=api_version), options) + + call_azure_url(token, httr::build_url(url), ...) +} + + +#' @rdname call_azure +#' @export +call_azure_url <- function(token, url, ..., + http_verb=c("GET", "DELETE", "PUT", "POST", "HEAD", "PATCH"), + http_status_handler=c("stop", "warn", "message", "pass"), + auto_refresh=TRUE) +{ + headers <- process_headers(token, ..., auto_refresh=auto_refresh) + verb <- get(match.arg(http_verb), getNamespace("httr")) + + # do actual API call + res <- verb(url, headers, ...) + + process_response(res, match.arg(http_status_handler)) +} + + +process_headers <- function(token, ..., auto_refresh) +{ + # if token has expired, renew it + if(auto_refresh && !token$validate()) + { + message("Access token has expired or is no longer valid; refreshing") + token$refresh() + } + + creds <- token$credentials + host <- httr::parse_url(creds$resource)$host + headers <- c(Host=host, Authorization=paste(creds$token_type, creds$access_token)) + + # default content-type is json, set this if encoding not specified + dots <- list(...) + if(is_empty(dots) || !("encode" %in% names(dots)) || dots$encode == "raw") + headers <- c(headers, `Content-type`="application/json") + + httr::add_headers(.headers=headers) +} + + +process_response <- function(response, handler) +{ + if(handler != "pass") + { + cont <- httr::content(response) + handler <- get(paste0(handler, "_for_status"), getNamespace("httr")) + handler(response, paste0("complete operation. Message:\n", + sub("\\.$", "", error_message(cont)))) + if(is.null(cont)) + cont <- list() + attr(cont, "status") <- httr::status_code(response) + cont + } + else response +} + + +# provide complete error messages from Resource Manager/AAD Graph/etc +error_message <- function(cont) +{ + # kiboze through possible message locations + msg <- if(is.character(cont)) + cont + else if(inherits(cont, "xml_node")) # Graph + paste(xml2::xml_text(xml2::xml_children(cont)), collapse=": ") + else if(is.list(cont)) + { + if(is.character(cont$message)) + cont$message + else if(is.list(cont$error) && is.character(cont$error$message)) + cont$error$message + else if(is.list(cont$odata.error)) # Graph OData + cont$odata.error$message$value + } + else "" + + paste0(strwrap(msg), collapse="\n") +} + diff --git a/man/az_graph.Rd b/man/az_graph.Rd new file mode 100644 index 0000000..8949697 --- /dev/null +++ b/man/az_graph.Rd @@ -0,0 +1,78 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/az_graph.R +\docType{class} +\name{az_graph} +\alias{az_graph} +\title{Azure Active Directory Graph} +\format{An R6 object of class \code{az_graph}.} +\usage{ +az_graph +} +\description{ +Base class for interacting with Azure AD Graph API. +} +\section{Methods}{ + +\itemize{ +\item \code{new(tenant, app, ...)}: Initialize a new ARM connection with the given credentials. See 'Authentication` for more details. +\item \code{create_app(name, ..., password=NULL, create_service_principal=TRUE)}: Creates a new registered app in Azure Active Directory. By default the app will have a randomly generated strong password with a duration of 1 year, and an associated service principal will also be created. +\item \code{get_app(app_id, object_id)}: Retrieves an existing registered app, via either its app ID or object ID. +\item \code{delete_app(app_id, object_id, confirm=TRUE)}: Deletes an existing registered app. Any associated service principal will also be deleted. +\item \code{create_service_principal(app_id, ...)}: Creates a service principal for a registered app. +\item \code{get_service_principal()}: Retrieves an existing service principal. +\item \code{delete_service_principal()}: Deletes an existing service principal. +} +} + +\section{Authentication}{ + +The recommended way to authenticate with Azure AD Graph is via the \link{create_graph_login} function, which creates a new instance of this class. + +To authenticate with the \code{az_graph} class directly, provide the following arguments to the \code{new} method: +\itemize{ +\item \code{tenant}: Your tenant ID. This can be a name ("myaadtenant"), a fully qualified domain name ("myaadtenant.onmicrosoft.com" or "mycompanyname.com"), or a GUID. +\item \code{app}: The client/app ID to use to authenticate with Azure Active Directory. The default is to login interactively using the Azure CLI cross-platform app, but it's recommended to supply your own app credentials if possible. +\item \code{password}: if \code{auth_type == "client_credentials"}, the app secret; if \code{auth_type == "resource_owner"}, your account password. +\item \code{username}: if \code{auth_type == "resource_owner"}, your username. +\item \code{auth_type}: The OAuth authentication method to use, one of "client_credentials", "authorization_code", "device_code" or "resource_owner". See \link{get_azure_token} for how the default method is chosen, along with some caveats. +\item \code{host}: your Azure AD Graph host. Defaults to \code{https://graph.windows.net/}. Change this if you are using a government or private cloud. +\item \code{aad_host}: Azure Active Directory host for authentication. Defaults to \code{https://login.microsoftonline.com/}. Change this if you are using a government or private cloud. +\item \code{config_file}: Optionally, a JSON file containing any of the arguments listed above. Arguments supplied in this file take priority over those supplied on the command line. You can also use the output from the Azure CLI \code{az ad sp create-for-rbac} command. +\item \code{token}: Optionally, an OAuth 2.0 token, of class \link{AzureToken}. This allows you to reuse the authentication details for an existing session. If supplied, all other arguments will be ignored. +} +} + +\examples{ +\dontrun{ + +# start a new Resource Manager session +gr <- az_graph$new(tenant="myaadtenant.onmicrosoft.com", app="app_id", password="password") + +# authenticate with credentials in a file +gr <- az_graph$new(config_file="creds.json") + +# authenticate with device code +gr <- az_graph$new(tenant="myaadtenant.onmicrosoft.com", app="app_id", auth_type="device_code") + +# retrieve a registered app +gr$get_app(app_id="myappid") + +# create a new app and associated service principal, set password duration to 10 years +app <- gr$create_app("mynewapp", password_duration=10) + +svc <- gr$get_service_principal(app_id=app$properties$appId) + +# delete the app +gr$delete_app(app_id=app$properties$appId) +# ... but better to call the object's delete method directly +app$delete() + +} +} +\seealso{ +\link{create_graph_login}, \link{get_graph_login} + +\href{https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-graph-api}{Azure AD Graph overview}, +\href{https://docs.microsoft.com/en-au/previous-versions/azure/ad/graph/api/api-catalog}{REST API reference} +} +\keyword{datasets} diff --git a/man/call_azure.Rd b/man/call_azure.Rd new file mode 100644 index 0000000..b455165 --- /dev/null +++ b/man/call_azure.Rd @@ -0,0 +1,49 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/call_azure.R +\name{call_azure_graph} +\alias{call_azure_graph} +\alias{call_azure_url} +\title{Call the Azure AD Graph REST API} +\usage{ +call_azure_graph(token, tenant = "myorganization", operation, ..., + options = list(), api_version = getOption("azure_graph_api_version")) + +call_azure_url(token, url, ..., http_verb = c("GET", "DELETE", "PUT", + "POST", "HEAD", "PATCH"), http_status_handler = c("stop", "warn", + "message", "pass"), auto_refresh = TRUE) +} +\arguments{ +\item{token}{An Azure OAuth token, of class \link{AzureToken}.} + +\item{tenant}{An Azure Active Directory tenant. Can be a GUID, a domain name, or "myorganization" to use the tenant of the logged-in user.} + +\item{operation}{The operation to perform, which will form part of the URL path.} + +\item{...}{Other arguments passed to lower-level code, ultimately to the appropriate functions in httr.} + +\item{options}{A named list giving the URL query parameters.} + +\item{api_version}{The API version to use, which will form part of the URL sent to the host.} + +\item{url}{A complete URL to send to the host.} + +\item{http_verb}{The HTTP verb as a string, one of \code{GET}, \code{PUT}, \code{POST}, \code{DELETE}, \code{HEAD} or \code{PATCH}.} + +\item{http_status_handler}{How to handle in R the HTTP status code of a response. \code{"stop"}, \code{"warn"} or \code{"message"} will call the appropriate handlers in httr, while \code{"pass"} ignores the status code.} + +\item{auto_refresh}{Whether to refresh/renew the OAuth token if it is no longer valid.} +} +\value{ +If \code{http_status_handler} is one of \code{"stop"}, \code{"warn"} or \code{"message"}, the status code of the response is checked. If an error is not thrown, the parsed content of the response is returned with the status code attached as the "status" attribute. + +If \code{http_status_handler} is \code{"pass"}, the entire response is returned without modification. +} +\description{ +Call the Azure AD Graph REST API +} +\details{ +These functions form the low-level interface between R and Azure. \code{call_azure_graph} builds a URL from its arguments and passes it to \code{call_azure_url}. Authentication is handled automatically. +} +\seealso{ +\link[httr:GET]{httr::GET}, \link[httr:PUT]{httr::PUT}, \link[httr:POST]{httr::POST}, \link[httr:DELETE]{httr::DELETE}, \link[httr:stop_for_status]{httr::stop_for_status}, \link[httr:content]{httr::content} +}