maz

package module
v2.0.0-rc7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 21, 2025 License: MIT Imports: 22 Imported by: 0

README

maz

This is a Go library package module for managing Microsoft Azure resource and security objects. Please see https://que.one/azure/ to better understand what is meant by resource and security objects. Essentially this library provides basic MSAL authentication and token creation to allow principals to call the two supported Azure APIs, the Azure Resource Managment (ARM) API and the MS Graph API. Other APIs could be added in the future.

Why?

  • Learning/Experimentation: Building your own SDK can be a great way to learn more about Go and REST API development.
  • Specialized Use Cases: If your application only interacts with this smaller subset of Microsoft Graph APIs, then this lightweight custom SDK might be simpler and faster.
  • Control Over Dependencies: The official SDK might introduce dependencies or abstractions you want to avoid.
  • Custom Abstractions: If you need custom abstractions or behavior not easily achieved with the official SDK.

Getting Started

  1. To use this library, import the module then instantiate a variable of type maz.Config to manage the interaction. For example:
import (
    "github.com/queone/maz"
)

z := maz.NewConfig()
  • From then on, above global config z pointer variable can be used for managing the interation with the library.
  • This variable includes things like z.ConfDir, which defaults to ~/.maz, and so on.
  • See https://github.com/queone/maz/blob/main/maz.go for more information on the Config type, and what methods are available.
  1. Your program should then call maz.SetupInterativeLogin(z) or maz.SetupAutomatedLogin(z) to setup the credentials file accordingly.

  2. Then it should call z := maz.SetupApiTokens(*z) to acquire the respective API tokens, web headers, and other variables.

  3. Afterwards, it can then call whatever MS Graph and Azure Resource API functions you want by passing and using the z variables, with its z.mgHeaders and/or z.azHeaders attributes, and so on.

  4. The best way to understand this is to look at code of an example program like azgrp.

Login Credentials

There are four (4) different ways to set up the login credentials to use this library module. All four ways required three (3) special attributes:

# Type Method Details
1 Interactive Config file Set up attributes via ~/.maz/credentials.yaml file
2 Interactive Environment variables Set up attributes via environment variables (OVERIDES config file)
3 Automated Config file Set up attributes via ~/.maz/credentials.yaml file
4 Automated Environment variables Set up attributes via environment variables (OVERIDES config file)
  1. Interactive via config file: The calling utility sets up a way to allow setting up the ~/.maz/credentials.yaml file with the 3 special attributes. For example, the azm CLI utility does this via the -id switch, to Set up MSAL interactive browser popup login:

    azm -id 3f050090-20b0-40a0-a060-c05060104010 user1@domain.io
    

    Above will populate the ~/.maz/credentials.yaml file as follows:

    tenant_id: 3f050090-20b0-40a0-a060-c05060104010
    username: user1@domain.io
    interactive: true
    

    From then on the azm utility will use above credentials to interact with the maz library to perform all its functions.

  2. Interactive via environment variables: The calling utility will instead use the os.Getenv("VAR") function to look for the following 3 special environment variables:

    MAZ_TENANT_ID=3f050090-20b0-40a0-a060-c05060104010
    MAZ_USERNAME=user1@domain.io
    MAZ_INTERACTIVE=true
    

    Above values take precedence and OVERIDE any existing config ~/.maz/credentials.yaml file values.

  3. Automated via config file: The calling utility sets up a way to allow setting up the ~/.maz/credentials.yaml file with the 3 special attributes. For example, the azm CLI utility does this via the -id switch, to Set up MSAL automated ClientId + Secret login:

    azm -id 3f050090-20b0-40a0-a060-c05060104010 f1110121-7111-4171-a181-e1614131e181 ACB8c~HdLejfQGiHeI9LUKgNOODPQRISNTmVLX_i
    

    Above will populate the ~/.maz/credentials.yaml file as follows:

    tenant_id: 3f050090-20b0-40a0-a060-c05060104010
    client_id: f1110121-7111-4171-a181-e1614131e181
    client_secret: ACB8c~HdLejfQGiHeI9LUKgNOODPQRISNTmVLX_i
    

    From then on the azm utility will use above credentials to interact with the maz library to perform all its functions.

  4. Automated via environment variables: The calling utility will instead use the os.Getenv("VAR") function to look for the following 3 special environment variables

    MAZ_TENANT_ID=3f050090-20b0-40a0-a060-c05060104010
    MAZ_CLIENT_ID=f1110121-7111-4171-a181-e1614131e181
    MAZ_CLIENT_SECRET=ACB8c~HdLejfQGiHeI9LUKgNOODPQRISNTmVLX_i
    

    Above values take precedence and OVERIDE any existing config ~/.maz/credentials.yaml file values.

The benefit of using environment variables is to be able to override an existing credentials.yaml file, and to specify different credentials, as well as being able to use different credentials from different shell sessions on the same host. They also allow utilities written with this library to be used in continuous delivery and other types of automation.

