msgraph

package module
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2023 License: MIT Imports: 15 Imported by: 5

README

Golang Microsoft Graph API implementation

Latest Release Github Actions godoc Go Report Card codebeat badge codecov MIT License

go-msgraph is an incomplete go lang implementation of the Microsoft Graph API. See Overview of Microsoft Graph

General

This implementation has been written to get various user, group and calendar details out of a Microsoft Azure Active Directory and create / update the same.

⚠ Deprecation warning

This code was created as part of a software project developed by Open Networks GmbH, Austria (the one in Europe 😉) in the year 2017. The company has been bought by Bechtle AG, Germany in 2021 and the software project is planned to be replaced by end of 2022. Furthermore, the employee mainly working on this project also left the company by April 2022 and may only contribute in his leisure time.

Back in the days, there was no official support from Microsoft for Go lang. This support has been added in 2021, see Issue #25.

Therefore, I strongly advise you to use the new official implementation from Microsoft at Golang MSGraph SDK by Microsoft.

Features

working & tested:

  • list users, groups, calendars, calendarevents
  • automatically grab & refresh token for API-access
  • json-load the GraphClient struct & initialize it
  • set timezone for full-day CalendarEvent
  • use $select, $search and $filter when querying data
  • context-aware API calls, can be cancelled.
  • loading huge data sets with paging, thanks to PR #20 - @Goorsky123

planned:

Example

To get your credentials to access the Microsoft Graph API visit: Register an application with Azure AD and create a service principal

More examples can be found at the docs. Here's a brief summary of some of the most common API-queries, ready to copy'n'paste:

// initialize GraphClient manually
graphClient, err := msgraph.NewGraphClient("<TenantID>", "<ApplicationID>", "<ClientSecret>")
if err != nil {
    fmt.Println("Credentials are probably wrong or system time is not synced: ", err)
}

// List all users
users, err := graphClient.ListUsers()
// Gets all the detailled information about a user identified by it's ID or userPrincipalName
user, err := graphClient.GetUser("humpty@contoso.com")
// List all groups
groups, err := graphClient.ListGroups()
// List all members of a group.
groupMembers, err := groups[0].ListMembers()
// Lists all Calendars of a user
calendars, err := user.ListCalendars()

// Let all full-day calendar events that are loaded from ms graph be set to timezone Europe/Vienna:
// Standard is time.Local
msgraph.FullDayEventTimeZone, _ = time.LoadLocation("Europe/Vienna")

// Lists all CalendarEvents of the given userPrincipalName/ID that starts/ends within the the next 7 days
startTime := time.Now()
endTime := time.Now().Add(time.Hour * 24 * 7)
events, err := graphClient.ListCalendarView("alice@contoso.com", startTime, endTime)

Versioning & backwards compatibility

This project uses Semantic versioning with all tags prefixed with a v. Altough currently the case, I cannot promise to really keep everything backwards compatible for the 0.x version. If a 1.x version of this repository is ever released with enough API-calls implemented, I will keep this promise for sure. Any Breaking changes will be marked as such in the release notes of each release.

Installation

I recommend to use go modules and always use the latest tagged release. You may directly download the source code there, but the preffered way to install and update is with go get:

# Initially install
go get github.com/open-networks/go-msgraph
# Update
go get -u github.com/open-networks/go-msgraph
go mod tidy

Documentation

There is some example code placed in the docs/ folder. The code itself is pretty well documented with comments, hence see http://godoc.org/github.com/open-networks/go-msgraph or run:

godoc github.com/open-networks/go-msgraph

License

MIT

Documentation

Overview

Package msgraph is a go lang implementation of the Microsoft Graph API

See: https://developer.microsoft.com/en-us/graph/docs/concepts/overview

Index

Constants

View Source
const (

	// Azure AD authentication endpoint "Global". Used to aquire a token for the ms graph API connection.
	//
	// Microsoft Documentation: https://docs.microsoft.com/en-us/azure/active-directory/develop/authentication-national-cloud#azure-ad-authentication-endpoints
	AzureADAuthEndpointGlobal string = "https://login.microsoftonline.com"

	// Azure AD authentication endpoint "Germany". Used to aquire a token for the ms graph API connection.
	//
	// Microsoft Documentation: https://docs.microsoft.com/en-us/azure/active-directory/develop/authentication-national-cloud#azure-ad-authentication-endpoints
	AzureADAuthEndpointGermany string = "https://login.microsoftonline.de"

	// Azure AD authentication endpoint "US Government". Used to aquire a token for the ms graph API connection.
	//
	// Microsoft Documentation: https://docs.microsoft.com/en-us/azure/active-directory/develop/authentication-national-cloud#azure-ad-authentication-endpoints
	AzureADAuthEndpointUSGov string = "https://login.microsoftonline.us"

	// Azure AD authentication endpoint "China by 21 Vianet". Used to aquire a token for the ms graph API connection.
	//
	// Microsoft Documentation: https://docs.microsoft.com/en-us/azure/active-directory/develop/authentication-national-cloud#azure-ad-authentication-endpoints
	AzureADAuthEndpointChina string = "https://login.partner.microsoftonline.cn"

	// ServiceRootEndpointGlobal represents the default Service Root Endpoint used to perform all ms graph
	// API-calls, hence the Service Root Endpoint.
	//
	// See https://docs.microsoft.com/en-us/azure/active-directory/develop/authentication-national-cloud#azure-ad-authentication-endpoints
	ServiceRootEndpointGlobal string = "https://graph.microsoft.com"

	// Service Root Endpoint "US Government L4".
	//
	// See https://docs.microsoft.com/en-us/graph/deployments#microsoft-graph-and-graph-explorer-service-root-endpoints
	ServiceRootEndpointUSGovL4 string = "https://graph.microsoft.us"

	// Service Root Endpoint "US Government L5 (DOD)".
	//
	// See https://docs.microsoft.com/en-us/graph/deployments#microsoft-graph-and-graph-explorer-service-root-endpoints
	ServiceRootEndpointUSGovL5 string = "https://dod-graph.microsoft.us"

	// Service Root Endpoint "Germany".
	//
	// See https://docs.microsoft.com/en-us/graph/deployments#microsoft-graph-and-graph-explorer-service-root-endpoints
	ServiceRootEndpointGermany string = "https://graph.microsoft.de"

	// Service Root Endpoint "China operated by 21Vianet".
	//
	// See https://docs.microsoft.com/en-us/graph/deployments#microsoft-graph-and-graph-explorer-service-root-endpoints
	ServiceRootEndpointChina string = "https://microsoftgraph.chinacloudapi.cn"
)
View Source
const APIVersion string = "v1.0"

