azure

package
v7.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2016 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package azure provides Azure-specific implementations used with AutoRest.

See the included examples for more detail.

Index

Examples

Constants

View Source
const (
	// HeaderClientID is the Azure extension header to set a user-specified request ID.
	HeaderClientID = "x-ms-client-request-id"

	// HeaderReturnClientID is the Azure extension header to set if the user-specified request ID
	// should be included in the response.
	HeaderReturnClientID = "x-ms-return-client-request-id"

	// HeaderRequestID is the Azure extension header of the service generated request ID returned
	// in the response.
	HeaderRequestID = "x-ms-request-id"
)
View Source
const (

	// OAuthGrantTypeDeviceCode is the "grant_type" identifier used in device flow
	OAuthGrantTypeDeviceCode = "device_code"

	// OAuthGrantTypeClientCredentials is the "grant_type" identifier used in credential flows
	OAuthGrantTypeClientCredentials = "client_credentials"

	// OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows
	OAuthGrantTypeRefreshToken = "refresh_token"
)

Variables

View Source
var (
	// ErrDeviceGeneric represents an unknown error from the token endpoint when using device flow
	ErrDeviceGeneric = fmt.Errorf("%s Error while retrieving OAuth token: Unknown Error", logPrefix)

	// ErrDeviceAccessDenied represents an access denied error from the token endpoint when using device flow
	ErrDeviceAccessDenied = fmt.Errorf("%s Error while retrieving OAuth token: Access Denied", logPrefix)

	// ErrDeviceAuthorizationPending represents the server waiting on the user to complete the device flow
	ErrDeviceAuthorizationPending = fmt.Errorf("%s Error while retrieving OAuth token: Authorization Pending", logPrefix)

	// ErrDeviceCodeExpired represents the server timing out and expiring the code during device flow
	ErrDeviceCodeExpired = fmt.Errorf("%s Error while retrieving OAuth token: Code Expired", logPrefix)

	// ErrDeviceSlowDown represents the service telling us we're polling too often during device flow
	ErrDeviceSlowDown = fmt.Errorf("%s Error while retrieving OAuth token: Slow Down", logPrefix)
)
View Source
var (
	// PublicCloud is the default public Azure cloud environment
	PublicCloud = Environment{
		Name:                      "AzurePublicCloud",
		ManagementPortalURL:       "https://manage.windowsazure.com/",
		PublishSettingsURL:        "https://manage.windowsazure.com/publishsettings/index",
		ServiceManagementEndpoint: "https://management.core.windows.net/",
		ResourceManagerEndpoint:   "https://management.azure.com/",
		ActiveDirectoryEndpoint:   "https://login.microsoftonline.com/",
		GalleryEndpoint:           "https://gallery.azure.com/",
		KeyVaultEndpoint:          "https://vault.azure.net/",
		GraphEndpoint:             "https://graph.windows.net/",
		StorageEndpointSuffix:     "core.windows.net",
		SQLDatabaseDNSSuffix:      "database.windows.net",
		TrafficManagerDNSSuffix:   "trafficmanager.net",
		KeyVaultDNSSuffix:         "vault.azure.net",
		ServiceBusEndpointSuffix:  "servicebus.azure.com",
	}

	// USGovernmentCloud is the cloud environment for the US Government
	USGovernmentCloud = Environment{
		Name:                      "AzureUSGovernmentCloud",
		ManagementPortalURL:       "https://manage.windowsazure.us/",
		PublishSettingsURL:        "https://manage.windowsazure.us/publishsettings/index",
		ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/",
		ResourceManagerEndpoint:   "https://management.usgovcloudapi.net",
		ActiveDirectoryEndpoint:   "https://login.microsoftonline.com/",
		GalleryEndpoint:           "https://gallery.usgovcloudapi.net/",
		KeyVaultEndpoint:          "https://vault.azure.net/",
		GraphEndpoint:             "https://graph.usgovcloudapi.net/",
		StorageEndpointSuffix:     "core.usgovcloudapi.net",
		SQLDatabaseDNSSuffix:      "database.usgovcloudapi.net",
		TrafficManagerDNSSuffix:   "trafficmanager.net",
		KeyVaultDNSSuffix:         "vault.azure.net",
		ServiceBusEndpointSuffix:  "servicebus.usgovcloudapi.net",
	}

	// ChinaCloud is the cloud environment operated in China
	ChinaCloud = Environment{
		Name:                      "AzureChinaCloud",
		ManagementPortalURL:       "https://manage.chinacloudapi.com/",
		PublishSettingsURL:        "https://manage.chinacloudapi.com/publishsettings/index",
		ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/",
		ResourceManagerEndpoint:   "https://management.chinacloudapi.cn/",
		ActiveDirectoryEndpoint:   "https://login.chinacloudapi.cn/?api-version=1.0",
		GalleryEndpoint:           "https://gallery.chinacloudapi.cn/",
		KeyVaultEndpoint:          "https://vault.azure.net/",
		GraphEndpoint:             "https://graph.chinacloudapi.cn/",
		StorageEndpointSuffix:     "core.chinacloudapi.cn",
		SQLDatabaseDNSSuffix:      "database.chinacloudapi.cn",
		TrafficManagerDNSSuffix:   "trafficmanager.cn",
		KeyVaultDNSSuffix:         "vault.azure.net",
		ServiceBusEndpointSuffix:  "servicebus.chinacloudapi.net",
	}
)