NOTE: If all four MAZ_USERNAME, MAZ_INTERACTIVE, MAZ_CLIENT_ID, and MAZ_CLIENT_SECRET are properly define, then precedence is given to the Username Interactive login. To force a ClientID ClientSecret login via environment variables, you must ensure the first two are unset in the current shell.

Functions

TODO: List of all available functions?

  • maz.SetupInterativeLogin: This functions allows you to set up the~/.maz/credentials.yaml file for interactive Azure login.
  • ...

Releases

See releases

Documentation

Overview

Package maz is a library of functions for interacting with essential Azure APIs via REST calls. Currently it supports two APIs, the Azure Resource Management (ARM) API and the MS Graph API, but can be extended to support additional APIs. This package obviously also includes code to get an Azure JWT token using the MSAL library, to then use against either the 2 currently supported Azure APIs.

Index

Constants

View Source
const (
	NeitherExists = iota // 0: Neither App nor SP exists
	OnlySPExists         // 1: Only SP exists
	OnlyAppExists        // 2: Only App exists
	BothExist            // 3: Both App and SP exist
)
View Source
const (
	ConstAuthUrl = "https://login.microsoftonline.com/"
	ConstMgUrl   = "https://graph.microsoft.com"
	ConstAzUrl   = "https://management.azure.com"

	ConstAzPowerShellClientId = "1950a258-227b-4e31-a9cf-717495945fc2" // 'Microsoft Azure PowerShell' ClientId

	ConstCacheFileExtension   = "gz"
	ConstMgCacheFileAgePeriod = 1800  // Half hour
	ConstAzCacheFileAgePeriod = 86400 // One day
)

Variables

View Source
var (
	CacheSuffix = map[string]string{
		"d":  "_res-role-defs",
		"a":  "_res-role-assgns",
		"s":  "_res-subs",
		"mg": "_res-mgmt-groups",
		"u":  "_dir-users",
		"g":  "_dir-groups",
		"sp": "_dir-sps",
		"ap": "_dir-apps",
		"ad": "_dir-roles",
	}
	ApiEndpoint = map[string]string{
		"d":  "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleDefinitions",
		"a":  "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments",
		"s":  "/subscriptions",
		"mg": "/providers/Microsoft.Management/managementGroups",
		"u":  "/v1.0/users",
		"g":  "/v1.0/groups",
		"sp": "/v1.0/servicePrincipals",
		"ap": "/v1.0/applications",
		"ad": "/v1.0/roleDefinitions",
	}
	MazObjName = map[string]string{
		"d":  "resource RBAC role definition",
		"a":  "resource RBAC role assignment",
		"s":  "resource subscription",
		"mg": "resource management group",
		"u":  "directory user",
		"g":  "directory group",
		"sp": "directory service principal",
		"ap": "directory application",
		"ad": "directory role definition",
	}
)

Functions

func AdRolesCountAzure

func AdRolesCountAzure(z *Config) int64

Returns count of Azure AD directory role entries in current tenant

func AdRolesCountLocal

func AdRolesCountLocal(z *Config) int64

Returns count of Azure AD directory role entries in local cache file

func AddAppSpSecret

func AddAppSpSecret(t, id, displayName, expiry string, z *Config)

Adds a new secret to the given App or SP

func ApiCall

func ApiCall(method, apiUrl string, z *Config, payload jsonT, params strMapT, verbose bool) (result jsonT, rsc int, err error)

Makes API calls and returns JSON object, Response StatusCode, and error. For a more clear explanation of how to interpret the JSON responses see https://eager.io/blog/go-and-json/ This function is the cornerstone of the maz package, extensively handling all API interactions.

func ApiDelete