APIVersion represents the APIVersion of msgraph used by this implementation

View Source
const MaxPageSize int = 999

MaxPageSize is the maximum Page size for an API-call. This will be rewritten to use paging some day. Currently limits environments to 999 entries (e.g. Users, CalendarEvents etc.)

Variables

View Source
var (
	// GetWithContext - add a context.Context to the HTTP request e.g. to allow cancellation
	GetWithContext = func(ctx context.Context) GetQueryOption {
		return func(opts *getQueryOptions) {
			opts.ctx = ctx
		}
	}

	// GetWithSelect - $select - Filters properties (columns) - https://docs.microsoft.com/en-us/graph/query-parameters#select-parameter
	GetWithSelect = func(selectParam string) GetQueryOption {
		return func(opts *getQueryOptions) {
			opts.queryValues.Add(odataSelectParamKey, selectParam)
		}
	}

	// ListWithContext - add a context.Context to the HTTP request e.g. to allow cancellation
	ListWithContext = func(ctx context.Context) ListQueryOption {
		return func(opts *listQueryOptions) {
			opts.ctx = ctx
		}
	}

	// ListWithSelect - $select - Filters properties (columns) - https://docs.microsoft.com/en-us/graph/query-parameters#select-parameter
	ListWithSelect = func(selectParam string) ListQueryOption {
		return func(opts *listQueryOptions) {
			opts.queryValues.Add(odataSelectParamKey, selectParam)
		}
	}

	// ListWithFilter - $filter - Filters results (rows) - https://docs.microsoft.com/en-us/graph/query-parameters#filter-parameter
	ListWithFilter = func(filterParam string) ListQueryOption {
		return func(opts *listQueryOptions) {
			opts.queryValues.Add(odataFilterParamKey, filterParam)
		}
	}

	// ListWithSearch - $search - Returns results based on search criteria - https://docs.microsoft.com/en-us/graph/query-parameters#search-parameter
	ListWithSearch = func(searchParam string) ListQueryOption {
		return func(opts *listQueryOptions) {
			opts.queryHeaders.Add("ConsistencyLevel", "eventual")
			opts.queryValues.Add(odataSearchParamKey, searchParam)
		}
	}

	// CreateWithContext - add a context.Context to the HTTP request e.g. to allow cancellation
	CreateWithContext = func(ctx context.Context) CreateQueryOption {
		return func(opts *createQueryOptions) {
			opts.ctx = ctx
		}
	}

	// UpdateWithContext - add a context.Context to the HTTP request e.g. to allow cancellation
	UpdateWithContext = func(ctx context.Context) UpdateQueryOption {
		return func(opts *updateQueryOptions) {
			opts.ctx = ctx
		}
	}
	// DeleteWithContext - add a context.Context to the HTTP request e.g. to allow cancellation
	DeleteWithContext = func(ctx context.Context) DeleteQueryOption {
		return func(opts *deleteQueryOptions) {
			opts.ctx = ctx
		}
	}
)
View Source
var (
	// ErrFindUser is returned on any func that tries to find a user with the given parameters that cannot be found
	ErrFindUser = errors.New("unable to find user")
	// ErrFindGroup is returned on any func that tries to find a group with the given parameters that cannot be found
	ErrFindGroup = errors.New("unable to find group")
	// ErrFindCalendar is returned on any func that tries to find a calendar with the given parameters that cannot be found
	ErrFindCalendar = errors.New("unable to find calendar")
	// ErrNotGraphClientSourced is returned if e.g. a ListMembers() is called but the Group has not been created by a graphClient query
	ErrNotGraphClientSourced = errors.New("instance is not created from a GraphClient API-Call, cannot directly get further information")
)
View Source
var FullDayEventTimeZone = time.Local

FullDayEventTimeZone is used by CalendarEvent.UnmarshalJSON to set the timezone for full day events.

That method json-unmarshal automatically sets the Begin/End Date to 00:00 with the correnct days then. This has to be done because Microsoft always sets the timezone to UTC for full day events. To work with that within your program is probably a bad idea, hence configure this as you need or probably even back to time.UTC

View Source
var WinIANA = map[string]string{}/* 159 elements not displayed */

WinIANA contains a mapping for all Windows Time Zones to IANA time zones usable for time.LoadLocation. This list was initially copied from https://github.com/thinkovation/windowsiana/blob/master/windowsiana.go on 30th of August 2018, 14:00 and then extended on the same day.

The full list of time zones that have been added and are now supported come from an an API-Call described here: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/outlookuser_supportedtimezones

Functions

This section is empty.

Types

type Alert

type Alert struct {
	ActivityGroupName    string                    `json:"activityGroupName"`
	AssignedTo           string                    `json:"assignedTo"`
	AzureSubscriptionID  string                    `json:"azureSubscriptionId"`
	AzureTenantID        string                    `json:"azureTenantId"`
	Category             string                    `json:"category"`
	ClosedDateTime       time.Time                 `json:"closedDateTime"`
	CloudAppStates       []CloudAppSecurityState   `json:"cloudAppStates"`
	Comments             []string                  `json:"comments"`
	Confidence           int32                     `json:"confidence"`
	CreatedDateTime      time.Time                 `json:"createdDateTime"`
	Description          string                    `json:"description"`
	DetectionIDs         []string                  `json:"detectionIds"`
	EventDateTime        time.Time                 `json:"eventDateTime"`
	Feedback             string                    `json:"feedback"`
	FileStates           []FileSecurityState       `json:"fileStates"`
	HostStates           []HostSecurityState       `json:"hostStates"`
	ID                   string                    `json:"id"`
	IncidentIDs          []string                  `json:"incidentIds"`
	LastModifiedDateTime time.Time                 `json:"lastModifiedDateTime"`
	MalwareStates        []MalwareState            `json:"malwareStates"`
	NetworkConnections   []NetworkConnection       `json:"networkConnections"`
	Processes            []Process                 `json:"processes"`
	RecommendedActions   []string                  `json:"recommendedActions"`
	RegistryKeyStates    []RegistryKeyState        `json:"registryKeyStates"`
	SecurityResources    []SecurityResource        `json:"securityResources"`
	Severity             string                    `json:"severity"`
	SourceMaterials      []string                  `json:"sourceMaterials"`
	Status               string                    `json:"status"`
	Tags                 []string                  `json:"tags"`
	Title                string                    `json:"title"`
	Triggers             []AlertTrigger            `json:"triggers"`
	UserStates           []UserSecurityState       `json:"userStates"`
	VendorInformation    SecurityVendorInformation `json:"vendorInformation"`
	VulnerabilityStates  []VulnerabilityState      `json:"vulnerabilityStates"`
}

Alert represents a security alert.

type AlertTrigger

type AlertTrigger struct {
	Name  string `json:"name"`
	Type  string `json:"type"`
	Value string `json:"value"`
}

AlertTrigger contains information about a property which triggered an alert detection.

type AssignedLicense added in v0.2.0

type AssignedLicense struct {
	DisabledPlans []string `json:"disabledPlans,omitempty"`
	SkuID         string   `json:"skuId,omitempty"`
}

type Attendee

type Attendee struct {
	Type           string         // the type of the invitation, e.g. required, optional etc.
	Name           string         // the name of the person, comes from the E-Mail Address - hence not a reliable name to search for
	Email          string         // the e-mail address of the person - use this to identify the user
	ResponseStatus ResponseStatus // the ResponseStatus for that particular Attendee for the CalendarEvent
}

Attendee struct represents an attendee for a CalendarEvent

func (Attendee) Equal

func (a Attendee) Equal(other Attendee) bool

Equal compares the Attendee to the other Attendee and returns true if the two given Attendees are equal. Otherwise returns false

func (Attendee) String

func (a Attendee) String() string

func (*Attendee) UnmarshalJSON

func (a *Attendee) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type Attendees

type Attendees []Attendee

Attendees struct represents multiple Attendees for a CalendarEvent

func (Attendees) Equal

func (a Attendees) Equal(other Attendees) bool

Equal compares the Attendee to the other Attendee and returns true if the two given Attendees are equal. Otherwise returns false

func (Attendees) String

func (a Attendees) String() string

type AverageComparativeScore

type AverageComparativeScore struct {
	Basis        string  `json:"basis"`
	AverageScore float64 `json:"averageScore"`
}

AverageComparativeScore describes average scores across a variety of different scopes. The Basis field may contain the strings "AllTenants", "TotalSeats", or "IndustryTypes".

type Calendar

type Calendar struct {
	ID                  string // The group's unique identifier. Read-only.
	Name                string // The calendar name.
	CanEdit             bool   // True if the user can write to the calendar, false otherwise. This property is true for the user who created the calendar. This property is also true for a user who has been shared a calendar and granted write access.
	CanShare            bool   // True if the user has the permission to share the calendar, false otherwise. Only the user who created the calendar can share it.
	CanViewPrivateItems bool   // True if the user can read calendar items that have been marked private, false otherwise.
	ChangeKey           string // Identifies the version of the calendar object. Every time the calendar is changed, changeKey changes as well. This allows Exchange to apply changes to the correct version of the object. Read-only.

	Owner EmailAddress // If set, this represents the user who created or added the calendar. For a calendar that the user created or added, the owner property is set to the user. For a calendar shared with the user, the owner property is set to the person who shared that calendar with the user.
	// contains filtered or unexported fields
}

Calendar represents a single calendar of a user

See https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/calendar

func (Calendar) String

func (c Calendar) String() string

func (*Calendar) UnmarshalJSON

func (c *Calendar) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type CalendarEvent

type CalendarEvent struct {
	ID                    string
	CreatedDateTime       time.Time      // Creation time of the CalendarEvent, has the correct timezone set from OriginalStartTimeZone (json)
	LastModifiedDateTime  time.Time      // Last modified time of the CalendarEvent, has the correct timezone set from OriginalEndTimeZone (json)
	OriginalStartTimeZone *time.Location // The original start-timezone, is already integrated in the calendartimes. Caution: is UTC on full day events
	OriginalEndTimeZone   *time.Location // The original end-timezone, is already integrated in the calendartimes. Caution: is UTC on full day events
	ICalUID               string
	Subject               string
	Importance            string
	Sensitivity           string
	IsAllDay              bool   // true = full day event, otherwise false
	IsCancelled           bool   // calendar event has been cancelled but is still in the calendar
	IsOrganizer           bool   // true if the calendar owner is the organizer
	SeriesMasterID        string // the ID of the master-entry of this series-event if any
	ShowAs                string
	Type                  string
	ResponseStatus        ResponseStatus // how the calendar-owner responded to the event (normally "organizer" because support-calendar is the host)
	StartTime             time.Time      // starttime of the Event, correct timezone is set
	EndTime               time.Time      // endtime of the event, correct timezone is set

	Attendees      Attendees // represents all attendees to this CalendarEvent
	OrganizerName  string    // the name of the organizer from the e-mail, not reliable to identify anyone
	OrganizerEMail string    // the e-mail address of the organizer, use this to identify the user
}

CalendarEvent represents a single event within a calendar

func (CalendarEvent) Equal

func (c CalendarEvent) Equal(other CalendarEvent) bool

Equal returns wether the CalendarEvent is identical to the given CalendarEvent

func (CalendarEvent) GetFirstAttendee

func (c CalendarEvent) GetFirstAttendee() Attendee

GetFirstAttendee returns the first Attendee that is not the organizer of the event from the Attendees array. If none is found then an Attendee with the Name of "None" will be returned.

func (CalendarEvent) PrettySimpleString

func (c CalendarEvent) PrettySimpleString() string

PrettySimpleString returns all Calendar Events in a readable format, mostly used for logging purposes

func (CalendarEvent) String

func (c CalendarEvent) String() string

func (*CalendarEvent) UnmarshalJSON

func (c *CalendarEvent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type CalendarEvents

type CalendarEvents []CalendarEvent

CalendarEvents represents multiple events of a Calendar. The amount of entries is determined by the timespan that is used to load the Calendar

func (CalendarEvents) Equal

func (c CalendarEvents) Equal(others CalendarEvents) bool

Equal returns true if the two CalendarEvent[] are equal. The order of the events doesn't matter

func (CalendarEvents) GetCalendarEventsAtCertainTime

func (c CalendarEvents) GetCalendarEventsAtCertainTime(givenTime time.Time) CalendarEvents

GetCalendarEventsAtCertainTime returns a subset of CalendarEvents that either start or end at the givenTime or whose StartTime is before and EndTime is After the givenTime

func (CalendarEvents) PrettySimpleString

func (c CalendarEvents) PrettySimpleString() string

PrettySimpleString returns all Calendar Events in a readable format, mostly used for logging purposes

func (CalendarEvents) SortByStartDateTime

func (c CalendarEvents) SortByStartDateTime()

SortByStartDateTime sorts the array in this CalendarEvents instance

func (CalendarEvents) String

func (c CalendarEvents) String() string

func (*CalendarEvents) UnmarshalJSON

func (c *CalendarEvents) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library. The only purpose of this overwrite is to immediately sort the []CalendarEvent by StartDateTime

type Calendars

type Calendars []Calendar

Calendars represents an array of Calendar instances combined with some helper-functions

See: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/calendar

func (Calendars) GetByName

func (c Calendars) GetByName(name string) (Calendar, error)

GetByName returns the calendar obj of that array whose DisplayName matches the given name. Returns an ErrFindCalendar if no calendar exists that matches the given name.

func (Calendars) String

func (c Calendars) String() string

type CertificationControl

type CertificationControl struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

CertificationControl contains compliance certification data associated with a secure score control.

type CloudAppSecurityState

type CloudAppSecurityState struct {
	DestinationServiceIP   net.IP `json:"destinationServiceIp"`
	DestinationServiceName string `json:"destinationServiceName"`
	RiskScore              string `json:"riskScore"`
}

CloudAppSecurityState contains stateful information about a cloud application related to an alert.

type ComplianceInformation

type ComplianceInformation struct {
	CertificationName     string                 `json:"certificationName"`
	CertificationControls []CertificationControl `json:"certificationControls"`
}

ComplianceInformation contains compliance data associated with a secure score control.

type ControlScore

type ControlScore struct {
	ControlName     string  `json:"controlName"`
	Score           float64 `json:"score"`
	ControlCategory string  `json:"controlCategory"`
	Description     string  `json:"description"`
}

ControlScore contains a score for a single security control.

type CreateQueryOption added in v0.2.0

type CreateQueryOption func(opts *createQueryOptions)

type DeleteQueryOption added in v0.2.0

type DeleteQueryOption func(opts *deleteQueryOptions)

type EmailAddress

type EmailAddress struct {
	Address string `json:"address"` // The email address of the person or entity.
	Name    string `json:"name"`    // The display name of the person or entity.
	// contains filtered or unexported fields
}

EmailAddress represents an emailAddress instance as microsoft.graph.EmailAddress. This is used at various positions, for example in CalendarEvents for attenees, owners, organizers or in Calendar for the owner.

Short: The name and email address of a contact or message recipient.

See https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/emailaddress

func (EmailAddress) GetUser

func (e EmailAddress) GetUser() (User, error)

GetUser tries to get the real User-Instance directly from msgraph identified by the e-mail address of the user. This should normally be the userPrincipalName anyways. Returns an error if any from GraphClient.

func (EmailAddress) String

func (e EmailAddress) String() string

type FileHash

type FileHash struct {
	HashType  string `json:"hashType"`
	HashValue string `json:"hashValue"`
}

FileHash contains hash information related to a file.

type FileSecurityState

type FileSecurityState struct {
	FileHash  FileHash `json:"fileHash"`
	Name      string   `json:"name"`
	Path      string   `json:"path"`
	RiskScore string   `json:"riskScore"`
}

FileSecurityState contains information about a file (not process) related to an alert.

type GetQueryOption

type GetQueryOption func(opts *getQueryOptions)

type GraphClient

GraphClient represents a msgraph API connection instance.

An instance can also be json-unmarshalled and will immediately be initialized, hence a Token will be grabbed. If grabbing a token fails the JSON-Unmarshal returns an error.

func NewGraphClient

func NewGraphClient(tenantID, applicationID, clientSecret string) (*GraphClient, error)

NewGraphClient creates a new GraphClient instance with the given parameters and grabs a token. Returns an error if the token cannot be initialized. The default ms graph API global endpoint is used.

This method does not have to be used to create a new GraphClient. If not used, the default global ms Graph API endpoint is used.

func NewGraphClientWithCustomEndpoint added in v0.2.0

func NewGraphClientWithCustomEndpoint(tenantID, applicationID, clientSecret string, azureADAuthEndpoint string, serviceRootEndpoint string) (*GraphClient, error)

NewGraphClientCustomEndpoint creates a new GraphClient instance with the given parameters and tries to get a valid token. All available public endpoints for azureADAuthEndpoint and serviceRootEndpoint are available via msgraph.azureADAuthEndpoint* and msgraph.ServiceRootEndpoint*

For available endpoints from Microsoft, see documentation:

Returns an error if the token cannot be initialized. This func does not have to be used to create a new GraphClient.

func (*GraphClient) CreateUser added in v0.2.0

func (g *GraphClient) CreateUser(userInput User, opts ...CreateQueryOption) (User, error)

CreateUser creates a new user given a user object and returns and updated object Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user-post-users

func (*GraphClient) GetGroup

func (g *GraphClient) GetGroup(groupID string, opts ...GetQueryOption) (Group, error)

GetGroup returns the group object identified by the given groupID. Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/group_get

func (*GraphClient) GetToken added in v0.3.0

func (g *GraphClient) GetToken() Token

GetToken returns a copy the currently token used by this GraphClient instance.

func (*GraphClient) GetUser

func (g *GraphClient) GetUser(identifier string, opts ...GetQueryOption) (User, error)

GetUser returns the user object associated to the given user identified by either the given ID or userPrincipalName Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_get

func (*GraphClient) ListAlerts

func (g *GraphClient) ListAlerts(opts ...ListQueryOption) ([]Alert, error)

ListAlerts returns a slice of Alert objects from MS Graph's security API. Each Alert represents a security event reported by some component. Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

func (*GraphClient) ListGroups

func (g *GraphClient) ListGroups(opts ...ListQueryOption) (Groups, error)

ListGroups returns a list of all groups Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/group_list

func (*GraphClient) ListSecureScoreControlProfiles

func (g *GraphClient) ListSecureScoreControlProfiles(opts ...ListQueryOption) ([]SecureScoreControlProfile, error)

ListSecureScoreControlProfiles returns a slice of SecureScoreControlProfile objects. Each object represents a secure score control profile, which is used when calculating a tenant's secure score. Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

func (*GraphClient) ListSecureScores

func (g *GraphClient) ListSecureScores(opts ...ListQueryOption) ([]SecureScore, error)

ListSecureScores returns a slice of SecureScore objects. Each SecureScore represents Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters a tenant's security score for a particular day.

func (*GraphClient) ListUsers

func (g *GraphClient) ListUsers(opts ...ListQueryOption) (Users, error)

ListUsers returns a list of all users Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list

func (*GraphClient) String

func (g *GraphClient) String() string

func (*GraphClient) UnmarshalJSON

func (g *GraphClient) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library. This method additionally to loading the TenantID, ApplicationID and ClientSecret immediately gets a Token from msgraph (hence initialize this GraphAPI instance) and returns an error if any of the data provided is incorrect or the token cannot be acquired

type Group

type Group struct {
	ID                           string
	Description                  string
	DisplayName                  string
	CreatedDateTime              time.Time
	GroupTypes                   []string
	Mail                         string
	MailEnabled                  bool
	MailNickname                 string
	OnPremisesLastSyncDateTime   time.Time // defaults to 0001-01-01 00:00:00 +0000 UTC if there's none
	OnPremisesSecurityIdentifier string
	OnPremisesSyncEnabled        bool
	ProxyAddresses               []string
	SecurityEnabled              bool
	Visibility                   string
	// contains filtered or unexported fields
}

Group represents one group of ms graph

See: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/group_get

func (Group) GetMemberGroupsAsStrings added in v0.3.0

func (g Group) GetMemberGroupsAsStrings(opts ...GetQueryOption) ([]string, error)

GetMemberGroupsAsStrings returns a list of all group IDs the user is a member of.

opts ...GetQueryOption - only msgraph.GetWithContext is supported.

Reference: https://docs.microsoft.com/en-us/graph/api/directoryobject-getmembergroups?view=graph-rest-1.0&tabs=http

func (Group) ListMembers

func (g Group) ListMembers(opts ...ListQueryOption) (Users, error)

ListMembers - Get a list of the group's direct members. A group can have users, contacts, and other groups as members. This operation is not transitive. This method will currently ONLY return User-instances of members Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

See https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/group_list_members

func (Group) ListTransitiveMembers added in v0.3.0

func (g Group) ListTransitiveMembers(opts ...ListQueryOption) (Users, error)

Get a list of the group's members. A group can have users, devices, organizational contacts, and other groups as members. This operation is transitive and returns a flat list of all nested members. This method will currently ONLY return User-instances of members Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

See https://docs.microsoft.com/en-us/graph/api/group-list-transitivemembers?view=graph-rest-1.0&tabs=http

func (Group) String

func (g Group) String() string

func (*Group) UnmarshalJSON

func (g *Group) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type Groups

type Groups []Group

Groups represents multiple Group-instances and provides funcs to work with them.

func (Groups) GetByDisplayName

func (g Groups) GetByDisplayName(displayName string) (Group, error)

GetByDisplayName returns the Group obj of that array whose DisplayName matches the given name. Returns an ErrFindGroup if no group exists that matches the given DisplayName.

func (Groups) String

func (g Groups) String() string

type HostSecurityState

type HostSecurityState struct {
	FQDN                      string `json:"fqdn"`
	IsAzureAADJoined          bool   `json:"isAzureAadJoined"`
	IsAzurAADRegistered       bool   `json:"isAzureAadRegistered"`
	IsHybridAzureDomainJoined bool   `json:"isHybridAzureDomainJoined"`
	NetBiosName               string `json:"netBiosName"`
	OS                        string `json:"os"`
	PrivateIPAddress          net.IP `json:"privateIpAddress"`
	PublicIPAddress           net.IP `json:"publicIpAddress"`
	RiskScore                 string `json:"riskScore"`
}

HostSecurityState contains information about a host (computer, device, etc.) related to an alert.

type ListQueryOption

type ListQueryOption func(opts *listQueryOptions)

type MalwareState

type MalwareState struct {
	Category   string `json:"category"`
	Family     string `json:"family"`
	Name       string `json:"name"`
	Severity   string `json:"severity"`
	WasRunning bool   `json:"wasRunning"`
}

MalwareState contains information about a malware entity.

type NetworkConnection

type NetworkConnection struct {
	ApplicationName          string    `json:"applicationName"`
	DestinationAddress       net.IP    `json:"destinationAddress"`
	DestinationLocation      string    `json:"destinationLocation"`
	DestinationDomain        string    `json:"destinationDomain"`
	DestinationPort          string    `json:"destinationPort"` // spec calls it a string, not a number
	DestinationURL           string    `json:"destinationUrl"`
	Direction                string    `json:"direction"`
	DomainRegisteredDateTime time.Time `json:"domainRegisteredDateTime"`
	LocalDNSName             string    `json:"localDnsName"`
	NATDestinationAddress    net.IP    `json:"natDestinationAddress"`
	NATDestinationPort       string    `json:"natDestinationPort"`
	NATSourceAddress         net.IP    `json:"natSourceAddress"`
	NATSourcePort            string    `json:"natSourcePort"`
	Protocol                 string    `json:"protocol"`
	RiskScore                string    `json:"riskScore"`
	SourceAddress            net.IP    `json:"sourceAddress"`
	SourceLocation           string    `json:"sourceLocation"`
	SourcePort               string    `json:"sourcePort"`
	Status                   string    `json:"status"`
	URLParameters            string    `json:"urlParameters"`
}

NetworkConnection contains stateful information describing a network connection related to an alert.

type PasswordProfile added in v0.2.0

type PasswordProfile struct {
	ForceChangePasswordNextSignIn        bool   `json:"forceChangePasswordNextSignIn,omitempty"`
	ForceChangePasswordNextSignInWithMfa bool   `json:"forceChangePasswordNextSignInWithMfa,omitempty"`
	Password                             string `json:"password,omitempty"`
}

type Process

type Process struct {
	AccountName                  string    `json:"accountName"`
	CommandLine                  string    `json:"commandLine"`
	CreatedDateTime              time.Time `json:"createdDateTime"` // translated
	FileHash                     FileHash  `json:"fileHash"`
	IntegrityLevel               string    `json:"integrityLevel"`
	IsElevated                   bool      `json:"isElevated"`
	Name                         string    `json:"name"`
	ParentProcessCreatedDateTime time.Time `json:"parentProcessCreatedDateTime"` // translated
	ParentProcessID              int32     `json:"parentProcessId"`
	ParentProcessName            string    `json:"parentProcessName"`
	Path                         string    `json:"path"`
	ProcessID                    int32     `json:"processId"`
}

Process describes a process related to an alert.

type RegistryKeyState

type RegistryKeyState struct {
	Hive         string `json:"hive"`
	Key          string `json:"key"`
	OldKey       string `json:"oldKey"`
	OldValueData string `json:"oldValueData"`
	OldValueName string `json:"oldValueName"`
	Operation    string `json:"operation"`
	ProcessID    int32  `json:"processId"`
	ValueData    string `json:"valueData"`
	ValueName    string `json:"valueName"`
	ValueType    string `json:"valueType"`
}

RegistryKeyState contains information about registry key changes related to an alert, and about the process which changed the keys.

type ResponseStatus

type ResponseStatus struct {
	Response string    // status of the response, may be organizer, accepted, declined etc.
	Time     time.Time // represents the time when the response was performed
}

ResponseStatus represents the response status for an Attendee to a CalendarEvent or just for a CalendarEvent

func (ResponseStatus) Equal

func (s ResponseStatus) Equal(other ResponseStatus) bool

Equal compares the ResponseStatus to the other Response status and returns true if the Response and time is equal

func (ResponseStatus) String

func (s ResponseStatus) String() string

func (*ResponseStatus) UnmarshalJSON

func (s *ResponseStatus) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type SecureScore

type SecureScore struct {
	ID                       string                    `json:"id"`
	AzureTenantID            string                    `json:"azureTenantId"`
	ActiveUserCount          int32                     `json:"activeUserCount"`
	CreatedDateTime          time.Time                 `json:"createdDateTime"`
	CurrentScore             float64                   `json:"currentScore"`
	EnabledServices          []string                  `json:"enabledServices"`
	LicensedUserCount        int32                     `json:"licensedUserCount"`
	MaxScore                 float64                   `json:"maxScore"`
	AverageComparativeScores []AverageComparativeScore `json:"averageComparativeScores"`
	ControlScores            []ControlScore            `json:"controlScores"`
	VendorInformation        SecurityVendorInformation `json:"vendorInformation"`
}

SecureScore represents the security score of a tenant for a particular day.

type SecureScoreControlProfile

type SecureScoreControlProfile struct {
	ID                    string                          `json:"id"`
	AzureTenantID         string                          `json:"azureTenantId"`
	ActionType            string                          `json:"actionType"`
	ActionURL             string                          `json:"actionUrl"`
	ControlCategory       string                          `json:"controlCategory"`
	Title                 string                          `json:"title"`
	Deprecated            bool                            `json:"deprecated"`
	ImplementationCost    string                          `json:"implementationCost"`
	LastModifiedDateTime  time.Time                       `json:"lastModifiedDateTime"`
	MaxScore              float64                         `json:"maxScore"`
	Rank                  int32                           `json:"rank"`
	Remediation           string                          `json:"remediation"`
	RemediationImpact     string                          `json:"remediationImpact"`
	Service               string                          `json:"service"`
	Threats               []string                        `json:"threats"`
	Tier                  string                          `json:"tier"`
	UserImpact            string                          `json:"userImpact"`
	ComplianceInformation []ComplianceInformation         `json:"complianceInformation"`
	ControlStateUpdates   []SecureScoreControlStateUpdate `json:"controlStateUpdates"`
	VendorInformation     SecurityVendorInformation       `json:"vendorInformation"`
}

SecureScoreControlProfile describes in greater detail the parameters of a given security score control.

type SecureScoreControlStateUpdate

type SecureScoreControlStateUpdate struct {
	AssignedTo      string    `json:"assignedTo"`
	Comment         string    `json:"comment"`
	State           string    `json:"state"`
	UpdatedBy       string    `json:"updatedBy"`
	UpdatedDateTime time.Time `json:"updatedDateTime"`
}

SecureScoreControlStateUpdate records a particular historical state of the control state as updated by the user.

type SecurityResource

type SecurityResource struct {
	Resource     string `json:"resource"`
	ResourceType string `json:"resourceType"`
}

SecurityResource represents resources related to an alert.

type SecurityVendorInformation

type SecurityVendorInformation struct {
	Provider        string `json:"provider"`
	ProviderVersion string `json:"providerVersion"`
	SubProvider     string `json:"subProvider"`
	Vendor          string `json:"vendor"`
}

SecurityVendorInformation contains details about the vendor of a particular security product.

type Token

type Token struct {
	TokenType   string    // should always be "Bearer" for msgraph API-calls
	NotBefore   time.Time // time when the access token starts to be valid
	ExpiresOn   time.Time // time when the access token expires
	Resource    string    // will most likely be https://graph.microsoft.*, hence the Service Root Endpoint
	AccessToken string    // the access-token itself
}

Token struct holds the Microsoft Graph API authentication token used by GraphClient to authenticate API-requests to the ms graph API

func (Token) GetAccessToken

func (t Token) GetAccessToken() string

GetAccessToken teturns the API access token in Bearer format representation ready to send to the API interface.

func (Token) HasExpired

func (t Token) HasExpired() bool

HasExpired returns true if the token has already expired.

Hint: this is a wrapper for >>!token.IsStillValid()<<

func (Token) IsAlreadyValid

func (t Token) IsAlreadyValid() bool

IsAlreadyValid returns true if the token is already valid, hence the NotBefore is before the current time. Otherwise false.

Hint: The current time is determined by time.Now()

func (Token) IsStillValid

func (t Token) IsStillValid() bool

IsStillValid returns true if the token is still valid, hence the current time is before ExpiresOn. Does NOT check it the token is yet valid or in the future.

Hint: The current time is determined by time.Now()

func (Token) IsValid

func (t Token) IsValid() bool

IsValid returns true if the token is already valid and is still valid. Otherwise false.

Hint: this is a wrapper for >>token.IsAlreadyValid() && token.IsStillValid()<<

func (Token) String

func (t Token) String() string

func (*Token) UnmarshalJSON

func (t *Token) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library.

Hint: the UnmarshalJSON also checks immediately if the token is valid, hence the current time.Now() is after NotBefore and before ExpiresOn

func (Token) WantsToBeRefreshed

func (t Token) WantsToBeRefreshed() bool

WantsToBeRefreshed returns true if the token is already invalid or close to expire (10 second before ExpiresOn), otherwise false. time.Now() is used to determine the current time.

type UpdateQueryOption added in v0.2.0

type UpdateQueryOption func(opts *updateQueryOptions)

type User

type User struct {
	ID                string            `json:"id,omitempty"`
	BusinessPhones    []string          `json:"businessPhones,omitempty"`
	DisplayName       string            `json:"displayName,omitempty"`
	GivenName         string            `json:"givenName,omitempty"`
	JobTitle          string            `json:"jobTitle,omitempty"`
	Mail              string            `json:"mail,omitempty"`
	MobilePhone       string            `json:"mobilePhone,omitempty"`
	PreferredLanguage string            `json:"preferredLanguage,omitempty"`
	Surname           string            `json:"surname,omitempty"`
	UserPrincipalName string            `json:"userPrincipalName,omitempty"`
	AccountEnabled    bool              `json:"accountEnabled,omitempty"`
	AssignedLicenses  []AssignedLicense `json:"assignedLicenses,omitempty"`
	CompanyName       string            `json:"companyName,omitempty"`
	Department        string            `json:"department,omitempty"`
	MailNickname      string            `json:"mailNickname,omitempty"`
	PasswordProfile   PasswordProfile   `json:"passwordProfile,omitempty"`
	// contains filtered or unexported fields
}

User represents a user from the ms graph API

func (User) DeleteUser added in v0.2.0

func (u User) DeleteUser(opts ...DeleteQueryOption) error

DeleteUser deletes this user instance at the Microsoft Azure AD. Use with caution.

Reference: https://docs.microsoft.com/en-us/graph/api/user-delete

func (User) DisableAccount added in v0.2.0

func (u User) DisableAccount(opts ...UpdateQueryOption) error

DisableAccount disables the User-Account, hence sets the AccountEnabled-field to false. This function must be used instead of user.UpdateUser, because the AccountEnabled-field with json "omitempty" will never be sent when false. Without omitempty, the user account would always accidentially disabled upon an update of e.g. only "DisplayName"

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user-update

func (User) Equal

func (u User) Equal(other User) bool

Equal returns wether the user equals the other User by comparing every property of the user including the ID

func (*User) GetActivePhone

func (u *User) GetActivePhone() string

GetActivePhone returns the space-trimmed active phone-number of the user. The active phone number is either the MobilePhone number or the first business-Phone number

func (User) GetFullName

func (u User) GetFullName() string

GetFullName returns the full name in that format: <firstname> <lastname>

func (User) GetMemberGroupsAsStrings added in v0.3.0

func (u User) GetMemberGroupsAsStrings(securityGroupsEnabeled bool, opts ...GetQueryOption) ([]string, error)

GetMemberGroupsAsStrings returns a list of all group IDs the user is a member of. You can specify the securityGroupsEnabeled parameter to only return security group IDs.

opts ...GetQueryOption - only msgraph.GetWithContext is supported.

Reference: https://docs.microsoft.com/en-us/graph/api/directoryobject-getmembergroups?view=graph-rest-1.0&tabs=http

func (User) GetShortName

func (u User) GetShortName() string

GetShortName returns the first part of UserPrincipalName before the @. If there is no @, then just the UserPrincipalName will be returned

func (User) ListCalendarView

func (u User) ListCalendarView(startDateTime, endDateTime time.Time, opts ...ListQueryOption) (CalendarEvents, error)

ListCalendarView returns the CalendarEvents of the given user within the specified start- and endDateTime. The calendar used is the default calendar of the user. Returns an error if the user it not GraphClient sourced or if there is any error during the API-call. Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

See https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_calendarview

func (User) ListCalendars

func (u User) ListCalendars(opts ...ListQueryOption) (Calendars, error)

ListCalendars returns all calendars associated to that user. Supports optional OData query parameters https://docs.microsoft.com/en-us/graph/query-parameters

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_calendars

func (User) PrettySimpleString

func (u User) PrettySimpleString() string

PrettySimpleString returns the User-instance simply formatted for logging purposes: {FullName (email) (activePhone)}

func (User) String

func (u User) String() string

func (User) UpdateUser added in v0.2.0

func (u User) UpdateUser(userInput User, opts ...UpdateQueryOption) error

UpdateUser patches this user object. Note, only set the fields that should be changed.

IMPORTANT: the user cannot be disabled (field AccountEnabled) this way, because the default value of a boolean is false - and hence will not be posted via json - omitempty is used. user func user.DisableAccount() instead.

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user-update

type UserSecurityState

type UserSecurityState struct {
	AADUserID                    string    `json:"aadUserId"`
	AccountName                  string    `json:"accountName"`
	DomainName                   string    `json:"domainName"`
	EmailRole                    string    `json:"emailRole"`
	IsVPN                        bool      `json:"isVpn"`
	LogonDateTime                time.Time `json:"logonDateTime"`
	LogonID                      string    `json:"logonId"`
	LogonIP                      net.IP    `json:"logonIp"`
	LogonLocation                string    `json:"logonLocation"`
	LogonType                    string    `json:"logonType"`
	OnPremisesSecurityIdentifier string    `json:"onPremisesSecurityIdentifier"`
	RiskScore                    string    `json:"riskScore"`
	UserAccountType              string    `json:"userAccountType"`
	UserPrincipalName            string    `json:"userPrincipalName"`
}

UserSecurityState contains stateful information about a user account related to an alert.

type Users

type Users []User

Users represents multiple Users, used in JSON unmarshal

func (Users) Equal

func (u Users) Equal(other Users) bool

Equal compares the Users to the other Users and returns true if the two given Users are equal. Otherwise returns false

func (Users) GetUserByActivePhone

func (u Users) GetUserByActivePhone(activePhone string) (User, error)

GetUserByActivePhone returns the User-instance whose activeNumber equals the given phone number. Will return an error ErrFindUser if the user cannot be found

func (Users) GetUserByMail

func (u Users) GetUserByMail(email string) (User, error)

GetUserByMail returns the User-instance that e-mail address matches the given e-mail addr. Will return an error ErrFindUser if the user cannot be found.

func (Users) GetUserByShortName

func (u Users) GetUserByShortName(shortName string) (User, error)

GetUserByShortName returns the first User object that has the given shortName. Will return an error ErrFindUser if the user cannot be found

func (Users) PrettySimpleString

func (u Users) PrettySimpleString() string

PrettySimpleString returns the whole []Users pretty simply formatted for logging purposes

func (Users) String

func (u Users) String() string

type VulnerabilityState

type VulnerabilityState struct {
	CVE        string `json:"cve"`
	Severity   string `json:"severity"`
	WasRunning bool   `json:"wasRunning"`
}

VulnerabilityState contains information about a particular vulnerability.

Jump to

Keyboard shortcuts

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