Functions

func DoPollForAsynchronous

func DoPollForAsynchronous(delay time.Duration) autorest.SendDecorator

DoPollForAsynchronous returns a SendDecorator that polls if the http.Response is for an Azure long-running operation. It will delay between requests for the duration specified in the RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by closing the optional channel on the http.Request.

func ExtractClientID

func ExtractClientID(resp *http.Response) string

ExtractClientID extracts the client identifier from the x-ms-client-request-id header set on the http.Request sent to the service (and returned in the http.Response)

func ExtractRequestID

func ExtractRequestID(resp *http.Response) string

ExtractRequestID extracts the Azure server generated request identifier from the x-ms-request-id header.

func IsAzureError

func IsAzureError(e error) bool

IsAzureError returns true if the passed error is an Azure Service error; false otherwise.

func SaveToken

func SaveToken(path string, mode os.FileMode, token Token) error

SaveToken persists an oauth token at the given location on disk. It moves the new file into place so it can safely be used to replace an existing file that maybe accessed by multiple processes.

func WithClientID

func WithClientID(uuid string) autorest.PrepareDecorator

WithClientID returns a PrepareDecorator that adds an HTTP extension header of x-ms-client-request-id whose value is passed, undecorated UUID (e.g., "0F39878C-5F76-4DB8-A25D-61D2C193C3CA").

Example

Use a Client Inspector to set the request identifier.

uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6"
req, _ := autorest.Prepare(&http.Request{},
	autorest.AsGet(),
	autorest.WithBaseURL("https://microsoft.com/a/b/c/"))

c := autorest.Client{Sender: mocks.NewSender()}
c.RequestInspector = WithReturningClientID(uuid)

autorest.SendWithSender(c, req)
fmt.Printf("Inspector added the %s header with the value %s\n",
	HeaderClientID, req.Header.Get(HeaderClientID))
fmt.Printf("Inspector added the %s header with the value %s\n",
	HeaderReturnClientID, req.Header.Get(HeaderReturnClientID))
Output:

Inspector added the x-ms-client-request-id header with the value 71FDB9F4-5E49-4C12-B266-DE7B4FD999A6
Inspector added the x-ms-return-client-request-id header with the value true

func WithErrorUnlessStatusCode

func WithErrorUnlessStatusCode(codes ...int) autorest.RespondDecorator

WithErrorUnlessStatusCode returns a RespondDecorator that emits an azure.RequestError by reading the response body unless the response HTTP status code is among the set passed.

If there is a chance service may return responses other than the Azure error format and the response cannot be parsed into an error, a decoding error will be returned containing the response body. In any case, the Responder will return an error if the status code is not satisfied.

If this Responder returns an error, the response body will be replaced with an in-memory reader, which needs no further closing.

func WithReturnClientID

func WithReturnClientID(b bool) autorest.PrepareDecorator

WithReturnClientID returns a PrepareDecorator that adds an HTTP extension header of x-ms-return-client-request-id whose boolean value indicates if the value of the x-ms-client-request-id header should be included in the http.Response.

func WithReturningClientID

func WithReturningClientID(uuid string) autorest.PrepareDecorator