func ApiDelete(apiUrl string, z *Config, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a DELETE

func ApiDeleteDebug

func ApiDeleteDebug(apiUrl string, z *Config, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a DELETE with debugging on

func ApiErrorCheck

func ApiErrorCheck(method, apiUrl, caller string, r jsonT)

Prints useful error information if they occur

func ApiGet

func ApiGet(apiUrl string, z *Config, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a GET

func ApiGetDebug

func ApiGetDebug(apiUrl string, z *Config, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a GET with debugging on

func ApiPatch

func ApiPatch(apiUrl string, z *Config, payload jsonT, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a PATCH

func ApiPatchDebug

func ApiPatchDebug(apiUrl string, z *Config, payload jsonT, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a PATCH with debugging on

func ApiPost

func ApiPost(apiUrl string, z *Config, payload jsonT, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a POST

func ApiPostDebug

func ApiPostDebug(apiUrl string, z *Config, payload jsonT, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a POST with debugging on

func ApiPut

func ApiPut(apiUrl string, z *Config, payload jsonT, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a PUT

func ApiPutDebug

func ApiPutDebug(apiUrl string, z *Config, payload jsonT, params strMapT) (result jsonT, rsc int, err error)

ApiCall alias to do a PUT with debugging on

func CompareSpecfileToAzure

func CompareSpecfileToAzure(filePath string, z *Config)

Compares object in specfile to what is in Azure

func CreateAppSpByName

func CreateAppSpByName(force bool, displayName string, z *Config) error

Creates an App/SP object pair by name, if they don't already exist.

func CreateAzRoleAssignment

func CreateAzRoleAssignment(x map[string]interface{}, z *Config)

Creates an RBAC role assignment as defined by give x object

func CreateSkeletonFile

func CreateSkeletonFile(t string)

Creates specfile skeleton/scaffold files

func DecodeJwtToken

func DecodeJwtToken(tokenString string)

Decode and dump token string, trusting without formal verification and validation

func DeleteAppSpByIdentifier

func DeleteAppSpByIdentifier(force bool, identifier string, z *Config)

Deletes Azure AppSP pair from given command-line arguments.

func DeleteAzObject

func DeleteAzObject(force bool, specifier string, z *Config)

Deletes object based on string specifier (currently only supports roleDefinitions or Assignments) String specifier can be either of 3: UUID, specfile, or displaName (only for roleDefinition) 1) Search Azure by given identifier; 2) Grab object's Fully Qualified Id string; 3) Print and prompt for confirmation; 4) Delete or abort

func DeleteAzRoleAssignmentByFqid

func DeleteAzRoleAssignmentByFqid(fqid string, z *Config) map[string]interface{}

Deletes an RBAC role assignment by its fully qualified object Id Example of a fully qualified Id string (note it's one long line):

/providers/Microsoft.Management/managementGroups/33550b0b-2929-4b4b-adad-cccc66664444 \
  /providers/Microsoft.Authorization/roleAssignments/5d586a7b-3f4b-4b5c-844a-3fa8efe49ab3

func DeleteAzRoleDefinitionByFqid

func DeleteAzRoleDefinitionByFqid(fqid string, z *Config) map[string]interface{}

Deletes an RBAC role definition object by its fully qualified object Id Example of a fully qualified Id string:

"/providers/Microsoft.Authorization/roleDefinitions/50a6ff7c-3ac5-4acc-b4f4-9a43aee0c80f"

func DeleteDirObject

func DeleteDirObject(opts *Options, z *Config) error

Deletes directory object of given type in Azure, with a confirmation prompt.

func DeleteDirObjectInAzure

func DeleteDirObjectInAzure(t, id string, z *Config) error

Deletes directory object of given type in Azure, and updates local cache.

func DiffLists

func DiffLists(list1, list2 []interface{}) (added, removed []interface{}, same bool)

Compares two list of strings and returns added and removed items, and whether or not the lists are the same. Note they come in as []interface{} but we know they are strings. This is a special function for handling Azure RBAC role definition action differences.

func DiffRoleDefinitionSpecfileVsAzure

func DiffRoleDefinitionSpecfileVsAzure(a, b map[string]interface{}, z *Config)

Prints differences between role definition in Specfile (a) vs what is in Azure (b). The calling function must ensure that both a & b are valid role definition objects from a specfile and from Azure. A generic DiffJsonObject() function would probably be better for this.

func DumpLoginValues

func DumpLoginValues(z *Config)

Dumps configured login values

func FetchDirObjectsDelta

func FetchDirObjectsDelta(apiUrl string, z *Config, verbose bool) (deltaSet AzureObjectList, deltaLinkMap AzureObject)

Retrieves Azure directory object deltas. Returns the set of new or updated items, and a deltaLink for running the next future Azure query. Implements the code logic pattern described at https://docs.microsoft.com/en-us/graph/delta-query-overview

func FindAzObjectsById

func FindAzObjectsById(id string, z *Config) (list []interface{})

Returns list of Azure objects with this UUID. We are saying a list because 1) the UUID could be an appId shared by an app and an SP, or 2) there could be UUID collisions with multiple objects potentially sharing the same UUID. Only checks for the maz package limited set of Azure object types.

func FindObjectOld

func FindObjectOld(objSet []interface{}, id string) map[string]interface{}

Find JSON object with given ID in slice

func GetAzAdRoleById

func GetAzAdRoleById(id string, z *Config) map[string]interface{}

Gets Azure AD role definition by Object UUID, with all attributes

func GetAzAdRoles

func GetAzAdRoles(z *Config, verbose bool) (list []interface{})

Gets all directory role definitions from Azure and sync to local cache. Shows progress if verbose = true

func GetAzAllPages

func GetAzAllPages(apiUrl string, z *Config) (list []interface{})

Returns all Azure pages for given API URL call

func GetAzMgGroups

func GetAzMgGroups(z *Config) (list []interface{})

Gets all management groups in current Azure tenant, and saves them to local cache file

func GetAzObjectById

func GetAzObjectById(t, id string, z *Config) (x map[string]interface{})

Retrieves Azure object by Object UUID

func GetAzObjects

func GetAzObjects(apiUrl string, z *Config, verbose bool) (deltaSet []interface{}, deltaLinkMap map[string]interface{})

func GetAzRbacScopes

func GetAzRbacScopes(z *Config) (scopes []string)

Gets all scopes in the Azure tenant RBAC hierarchy: Tenant Root Group and all management groups, plus all subscription scopes

func GetAzRoleAssignmentById

func GetAzRoleAssignmentById(id string, z *Config) map[string]interface{}

Gets RBAC role assignment by its Object UUID. Unfortunately we have to iterate through the entire tenant scope hierarchy, which can take time.

func GetAzRoleAssignmentByObject

func GetAzRoleAssignmentByObject(x map[string]interface{}, z *Config) (y map[string]interface{})

Gets Azure resource RBAC role assignment object by matching given objects: roleId, principalId, and scope (the 3 parameters which make a role assignment unique)

func GetAzRoleAssignments

func GetAzRoleAssignments(z *Config, verbose bool) (list []interface{})

Gets all role assignments objects in current Azure tenant and save them to local cache file. Option to be verbose (true) or quiet (false), since it can take a while. References:

https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-list-rest
https://learn.microsoft.com/en-us/rest/api/authorization/role-assignments/list-for-subscription

func GetAzRoleDefinitionById

func GetAzRoleDefinitionById(id string, z *Config) map[string]interface{}

Gets role definition by Object Id. Unfortunately we have to iterate through the entire tenant scope hierarchy, which can take time.

func GetAzRoleDefinitionByName

func GetAzRoleDefinitionByName(roleName string, z *Config) (y map[string]interface{})

Gets role definition by displayName See https://learn.microsoft.com/en-us/rest/api/authorization/role-definitions/list

func GetAzRoleDefinitionByObject

func GetAzRoleDefinitionByObject(x map[string]interface{}, z *Config) (y map[string]interface{})

Gets role definition object if it exists exactly as x object (as per essential attributes). Matches on: displayName and assignableScopes

func GetAzRoleDefinitions

func GetAzRoleDefinitions(z *Config, verbose bool) (list []interface{})

Gets all role definitions in current Azure tenant and save them to local cache file Option to be verbose (true) or quiet (false), since it can take a while. References:

https://learn.microsoft.com/en-us/azure/role-based-access-control/role-definitions-list
https://learn.microsoft.com/en-us/rest/api/authorization/role-definitions/list

func GetAzSubscriptionById

func GetAzSubscriptionById(id string, z *Config) map[string]interface{}

Gets specific Azure subscription by Object UUID

func GetAzSubscriptions

func GetAzSubscriptions(z *Config) (list []interface{})

Gets all subscription in current Azure tenant, and saves them to local cache file

func GetAzSubscriptionsIds

func GetAzSubscriptionsIds(z *Config) (scopes []string)

Gets all subscription full IDs, i.e. "/subscriptions/UUID", which are commonly used as scopes for Azure resource RBAC role definitions and assignments

func GetAzUserById

func GetAzUserById(id string, z *Config) map[string]interface{}

Gets Azure user object by Object UUID, with all attributes

func GetAzUsers

func GetAzUsers(z *Config, verbose bool) (list []interface{})

Gets all users from Azure and sync to local cache. Show progress if verbose = true

func GetCachedObjects

func GetCachedObjects(cacheFile string) (cachedList []interface{})

Retrieves locally cached list of objects in given cache file

func GetDirObjectIdMap

func GetDirObjectIdMap(t string, z *Config) map[string]string

Returns an id:name map of objects of the given type.

func GetIdMapMgGroups

func GetIdMapMgGroups(z *Config) (nameMap map[string]string)

Returns id:name map of management groups

func GetIdMapRoleDefs

func GetIdMapRoleDefs(z *Config) (nameMap map[string]string)

Returns id:name map of all RBAC role definitions

func GetIdMapSubs

func GetIdMapSubs(z *Config) (nameMap map[string]string)

Returns id:name map of all subscriptions

func GetIdMapUsers

func GetIdMapUsers(z *Config) (nameMap map[string]string)

Returns an id:name map of all users

func GetMatchingAdRoles

func GetMatchingAdRoles(filter string, force bool, z *Config) (list []interface{})

Gets all AD roles matching on 'filter'. Returns entire list if filter is empty ""

func GetMatchingMgGroups

func GetMatchingMgGroups(filter string, force bool, z *Config) (list []interface{})

Gets all Azure management groups matching on 'filter'. Returns entire list if filter is empty ""

func GetMatchingRoleAssignments

func GetMatchingRoleAssignments(filter string, force bool, z *Config) (list []interface{})

Gets all RBAC role assignments matching on 'filter'. Return entire list if filter is empty ""

func GetMatchingRoleDefinitions

func GetMatchingRoleDefinitions(filter string, force bool, z *Config) (list []interface{})

Gets all role definitions matching on 'filter'. Returns entire list if filter is empty ""

func GetMatchingSubscriptions

func GetMatchingSubscriptions(filter string, force bool, z *Config) (list []interface{})

Gets all Azure subscriptions matching on 'filter'. Returns entire list if filter is empty ""

func GetMatchingUsers

func GetMatchingUsers(filter string, force bool, z *Config) (list []interface{})

Gets all users matching on 'filter'. Returns entire list if filter is empty ""

func GetObjectFromFile

func GetObjectFromFile(filePath string) (formatType, t string, specfileObj map[string]interface{})

Processes given specfile and returns the specfile format type, the maz object letter string type, and the actual object.

func GetObjects

func GetObjects(t, filter string, force bool, z *Config) (list []interface{})

Generic function to get objects of type t whose attributes match on filter. If filter is the "" empty string return ALL of the objects of this type.

func GetTokenByCredentials

func GetTokenByCredentials(scopes []string, z *Config) (token string, err error)

Initiates an Azure JWT token acquisition with provided parameters, using a Client ID plus a Client Secret. This is the 'Confidential' app auth flow and is documented at: https://github.com/AzureAD/microsoft-authentication-library-for-go/blob/dev/apps/confidential/confidential.go

func GetTokenInteractively

func GetTokenInteractively(scopes []string, z *Config) (token string, err error)

Initiates an Azure JWT token acquisition with provided parameters, using a Username and a browser pop up window. This is the 'Public' app auth flow as documented at: https://github.com/AzureAD/microsoft-authentication-library-for-go/blob/dev/apps/public/public.go

func MergeAzureObjects

func MergeAzureObjects(newObj, existingObj AzureObject)

Recursively merges the keys from AzureObject a into b. Existing object b attributes are overwritten if there's a conflict.

func MgGroupCountAzure

func MgGroupCountAzure(z *Config) int64

Returns count of management groups in Azure

func MgGroupCountLocal

func MgGroupCountLocal(z *Config) int64

Returns count of management group objects in local cache file

func MgType

func MgType(typeIn string) string

Returns ARM object type based on long string

func NormalizeCache

func NormalizeCache(baseSet, deltaSet []interface{}) (list []interface{})

Builds JSON mergeSet from deltaSet, and builds and returns the list of deleted IDs

func ObjectCountAzure

func ObjectCountAzure(t string, z *Config) int64

Returns the number of objects of given type in the Azure tenant.

func ObjectCountLocal

func ObjectCountLocal(t string, z *Config) int64

Returns the number of object entries in the local cache file for the given type.

func PrintAdRole

func PrintAdRole(x map[string]interface{}, z *Config)

Prints Azure AD role definition object in YAML-like format

func PrintApiErrMsg

func PrintApiErrMsg(msg string)

Prints API error messages in 2 parts separated by a newline: A header, then a JSON byte slice

func PrintApp

func PrintApp(x AzureObject, z *Config)

Prints application object in YAML-like format

func PrintAppRoleAssignmentsOthers

func PrintAppRoleAssignmentsOthers(appRoleAssignments []interface{}, z *Config)

Prints appRoleAssignments for other types of objects (Users and Groups)

func PrintAppRoleAssignmentsSp

func PrintAppRoleAssignmentsSp(roleNameMap map[string]string, appRoleAssignments []interface{})

Prints appRoleAssignments for given service principal (SP)

func PrintCertificateList

func PrintCertificateList(certificates []interface{})

Prints certificate list stanza for Apps and Sps

func PrintCountStatus

func PrintCountStatus(z *Config)

Prints a status count of all AZ and MG objects that are in Azure, and the local files.

func PrintCountStatusAppsAndSps

func PrintCountStatusAppsAndSps(z *Config)

func PrintCountStatusGroups

func PrintCountStatusGroups(z *Config)

func PrintGroup

func PrintGroup(x AzureObject, z *Config)

Print directory group object in YAML-like format

func PrintHeaders

func PrintHeaders(headers http.Header)

Prints HTTP headers specific to API calls. Simplifies ApiCall function.

func PrintMatching

func PrintMatching(printFormat, t, specifier string, z *Config)

Prints all objects that match on given specifier

func PrintMemberOfs

func PrintMemberOfs(t string, memberOf []interface{})

Prints all memberOf entries

func PrintMgChildren

func PrintMgChildren(indent int, children []interface{})

Recursively print management groups and all its children MGs and subscriptions

func PrintMgGroup

func PrintMgGroup(x map[string]interface{})

Prints management group object in YAML-like format

func PrintMgTree

func PrintMgTree(z *Config)

Gets current tenant management group tree, and recursively calls function PrintMgChildren() to print the hierarchy

func PrintObject

func PrintObject(t string, x map[string]interface{}, z *Config)

Generic print object function

func PrintObjectById

func PrintObjectById(id string, z *Config)

Prints object by given UUID

func PrintOwners

func PrintOwners(owners []interface{})

Print owners stanza for Apps and Sps

func PrintPags

func PrintPags(z *Config)

Lists all cached Privileged Access Groups (PAGs)

func PrintParams

func PrintParams(params url.Values)

Prints HTTP parameters specific to API calls. Simplifies ApiCall function.

func PrintRoleAssignment

func PrintRoleAssignment(x map[string]interface{}, z *Config)

Prints RBAC role definition object in YAML-like format

func PrintRoleAssignmentReport

func PrintRoleAssignmentReport(z *Config)

Prints a human-readable report of all RBAC role assignments

func PrintRoleDefinition

func PrintRoleDefinition(x map[string]interface{}, z *Config)

Prints role definition object in a YAML-like format

func PrintSecretList

func PrintSecretList(secretsList []interface{})

Prints secret list stanza for App and SP objects

func PrintSp

func PrintSp(x AzureObject, z *Config)

Prints service principal object in YAML-like format

func PrintStringMapColor

func PrintStringMapColor(strMap map[string]string)

Prints string map in YAML-like format, sorted, and in color

func PrintSubscription

func PrintSubscription(x map[string]interface{})

Prints subscription object in YAML-like format

func PrintTersely

func PrintTersely(t string, object interface{})

Prints this single object of type 't' tersely, with minimal attributes.

func PrintUser

func PrintUser(x map[string]interface{}, z *Config)

Prints user object in YAML-like format

func RemoveAppSpSecret

func RemoveAppSpSecret(t, id, keyId string, force bool, z *Config)

Removes a secret from the given App or SP object

func RemoveCacheFile

func RemoveCacheFile(t string, z *Config)

Removes specified cache file

func RemoveCacheFiles

func RemoveCacheFiles(t string, z *Config) error

Removes cache files for a given type code and configuration. It ensures both the cache file and deltaLink file associated with the type are deleted.

func RenameAppSp

func RenameAppSp(force bool, identifier, newName string, z *Config)

Renames Azure App/SP pair

func RenameDirObject

func RenameDirObject(opts *Options, z *Config)

Renames directory object of given type in Azure.

func RoleAssignmentsCountAzure

func RoleAssignmentsCountAzure(z *Config) int64

Calculates count of all role assignment objects in Azure

func RoleAssignmentsCountLocal

func RoleAssignmentsCountLocal(z *Config) int64

Retrieves count of all role assignment objects in local cache file

func RoleDefinitionCountAzure

func RoleDefinitionCountAzure(z *Config) (builtin, custom int64)

Counts all role definition in Azure. Returns 2 lists: one of native custom roles, the other of built-in role

func RoleDefinitionCountLocal

func RoleDefinitionCountLocal(z *Config) (builtin, custom int64)

Dedicated role definition local cache counter able to discern if role is custom to native tenant or it's an Azure BuilIn role

func SaveFileBinaryList

func SaveFileBinaryList(filePath string, data AzureObjectList, perm os.FileMode, compress bool) error

Serializes a slice of AzureObject objects into a gob binary file. The file is saved with the specified permissions, optionally compressed using Gzip.

func SaveFileBinaryObject

func SaveFileBinaryObject(filePath string, data AzureObject, perm os.FileMode) error

Saves a single AzureObject as a gob binary file with specified permissions.

func SetupApiTokens

func SetupApiTokens(z *Config)

Initializes the necessary global variables, acquires all API tokens, and sets them up for use.

func SetupAutomatedLogin

func SetupAutomatedLogin(z *Config)

Sets up credentials file for client_id + secret login

func SetupCredentials

func SetupCredentials(z *Config)

Gets credentials from OS environment variables (which take precedence), or from the credentials file.

func SetupInterativeLogin

func SetupInterativeLogin(z *Config)

Sets up credentials file for interactive login

func SpsCountAzure

func SpsCountAzure(z *Config) (native, others int64)

Retrieves counts of SPs native to this Azure tenant, and all others.

func SpsCountLocal

func SpsCountLocal(z *Config) (native, others int64)

Retrieves counts of all SPs in local cache, 2 values: Native ones to this tenant, and all others.

func SubsCountAzure

func SubsCountAzure(z *Config) int64

Returns count of all subscriptions in current Azure tenant

func SubsCountLocal

func SubsCountLocal(z *Config) int64

Returns count of all subscriptions in local cache file

func SyncDirObjectsWithAzure

func SyncDirObjectsWithAzure(t string, cache *Cache, z *Config, verbose bool)

Retrieves all directory objects of given type from Azure and syncs them to local cache. Shows progress if verbose = true.

func TokenValid

func TokenValid(tokenString string) bool

Validates a JWT token *string* as defined in https://tools.ietf.org/html/rfc7519

func UpdateCacheIfNeeded

func UpdateCacheIfNeeded(t string, cache *Cache, force bool, z *Config)

Updates the local director object cache is needed

func UpdateDirObject

func UpdateDirObject(force bool, id string, obj AzureObject, t string, z *Config)

Updates directory object of given type in Azure, with a confirmation prompt.

func UpdateDirObjectInAzure

func UpdateDirObjectInAzure(t, id string, obj AzureObject, z *Config) error

Updates directory object of given type in Azure, and updates local cache.

func UpsertAppSpFromFile

func UpsertAppSpFromFile(force bool, filePath string, z *Config)

Creates or updates an Azure App/SP pair from given specfile.

func UpsertAzObject

func UpsertAzObject(force bool, filePath string, z *Config)

Creates or updates an Azure object based on given specfile

func UpsertAzRoleDefinition

func UpsertAzRoleDefinition(force bool, x map[string]interface{}, z *Config)

Creates or updates an RBAC role definition as defined by give x object

func UpsertGroupFromArgs

func UpsertGroupFromArgs(opts *Options, z *Config)

Creates or updates an Azure directory group from given command-line arguments.

func UpsertGroupFromFile

func UpsertGroupFromFile(opts *Options, z *Config)

Creates or updates an Azure directory group from given specfile.

func UsersCountAzure

func UsersCountAzure(z *Config) int64

Returns the number of entries in Azure tenant

func UsersCountLocal

func UsersCountLocal(z *Config) int64

Returns the number of entries in local cache file

Types

type AzureObject

type AzureObject map[string]interface{} // Represents a single Azure JSON object

Basic types for this package

func CheckAppSpExistence

func CheckAppSpExistence(identifier string, z *Config) (app, sp AzureObject, code int)

Checks to see whether the App and SP objects exist. Another preprocessing helper function.

func CreateDirObject

func CreateDirObject(force bool, obj AzureObject, t string, z *Config) (AzureObject, error)

Creates directory object of given type in Azure, with a confirmation prompt.

func CreateDirObjectInAzure

func CreateDirObjectInAzure(t string, obj AzureObject, z *Config) (AzureObject, error)

Creates directory object of given type in Azure, and updates local cache.

func GetObjectFromAzureById

func GetObjectFromAzureById(t, id string, z *Config) AzureObject

Gets object of given type from Azure by id. Updates entry in local cache.

func LoadFileBinaryObject

func LoadFileBinaryObject(filePath string) (AzureObject, error)

Reads a gob binary file and decodes it into an AzureObject.

func PreFetchAzureObject

func PreFetchAzureObject(t, identifier string, z *Config) (x AzureObject)

Retrieves existing object from Azure by its ID or displayName. This is typically used as preprocessing for operations like renaming, deleting, or updating a group.

func (AzureObject) HasString

func (obj AzureObject) HasString(filter string) bool

Checks if the filter string is found anywhere within the AzureObject. This method performs a recursive search.

func (AzureObject) TrimForCache

func (obj AzureObject) TrimForCache(t string) (trimmed AzureObject)

Trims the AzureObject to retain only the fields needed for caching based on the type code.

type AzureObjectList

type AzureObjectList []AzureObject // Represents a list of Azure JSON objects

func FilterObjects

func FilterObjects(data AzureObjectList, filter string) AzureObjectList

Filter objects by matching any field to filter string.

func GetMatchingObjects

func GetMatchingObjects(t, filter string, force bool, z *Config) AzureObjectList

Gets all objects of given type, matching on 'filter'. Returns the entire list if filter is empty "".

func GetObjectFromAzureByName

func GetObjectFromAzureByName(t, displayName string, z *Config) AzureObjectList

Fetches objects of the given type from Azure by displayName. It returns a list of matching objects, accounting for the possibility of multiple objects with the same displayName.

func LoadFileBinaryList

func LoadFileBinaryList(filePath string, compressed bool) (AzureObjectList, error)

Reads a gob binary file and decodes it into a slice of AzureObject. If the file is compressed, it decompresses it using Gzip before decoding.

func NewList

func NewList() AzureObjectList

Initializes a new list of objects.

func (*AzureObjectList) Add

func (list *AzureObjectList) Add(obj AzureObject)

Add appends an AzureObject to the AzureObjectList.

func (*AzureObjectList) Delete

func (list *AzureObjectList) Delete(criteria AzureObject) bool

Deletes an object from the list based on one or more field matches.

func (*AzureObjectList) DeleteById

func (list *AzureObjectList) DeleteById(targetId string) bool

Deletes an object from the list by matching on its ID.

func (*AzureObjectList) DeleteByName

func (list *AzureObjectList) DeleteByName(targetName string) bool

Deletes an object from the list by matching on its displayName.

func (AzureObjectList) Exists

func (list AzureObjectList) Exists(criteria AzureObject) bool

Checks if an object exists in the list based on one or more field matches.

func (AzureObjectList) ExistsById

func (list AzureObjectList) ExistsById(targetId string) bool

Checks if an object exists in the list by its ID.

func (AzureObjectList) ExistsByName

func (list AzureObjectList) ExistsByName(targetName string) bool

Checks if an object exists in the list by its displayName.

func (AzureObjectList) Find

func (list AzureObjectList) Find(criteria AzureObject) *AzureObject

Finds an object in the list based on one or more field matches and returns a pointer to it.

func (AzureObjectList) FindById

func (list AzureObjectList) FindById(targetId string) *AzureObject

Finds an object in the list by its ID and returns a pointer to it.

func (AzureObjectList) FindByName

func (list AzureObjectList) FindByName(targetName string) *AzureObject

Finds an object in the list by its displayName and returns a pointer to it.

func (*AzureObjectList) Replace

func (list *AzureObjectList) Replace(newObj AzureObject) bool

Replaces an object in an AzureObjectList list by matching on id.

type Bundle

type Bundle struct {
	ConfDir      string // Directory where utility will store all its file
	CredsFile    string
	TokenFile    string
	TenantId     string
	ClientId     string
	ClientSecret string
	Interactive  bool
	Username     string
	AuthorityUrl string
	MgToken      string // This and below to support MS Graph API
	MgHeaders    map[string]string
	AzToken      string // This and below to support Azure Resource Management API
	AzHeaders    map[string]string
}

Old configuration Bundle type. To be deprecated.

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache type

func GetCache

func GetCache(t string, z *Config) (*Cache, error)

Initializes a Cache instance for a given type. If the cache file exists, it loads the existing cache; otherwise, it creates a new one.

func (*Cache) Age

func (c *Cache) Age() int64

Age returns the age of the cache file in seconds. If the file does not exist or is empty, it returns -1.

func (*Cache) Count

func (c *Cache) Count() int64

Count returns the number of entries in the cache.

func (*Cache) Delete

func (c *Cache) Delete(id string) error

Removes an object by its ID from the cache and saves the updated cache to disk.

func (*Cache) Erase

func (c *Cache) Erase() error

Deletes both the cache file and the deltaLink file from the filesystem.

func (*Cache) Load

func (c *Cache) Load() error

Load cache from file

func (c *Cache) LoadDeltaLink() (AzureObject, error)

LoadDeltaLink loads the delta link from the file, if it exists and is valid.

func (*Cache) Normalize

func (c *Cache) Normalize(t string, deltaSet AzureObjectList)

Merges the deltaSet with the current cache data.

func (*Cache) Save

func (c *Cache) Save() error

Save cache to file

func (c *Cache) SaveDeltaLink(deltaLinkMap AzureObject) error

SaveDeltaLink saves the provided delta link to the file.

func (*Cache) Upsert

func (c *Cache) Upsert(obj AzureObject) error

type Config

type Config struct {
	ConfDir      string
	CredsFile    string
	TokenFile    string
	TenantId     string
	ClientId     string
	ClientSecret string
	Interactive  bool
	Username     string
	MgToken      string
	MgHeaders    map[string]string
	AzToken      string
	AzHeaders    map[string]string
}

Config holds configuration and credentials for various APIs and the calling programs themselves.

func NewConfig

func NewConfig() *Config

Constructs, initializes, and returns a pointer to a Config instance. The returned pointer can be used as a global configuration object to store credentials, tokens, and other API-related details for the application.

func (*Config) AddAzHeader

func (m *Config) AddAzHeader(key, value string) *Config

Adds an Azure Resource Management API header.

func (*Config) AddMgHeader

func (m *Config) AddMgHeader(key, value string) *Config

Adds a Microsoft Graph API header.

func (*Config) SetInteractiveMode

func (m *Config) SetInteractiveMode(interactive bool) *Config

Sets the interactive mode flag.

func (*Config) SetTenantCredentials

func (m *Config) SetTenantCredentials(tenantID, clientID, clientSecret string) *Config

Sets the credentials for the tenant.

func (*Config) SetUsername

func (m *Config) SetUsername(username string) *Config

Sets the username.

func (*Config) Validate

func (m *Config) Validate() error

Checks whether required fields are set and returns an error if not.

type Options

type Options struct {
	// contains filtered or unexported fields
}

Options map type to facilitate calling functions with many variables.

func NewOptions

func NewOptions() *Options

Constructor to initialize an options map

func (*Options) Count

func (a *Options) Count() int

Returns the number of entries in the set of options.

func (*Options) Get

func (a *Options) Get(key string) (interface{}, bool)

Gets a value of any type from the options map.

func (*Options) GetBool

func (a *Options) GetBool(key string) (bool, bool)

Gets boolean value in an options map.

func (*Options) GetInt

func (a *Options) GetInt(key string) (int, bool)

Gets integer value in an options map.

func (*Options) GetString

func (a *Options) GetString(key string) (string, bool)

Gets string value in an options map.

func (*Options) Set

func (a *Options) Set(key string, value interface{}) *Options

Sets values in an options map.

func (*Options) Validate

func (a *Options) Validate(requiredKeys []string) error

Validate required keys.

type TokenCache

type TokenCache struct {
	// contains filtered or unexported fields
}

func (*TokenCache) Export

func (t *TokenCache) Export(ctx context.Context, cache cache.Marshaler, hints cache.ExportHints) error

func (*TokenCache) Print

func (t *TokenCache) Print() string

func (*TokenCache) Replace

func (t *TokenCache) Replace(ctx context.Context, cache cache.Unmarshaler, hints cache.ReplaceHints) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL