2018-11-21 22:06:03 +01:00
package authentication
import (
"fmt"
"log"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/hashicorp/go-multierror"
)
type managedServiceIdentityAuth struct {
2019-11-26 01:03:57 +01:00
msiEndpoint string
clientID string
2018-11-21 22:06:03 +01:00
}
func ( a managedServiceIdentityAuth ) build ( b Builder ) ( authMethod , error ) {
2019-11-26 01:03:57 +01:00
msiEndpoint := b . MsiEndpoint
if msiEndpoint == "" {
ep , err := adal . GetMSIVMEndpoint ( )
2018-11-21 22:06:03 +01:00
if err != nil {
return nil , fmt . Errorf ( "Error determining MSI Endpoint: ensure the VM has MSI enabled, or configure the MSI Endpoint. Error: %s" , err )
}
2019-11-26 01:03:57 +01:00
msiEndpoint = ep
2018-11-21 22:06:03 +01:00
}
2019-11-26 01:03:57 +01:00
log . Printf ( "[DEBUG] Using MSI msiEndpoint %q" , msiEndpoint )
2018-11-21 22:06:03 +01:00
auth := managedServiceIdentityAuth {
2019-11-26 01:03:57 +01:00
msiEndpoint : msiEndpoint ,
clientID : b . ClientID ,
2018-11-21 22:06:03 +01:00
}
return auth , nil
}
func ( a managedServiceIdentityAuth ) isApplicable ( b Builder ) bool {
return b . SupportsManagedServiceIdentity
}
func ( a managedServiceIdentityAuth ) name ( ) string {
return "Managed Service Identity"
}
2019-11-26 01:03:57 +01:00
func ( a managedServiceIdentityAuth ) getAuthorizationToken ( sender autorest . Sender , oauth * OAuthConfig , endpoint string ) ( autorest . Authorizer , error ) {
log . Printf ( "[DEBUG] getAuthorizationToken with MSI msiEndpoint %q, ClientID %q for msiEndpoint %q" , a . msiEndpoint , a . clientID , endpoint )
if oauth . OAuth == nil {
return nil , fmt . Errorf ( "Error getting Authorization Token for MSI auth: an OAuth token wasn't configured correctly; please file a bug with more details" )
}
var spt * adal . ServicePrincipalToken
var err error
if a . clientID == "" {
spt , err = adal . NewServicePrincipalTokenFromMSI ( a . msiEndpoint , endpoint )
if err != nil {
return nil , err
}
} else {
spt , err = adal . NewServicePrincipalTokenFromMSIWithUserAssignedID ( a . msiEndpoint , endpoint , a . clientID )
if err != nil {
return nil , fmt . Errorf ( "failed to get an oauth token from MSI for user assigned identity from MSI endpoint %q with client ID %q for endpoint %q: %v" , a . msiEndpoint , a . clientID , endpoint , err )
}
2018-11-21 22:06:03 +01:00
}
2019-11-26 01:03:57 +01:00
spt . SetSender ( sender )
2018-11-21 22:06:03 +01:00
auth := autorest . NewBearerAuthorizer ( spt )
return auth , nil
}
func ( a managedServiceIdentityAuth ) populateConfig ( c * Config ) error {
// nothing to populate back
return nil
}
func ( a managedServiceIdentityAuth ) validate ( ) error {
var err * multierror . Error
2019-11-26 01:03:57 +01:00
if a . msiEndpoint == "" {
2018-11-21 22:06:03 +01:00
err = multierror . Append ( err , fmt . Errorf ( "An MSI Endpoint must be configured" ) )
}
return err . ErrorOrNil ( )
}