WithReturningClientID returns a PrepareDecorator that adds an HTTP extension header of x-ms-client-request-id whose value is the passed, undecorated UUID (e.g., "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). It also sets the x-ms-return-client-request-id header to true such that UUID accompanies the http.Response.

Types

type DeviceCode

type DeviceCode struct {
	DeviceCode      *string `json:"device_code,omitempty"`
	UserCode        *string `json:"user_code,omitempty"`
	VerificationURL *string `json:"verification_url,omitempty"`
	ExpiresIn       *int64  `json:"expires_in,string,omitempty"`
	Interval        *int64  `json:"interval,string,omitempty"`

	Message     *string `json:"message"` // Azure specific
	Resource    string  // store the following, stored when initiating, used when exchanging
	OAuthConfig OAuthConfig
	ClientID    string
}

DeviceCode is the object returned by the device auth endpoint It contains information to instruct the user to complete the auth flow

func InitiateDeviceAuth

func InitiateDeviceAuth(client *autorest.Client, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error)

InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode that can be used with CheckForUserCompletion or WaitForUserCompletion.

type Environment

type Environment struct {
	Name                      string
	ManagementPortalURL       string
	PublishSettingsURL        string
	ServiceManagementEndpoint string
	ResourceManagerEndpoint   string
	ActiveDirectoryEndpoint   string
	GalleryEndpoint           string
	KeyVaultEndpoint          string
	GraphEndpoint             string
	StorageEndpointSuffix     string
	SQLDatabaseDNSSuffix      string
	TrafficManagerDNSSuffix   string
	KeyVaultDNSSuffix         string
	ServiceBusEndpointSuffix  string
}

Environment represents a set of endpoints for each of Azure's Clouds.

func (Environment) OAuthConfigForTenant

func (env Environment) OAuthConfigForTenant(tenantID string) (*OAuthConfig, error)

OAuthConfigForTenant returns an OAuthConfig with tenant specific urls

type OAuthConfig

type OAuthConfig struct {
	AuthorizeEndpoint  url.URL
	TokenEndpoint      url.URL
	DeviceCodeEndpoint url.URL
}

OAuthConfig represents the endpoints needed in OAuth operations

type RequestError

type RequestError struct {
	autorest.DetailedError

	// The error returned by the Azure service.
	ServiceError *ServiceError `json:"error"`

	// The request id (from the x-ms-request-id-header) of the request.
	RequestID string
}

RequestError describes an error response returned by Azure service.

func NewErrorWithError

func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) RequestError

NewErrorWithError creates a new Error conforming object from the passed packageType, method, statusCode of the given resp (UndefinedStatusCode if resp is nil), message, and original error. message is treated as a format string to which the optional args apply.

func (RequestError) Error

func (e RequestError) Error() string

Error returns a human-friendly error message from service error.

type ServiceError

type ServiceError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

ServiceError encapsulates the error response from an Azure service.

type ServicePrincipalCertificateSecret added in v1.1.0

type ServicePrincipalCertificateSecret struct {
	Certificate *x509.Certificate
	PrivateKey  *rsa.PrivateKey
}

ServicePrincipalCertificateSecret implements ServicePrincipalSecret for generic RSA cert auth with signed JWTs.

func (*ServicePrincipalCertificateSecret) SetAuthenticationValues added in v1.1.0

func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error

SetAuthenticationValues is a method of the interface ServicePrincipalSecret. It will populate the form submitted during oAuth Token Acquisition using a JWT signed with a certificate.

func (*ServicePrincipalCertificateSecret) SignJwt added in v1.1.0

SignJwt returns the JWT signed with the certificate's private key.

type ServicePrincipalNoSecret

type ServicePrincipalNoSecret struct {
}

ServicePrincipalNoSecret represents a secret type that contains no secret meaning it is not valid for fetching a fresh token. This is used by Manual

func (*ServicePrincipalNoSecret) SetAuthenticationValues

func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error

SetAuthenticationValues is a method of the interface ServicePrincipalSecret It only returns an error for the ServicePrincipalNoSecret type

type ServicePrincipalSecret added in v1.1.0

type ServicePrincipalSecret interface {
	SetAuthenticationValues(spt *ServicePrincipalToken, values *url.Values) error
}

ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form that is submitted when acquiring an oAuth token.

type ServicePrincipalToken

type ServicePrincipalToken struct {
	Token
	// contains filtered or unexported fields
}

