azure

package
v0.0.0-...-8d027c9 Latest Latest
Warning

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

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

Documentation

Overview

Package azure provides Azure-specific implementations used with AutoRest.

See the included examples for more detail.

Index

Constants

View Source
const (
	// HeaderAsyncOperation is the Azure header containing the location to poll for long-running
	// operations.
	HeaderAsyncOperation = "Azure-AsyncOperation"

	// 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 (
	// OAuthDeviceEndpointTemplate is Azure's OAuth2 Device Flow Endpoint
	OAuthDeviceEndpointTemplate = "https://login.microsoftonline.com/{tenantId}/oauth2/devicecode"
	// OAuthTokenEndpointTemplate is Azure's OAuth2 Token Endpoint
	OAuthTokenEndpointTemplate = "https://login.microsoftonline.com/{tenantId}/oauth2/token"
)
View Source
const (

	// AzureResourceManagerScope is the OAuth scope for the Azure Resource Manager.
	AzureResourceManagerScope = "https://management.azure.com/"

	// 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)
)

Functions

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 GetAsyncOperation

func GetAsyncOperation(resp *http.Response) string

GetAsyncOperation retrieves the long-running URL to poll from the passed response.

func IsAzureError

func IsAzureError(e error) bool

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

func NewAsyncPollingRequest

func NewAsyncPollingRequest(resp *http.Response, c autorest.Client) (*http.Request, error)

NewAsyncPollingRequest allocates and returns a new http.Request to poll an Azure long-running operation. If it successfully creates the request, it will also close the body of the passed response, otherwise the body remains open.

func ResponseIsLongRunning

func ResponseIsLongRunning(resp *http.Response) bool

ResponseIsLongRunning returns true if the passed response is for an Azure long-running operation.

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 WithAsyncPolling

func WithAsyncPolling(defaultDelay time.Duration) autorest.SendDecorator

WithAsyncPolling will poll until the completion of an Azure long-running operation. The delay time between requests is taken from the HTTP Retry-After header, if present, or the passed delay otherwise. Polling may be canceled by signaling on the optional http.Request channel.

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").

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
	ClientID string
	TenantID 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, clientID, tenantID, resource string) (*DeviceCode, error)

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

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

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

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

func (*ServicePrincipalCertificateSecret) SetAuthenticationValues

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

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

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(id string, secret string, tenantID string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

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

func NewServicePrincipalTokenFromCertificate

func NewServicePrincipalTokenFromCertificate(id string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, tenantID string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalTokenFromCertificate create a ServicePrincipalToken from the supplied pkcs12 bytes.

func NewServicePrincipalTokenFromManualToken

func NewServicePrincipalTokenFromManualToken(id string, tenantID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token

func NewServicePrincipalTokenWithSecret

func NewServicePrincipalTokenWithSecret(id string, tenantID 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) 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

type ServicePrincipalTokenSecret struct {
	ClientSecret string
}

ServicePrincipalTokenSecret implements ServicePrincipalSecret for client_secret type authorization.

func (*ServicePrincipalTokenSecret) SetAuthenticationValues

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

Jump to

Keyboard shortcuts

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