ServicePrincipalToken encapsulates a Token created for a Service Principal.

func NewServicePrincipalToken

func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal credentials scoped to the named resource.

func NewServicePrincipalTokenFromCertificate added in v1.1.0

func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalTokenFromCertificate create a ServicePrincipalToken from the supplied pkcs12 bytes.

func NewServicePrincipalTokenFromManualToken

func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token

func NewServicePrincipalTokenWithSecret added in v1.1.0

func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation.

func (*ServicePrincipalToken) EnsureFresh

func (spt *ServicePrincipalToken) EnsureFresh() error

EnsureFresh will refresh the token if it will expire within the refresh window (as set by RefreshWithin).

func (*ServicePrincipalToken) InvokeRefreshCallbacks

func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error

InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization

func (*ServicePrincipalToken) Refresh

func (spt *ServicePrincipalToken) Refresh() error

Refresh obtains a fresh token for the Service Principal.

func (*ServicePrincipalToken) RefreshExchange

func (spt *ServicePrincipalToken) RefreshExchange(resource string) error

RefreshExchange refreshes the token, but for a different resource.

func (*ServicePrincipalToken) SetAutoRefresh

func (spt *ServicePrincipalToken) SetAutoRefresh(autoRefresh bool)

SetAutoRefresh enables or disables automatic refreshing of stale tokens.

func (*ServicePrincipalToken) SetRefreshWithin

func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration)

SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will refresh the token.

func (*ServicePrincipalToken) SetSender

func (spt *ServicePrincipalToken) SetSender(s autorest.Sender)

SetSender sets the autorest.Sender used when obtaining the Service Principal token. An undecorated http.Client is used by default.

func (*ServicePrincipalToken) WithAuthorization

func (spt *ServicePrincipalToken) WithAuthorization() autorest.PrepareDecorator

WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose value is "Bearer " followed by the AccessToken of the ServicePrincipalToken.

By default, the token will automatically refresh if nearly expired (as determined by the RefreshWithin interval). Use the AutoRefresh method to enable or disable automatically refreshing tokens.

type ServicePrincipalTokenSecret added in v1.1.0

type ServicePrincipalTokenSecret struct {
	ClientSecret string
}

ServicePrincipalTokenSecret implements ServicePrincipalSecret for client_secret type authorization.

func (*ServicePrincipalTokenSecret) SetAuthenticationValues added in v1.1.0

func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error

SetAuthenticationValues is a method of the interface ServicePrincipalSecret. It will populate the form submitted during oAuth Token Acquisition using the client_secret.

type Token

type Token struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`

	ExpiresIn string `json:"expires_in"`
	ExpiresOn string `json:"expires_on"`
	NotBefore string `json:"not_before"`

	Resource string `json:"resource"`
	Type     string `json:"token_type"`
}

Token encapsulates the access token used to authorize Azure requests.

func CheckForUserCompletion

func CheckForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error)

CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint to see if the device flow has: been completed, timed out, or otherwise failed

func LoadToken

func LoadToken(path string) (*Token, error)

LoadToken restores a Token object from a file located at 'path'.

func WaitForUserCompletion

func WaitForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error)

WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'.

func (Token) Expires

func (t Token) Expires() time.Time

Expires returns the time.Time when the Token expires.

func (Token) IsExpired

func (t Token) IsExpired() bool

IsExpired returns true if the Token is expired, false otherwise.

func (Token) WillExpireIn

func (t Token) WillExpireIn(d time.Duration) bool

WillExpireIn returns true if the Token will expire after the passed time.Duration interval from now, false otherwise.

func (*Token) WithAuthorization

func (t *Token) WithAuthorization() autorest.PrepareDecorator

WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose value is "Bearer " followed by the AccessToken of the Token.

type TokenError

type TokenError struct {
	Error            *string `json:"error,omitempty"`
	ErrorCodes       []int   `json:"error_codes,omitempty"`
	ErrorDescription *string `json:"error_description,omitempty"`
	Timestamp        *string `json:"timestamp,omitempty"`
	TraceID          *string `json:"trace_id,omitempty"`
}

TokenError is the object returned by the token exchange endpoint when something is amiss

type TokenRefreshCallback

type TokenRefreshCallback func(Token) error

TokenRefreshCallback is the type representing callbacks that will be called after a successful token refresh

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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