diff --git a/azurerm/config.go b/azurerm/config.go index 06c646de77c9..504ace47ae80 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -99,6 +99,7 @@ type ArmClient struct { // Authentication roleAssignmentsClient authorization.RoleAssignmentsClient roleDefinitionsClient authorization.RoleDefinitionsClient + applicationsClient graphrbac.ApplicationsClient servicePrincipalsClient graphrbac.ServicePrincipalsClient // CDN @@ -446,6 +447,13 @@ func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscription definitionsClient.SkipResourceProviderRegistration = c.skipProviderRegistration c.roleDefinitionsClient = definitionsClient + applicationsClient := graphrbac.NewApplicationsClientWithBaseURI(graphEndpoint, tenantId) + setUserAgent(&applicationsClient.Client) + applicationsClient.Authorizer = graphAuth + applicationsClient.Sender = sender + applicationsClient.SkipResourceProviderRegistration = c.skipProviderRegistration + c.applicationsClient = applicationsClient + servicePrincipalsClient := graphrbac.NewServicePrincipalsClientWithBaseURI(graphEndpoint, tenantId) setUserAgent(&servicePrincipalsClient.Client) servicePrincipalsClient.Authorizer = graphAuth diff --git a/azurerm/import_arm_ad_application_test.go b/azurerm/import_arm_ad_application_test.go new file mode 100644 index 000000000000..9b381c87e346 --- /dev/null +++ b/azurerm/import_arm_ad_application_test.go @@ -0,0 +1,105 @@ +package azurerm + +import ( + "testing" + "time" + + "github.com/google/uuid" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAzureRMAdApplication_importSimple(t *testing.T) { + resourceName := "azurerm_ad_application.test" + + id := uuid.New().String() + config := testAccAzureRMAdApplication_simple(id) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMAdApplication_importAdvanced(t *testing.T) { + resourceName := "azurerm_ad_application.test" + + id := uuid.New().String() + config := testAccAzureRMAdApplication_advanced(id) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMAdApplication_importKeyCredential(t *testing.T) { + resourceName := "azurerm_ad_application.test" + + id := uuid.New().String() + keyId := uuid.New().String() + config := testAccAzureRMAdApplication_keyCredential_single(id, keyId, "AsymmetricX509Cert") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersWithTLS, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMAdApplication_importPasswordCredential(t *testing.T) { + resourceName := "azurerm_ad_application.test" + + id := uuid.New().String() + keyId := uuid.New().String() + timeStart := time.Now().UTC() + timeEnd := timeStart.Add(time.Duration(1) * time.Hour) + config := testAccAzureRMAdApplication_passwordCredential_single(id, keyId, timeStart, timeEnd) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/azurerm/import_arm_service_principal_test.go b/azurerm/import_arm_service_principal_test.go new file mode 100644 index 000000000000..7346f1b3db29 --- /dev/null +++ b/azurerm/import_arm_service_principal_test.go @@ -0,0 +1,31 @@ +package azurerm + +import ( + "testing" + + "github.com/google/uuid" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAzureRMServicePrincipal_importSimple(t *testing.T) { + resourceName := "azurerm_service_principal.test" + + id := uuid.New().String() + config := testAccAzureRMServicePrincipal_simple(id) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServicePrincipalDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/azurerm/key_credentials.go b/azurerm/key_credentials.go new file mode 100644 index 000000000000..2826cffd1581 --- /dev/null +++ b/azurerm/key_credentials.go @@ -0,0 +1,214 @@ +package azurerm + +import ( + "bytes" + "fmt" + "regexp" + "time" + + "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" + "github.com/Azure/go-autorest/autorest/date" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func keyCredentialsSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateUUID, + }, + + "start_date": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: compareDataAsUTCSuppressFunc, + ValidateFunc: validateRFC3339Date, + }, + + "end_date": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: compareDataAsUTCSuppressFunc, + ValidateFunc: validateRFC3339Date, + }, + + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + "AsymmetricX509Cert", + "Symmetric", + }, true), + }, + + "usage": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + "Verify", + "Sign", + }, true), + }, + + "value": { + Type: schema.TypeString, + Required: true, + Sensitive: true, + }, + }, + }, + Set: resourceKeyCredentialHash, + } +} + +func customizeDiffKeyCredential(diff *schema.ResourceDiff, v interface{}) error { + o, n := diff.GetChange("key_credential") + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } + os := o.(*schema.Set) + ns := n.(*schema.Set) + + // Detect if the user changed a key credential property without changing the + // KeyID associated with the credential. Changing the property changes the hash, + // which causes Terraform to pick it up as a new Set item. This will cause + // a conflict due to the unique KeyID requirement. + m := make(map[string]string) + for _, v := range os.Difference(ns).List() { + x := v.(map[string]interface{}) + m[x["key_id"].(string)] = x["key_id"].(string) + } + for _, v := range ns.Difference(os).List() { + x := v.(map[string]interface{}) + if _, ok := m[x["key_id"].(string)]; ok { + return fmt.Errorf("Error: changing Key Credential properties on existing KeyID %s requires generating a new unique KeyID.", x["key_id"].(string)) + } + } + + return nil +} + +func resourceKeyCredentialHash(v interface{}) int { + var buf bytes.Buffer + + if v != nil { + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["key_id"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["type"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["usage"].(string))) + + // We parse the DateTimes and then convert them back to a string + // in order to have a consistent format for the hash. + + if st, err := time.Parse(time.RFC3339, m["start_date"].(string)); err == nil { + buf.WriteString(fmt.Sprintf("%s-", string((st).Format(time.RFC3339)))) + } + + if et, err := time.Parse(time.RFC3339, m["end_date"].(string)); err == nil { + buf.WriteString(fmt.Sprintf("%s-", string((et).Format(time.RFC3339)))) + } + } + + return hashcode.String(buf.String()) +} + +func flattenAzureRmKeyCredential(cred *graphrbac.KeyCredential) interface{} { + l := make(map[string]interface{}) + l["key_id"] = *cred.KeyID + l["type"] = *cred.Type + l["usage"] = *cred.Usage + l["start_date"] = string((*cred.StartDate).Format(time.RFC3339)) + l["end_date"] = string((*cred.EndDate).Format(time.RFC3339)) + + return l +} + +func flattenAzureRmKeyCredentials(creds *[]graphrbac.KeyCredential) []interface{} { + result := make([]interface{}, 0, len(*creds)) + for _, cred := range *creds { + result = append(result, flattenAzureRmKeyCredential(&cred)) + } + return result +} + +func expandAzureRmKeyCredential(d *map[string]interface{}) (*graphrbac.KeyCredential, error) { + keyId := (*d)["key_id"].(string) + startDate := (*d)["start_date"].(string) + endDate := (*d)["end_date"].(string) + keyType := (*d)["type"].(string) + usage := (*d)["usage"].(string) + value := (*d)["value"].(string) + + if keyType == "AsymmetricX509Cert" && usage == "Sign" { + return nil, fmt.Errorf("Usage cannot be set to %s when %s is set as type for a Key Credential", usage, keyType) + } + + // Match against the prefix/suffix and '\n' of certificate values. + // The API doesn't accept them so they need to be removed. + pkre := regexp.MustCompile(`(-{5}.+?-{5})|(\n)`) + value = pkre.ReplaceAllString(value, ``) + + kc := graphrbac.KeyCredential{ + KeyID: &keyId, + Type: &keyType, + Usage: &usage, + Value: &value, + } + + if startDate != "" { + starttime, sterr := time.Parse(time.RFC3339, startDate) + if sterr != nil { + return nil, fmt.Errorf("Cannot parse start_date: %q", startDate) + } + stdt := date.Time{Time: starttime.Truncate(time.Second)} + kc.StartDate = &stdt + } + + if endDate != "" { + endtime, eterr := time.Parse(time.RFC3339, endDate) + if eterr != nil { + return nil, fmt.Errorf("Cannot parse end_date: %q", endDate) + } + etdt := date.Time{Time: endtime.Truncate(time.Second)} + kc.EndDate = &etdt + } + + return &kc, nil +} + +func expandAzureRmKeyCredentials(d *schema.ResourceData, o *schema.Set) (*[]graphrbac.KeyCredential, error) { + creds := d.Get("key_credential").(*schema.Set).List() + keyCreds := make([]graphrbac.KeyCredential, 0, len(creds)) + + for _, v := range creds { + cfg := v.(map[string]interface{}) + cred, err := expandAzureRmKeyCredential(&cfg) + if err != nil { + return nil, err + } + + // Azure only allows an in-place update of the Key Credentials list. + // Existing keys, matched by their KeyID, must be sent back with their + // Value attribute set to nil. New keys need to provide a Value. + // By referencing the existing schema (o), we can determine which + // entries in the list are existing keys. + if o != nil && o.Contains(v) { + cred.Value = nil + } + + keyCreds = append(keyCreds, *cred) + } + + return &keyCreds, nil +} diff --git a/azurerm/password_credentials.go b/azurerm/password_credentials.go new file mode 100644 index 000000000000..4ded9d8a1edb --- /dev/null +++ b/azurerm/password_credentials.go @@ -0,0 +1,177 @@ +package azurerm + +import ( + "bytes" + "fmt" + "time" + + "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" + "github.com/Azure/go-autorest/autorest/date" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func passwordCredentialsSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateUUID, + }, + + "start_date": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: compareDataAsUTCSuppressFunc, + ValidateFunc: validateRFC3339Date, + }, + + "end_date": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: compareDataAsUTCSuppressFunc, + ValidateFunc: validateRFC3339Date, + }, + + "value": { + Type: schema.TypeString, + Required: true, + Sensitive: true, + }, + }, + }, + Set: resourcePasswordCredentialHash, + } +} + +func customizeDiffPasswordCredential(diff *schema.ResourceDiff, v interface{}) error { + o, n := diff.GetChange("password_credential") + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } + os := o.(*schema.Set) + ns := n.(*schema.Set) + + // Detect if the user changed a password credential property without changing the + // KeyID associated with the credential. Changing the property changes the hash, + // which causes Terraform to pick it up as a new Set item. This will cause + // a conflict due to the unique KeyID requirement. + m := make(map[string]string) + for _, v := range os.Difference(ns).List() { + x := v.(map[string]interface{}) + m[x["key_id"].(string)] = x["key_id"].(string) + } + for _, v := range ns.Difference(os).List() { + x := v.(map[string]interface{}) + if _, ok := m[x["key_id"].(string)]; ok { + return fmt.Errorf("Error: changing Password Credential properties on existing KeyID %s requires generating a new unique KeyID.", x["key_id"].(string)) + } + } + + return nil +} + +func resourcePasswordCredentialHash(v interface{}) int { + var buf bytes.Buffer + + if v != nil { + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["key_id"].(string))) + + // We parse the DateTimes and then convert them back to a string + // in order to have a consistent format for the hash. + + if st, err := time.Parse(time.RFC3339, m["start_date"].(string)); err == nil { + buf.WriteString(fmt.Sprintf("%s-", string((st).Format(time.RFC3339)))) + } + + if et, err := time.Parse(time.RFC3339, m["end_date"].(string)); err == nil { + buf.WriteString(fmt.Sprintf("%s-", string((et).Format(time.RFC3339)))) + } + } + + return hashcode.String(buf.String()) +} + +func flattenAzureRmPasswordCredential(cred *graphrbac.PasswordCredential) interface{} { + l := make(map[string]interface{}) + l["key_id"] = *cred.KeyID + l["start_date"] = string((*cred.StartDate).Format(time.RFC3339)) + l["end_date"] = string((*cred.EndDate).Format(time.RFC3339)) + + return l +} + +func flattenAzureRmPasswordCredentials(creds *[]graphrbac.PasswordCredential) []interface{} { + result := make([]interface{}, 0, len(*creds)) + for _, cred := range *creds { + result = append(result, flattenAzureRmPasswordCredential(&cred)) + } + return result +} + +func expandAzureRmPasswordCredential(d *map[string]interface{}) (*graphrbac.PasswordCredential, error) { + keyId := (*d)["key_id"].(string) + startDate := (*d)["start_date"].(string) + endDate := (*d)["end_date"].(string) + value := (*d)["value"].(string) + + pc := graphrbac.PasswordCredential{ + KeyID: &keyId, + Value: &value, + } + + if startDate != "" { + starttime, sterr := time.Parse(time.RFC3339, startDate) + if sterr != nil { + return nil, fmt.Errorf("Cannot parse start_date: %q", startDate) + } + stdt := date.Time{Time: starttime} + pc.StartDate = &stdt + } + + if endDate != "" { + endtime, eterr := time.Parse(time.RFC3339, endDate) + if eterr != nil { + return nil, fmt.Errorf("Cannot parse end_date: %q", endDate) + } + etdt := date.Time{Time: endtime} + pc.EndDate = &etdt + } + + return &pc, nil +} + +func expandAzureRmPasswordCredentials(d *schema.ResourceData, o *schema.Set) (*[]graphrbac.PasswordCredential, error) { + creds := d.Get("password_credential").(*schema.Set).List() + passCreds := make([]graphrbac.PasswordCredential, 0, len(creds)) + + for _, v := range creds { + cfg := v.(map[string]interface{}) + cred, err := expandAzureRmPasswordCredential(&cfg) + if err != nil { + return nil, err + } + + // Azure only allows an in-place update of the Password Credentials list. + // Existing keys, matched by their KeyID, must be sent back with their + // Value attribute set to nil. New keys need to provide a Value. + // By referencing the existing schema (o), we can determine which + // entries in the list are existing keys. + if o != nil && o.Contains(v) { + cred.Value = nil + } + + passCreds = append(passCreds, *cred) + } + + return &passCreds, nil +} diff --git a/azurerm/provider.go b/azurerm/provider.go index 96971de5e67e..79605d71b5cc 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -113,6 +113,7 @@ func Provider() terraform.ResourceProvider { }, ResourcesMap: map[string]*schema.Resource{ + "azurerm_ad_application": resourceArmAdApplication(), "azurerm_application_gateway": resourceArmApplicationGateway(), "azurerm_application_insights": resourceArmApplicationInsights(), "azurerm_application_security_group": resourceArmApplicationSecurityGroup(), @@ -200,6 +201,7 @@ func Provider() terraform.ResourceProvider { "azurerm_servicebus_subscription_rule": resourceArmServiceBusSubscriptionRule(), "azurerm_servicebus_topic": resourceArmServiceBusTopic(), "azurerm_servicebus_topic_authorization_rule": resourceArmServiceBusTopicAuthorizationRule(), + "azurerm_service_principal": resourceArmServicePrincipal(), "azurerm_snapshot": resourceArmSnapshot(), "azurerm_scheduler_job_collection": resourceArmSchedulerJobCollection(), "azurerm_sql_database": resourceArmSqlDatabase(), diff --git a/azurerm/provider_test.go b/azurerm/provider_test.go index 4c8fc5ff3d8c..a1529d211a78 100644 --- a/azurerm/provider_test.go +++ b/azurerm/provider_test.go @@ -11,9 +11,11 @@ import ( "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/authentication" + "github.com/terraform-providers/terraform-provider-tls/tls" ) var testAccProviders map[string]terraform.ResourceProvider +var testAccProvidersWithTLS map[string]terraform.ResourceProvider var testAccProvider *schema.Provider func init() { @@ -21,6 +23,12 @@ func init() { testAccProviders = map[string]terraform.ResourceProvider{ "azurerm": testAccProvider, } + testAccProvidersWithTLS = map[string]terraform.ResourceProvider{ + "tls": tls.Provider().(*schema.Provider), + } + for k, v := range testAccProviders { + testAccProvidersWithTLS[k] = v + } } func TestProvider(t *testing.T) { diff --git a/azurerm/resource_arm_ad_application.go b/azurerm/resource_arm_ad_application.go new file mode 100644 index 000000000000..fb6b0ccadb96 --- /dev/null +++ b/azurerm/resource_arm_ad_application.go @@ -0,0 +1,325 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" + "github.com/hashicorp/terraform/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmAdApplication() *schema.Resource { + return &schema.Resource{ + Create: resourceArmAdApplicationCreate, + Read: resourceArmAdApplicationRead, + Update: resourceArmAdApplicationUpdate, + Delete: resourceArmAdApplicationDelete, + CustomizeDiff: customizeDiffAd, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "display_name": { + Type: schema.TypeString, + Required: true, + }, + + "homepage": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "identifier_uris": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "reply_urls": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "available_to_other_tenants": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + + "oauth2_allow_implicit_flow": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + + "key_credential": keyCredentialsSchema(), + + "password_credential": passwordCredentialsSchema(), + + "app_id": { + Type: schema.TypeString, + Computed: true, + }, + + "object_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func customizeDiffAd(diff *schema.ResourceDiff, v interface{}) error { + + if err := customizeDiffKeyCredential(diff, v); err != nil { + return err + } + + if err := customizeDiffPasswordCredential(diff, v); err != nil { + return err + } + + return nil +} + +func resourceArmAdApplicationCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).applicationsClient + ctx := meta.(*ArmClient).StopContext + + name := d.Get("display_name").(string) + multitenant := d.Get("available_to_other_tenants").(bool) + + properties := graphrbac.ApplicationCreateParameters{ + DisplayName: &name, + Homepage: expandAzureRmAdApplicationHomepage(d, name), + IdentifierUris: expandAzureRmAdApplicationIdentifierUris(d, name), + ReplyUrls: expandAzureRmAdApplicationReplyUrls(d, name), + AvailableToOtherTenants: utils.Bool(multitenant), + } + + if v, ok := d.GetOk("oauth2_allow_implicit_flow"); ok { + properties.Oauth2AllowImplicitFlow = utils.Bool(v.(bool)) + } + + if _, ok := d.GetOk("key_credential"); ok { + keyCreds, err := expandAzureRmKeyCredentials(d, nil) + if err != nil { + return err + } + properties.KeyCredentials = keyCreds + } + + if _, ok := d.GetOk("password_credential"); ok { + passCreds, err := expandAzureRmPasswordCredentials(d, nil) + if err != nil { + return err + } + properties.PasswordCredentials = passCreds + } + + app, err := client.Create(ctx, properties) + if err != nil { + return err + } + + d.SetId(*app.ObjectID) + + return resourceArmAdApplicationRead(d, meta) +} + +func resourceArmAdApplicationRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).applicationsClient + ctx := meta.(*ArmClient).StopContext + + resp, err := client.Get(ctx, d.Id()) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[DEBUG] Application ID %q was not found - removing from state", d.Id()) + d.SetId("") + return nil + } + + return fmt.Errorf("Error loading Application %q: %+v", d.Id(), err) + } + + d.Set("display_name", resp.DisplayName) + d.Set("app_id", resp.AppID) + d.Set("object_id", resp.ObjectID) + d.Set("homepage", resp.Homepage) + d.Set("identifier_uris", resp.IdentifierUris) + d.Set("reply_urls", resp.ReplyUrls) + d.Set("available_to_other_tenants", resp.AvailableToOtherTenants) + d.Set("oauth2_allow_implicit_flow", resp.Oauth2AllowImplicitFlow) + + rkc, err := client.ListKeyCredentials(ctx, d.Id()) + if err != nil { + return fmt.Errorf("Error loading Application Key Credentials %q: %+v", d.Id(), err) + } + + if err := d.Set("key_credential", flattenAzureRmKeyCredentials(rkc.Value)); err != nil { + return fmt.Errorf("[DEBUG] Error setting Application Key Credentials error: %#v", err) + } + + rpc, err := client.ListPasswordCredentials(ctx, d.Id()) + if err != nil { + return fmt.Errorf("Error loading Application Password Credentials %q: %+v", d.Id(), err) + } + + if err := d.Set("password_credential", flattenAzureRmPasswordCredentials(rpc.Value)); err != nil { + return fmt.Errorf("[DEBUG] Error setting Application Password Credentials error: %#v", err) + } + + return nil +} + +func resourceArmAdApplicationUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).applicationsClient + ctx := meta.(*ArmClient).StopContext + + name := d.Get("display_name").(string) + + var properties graphrbac.ApplicationUpdateParameters + + if d.HasChange("display_name") { + properties.DisplayName = &name + } + + if d.HasChange("homepage") { + properties.Homepage = expandAzureRmAdApplicationHomepage(d, name) + } + + if d.HasChange("identifier_uris") { + properties.IdentifierUris = expandAzureRmAdApplicationIdentifierUris(d, name) + } + + if d.HasChange("reply_urls") { + properties.ReplyUrls = expandAzureRmAdApplicationReplyUrls(d, name) + } + + if d.HasChange("available_to_other_tenants") { + multitenant := d.Get("available_to_other_tenants").(bool) + properties.AvailableToOtherTenants = utils.Bool(multitenant) + } + + if d.HasChange("oauth2_allow_implicit_flow") { + oauth := d.Get("oauth2_allow_implicit_flow").(bool) + properties.Oauth2AllowImplicitFlow = utils.Bool(oauth) + } + + d.Partial(true) + + _, err := client.Patch(ctx, d.Id(), properties) + if err != nil { + return err + } + + d.SetPartial("display_name") + d.SetPartial("homepage") + d.SetPartial("identifier_uris") + d.SetPartial("reply_urls") + d.SetPartial("available_to_other_tenants") + d.SetPartial("oauth2_allow_implicit_flow") + d.SetPartial("app_id") + d.SetPartial("object_id") + + if d.HasChange("key_credential") { + o, _ := d.GetChange("key_credential") + + kc, kcErr := expandAzureRmKeyCredentials(d, o.(*schema.Set)) + if kcErr != nil { + return kcErr + } + + keyUpdate := graphrbac.KeyCredentialsUpdateParameters{ + Value: kc, + } + + _, err := client.UpdateKeyCredentials(ctx, d.Id(), keyUpdate) + if err != nil { + return err + } + + d.SetPartial("key_credential") + } + + if d.HasChange("password_credential") { + o, _ := d.GetChange("password_credential") + + pc, pcErr := expandAzureRmPasswordCredentials(d, o.(*schema.Set)) + if pcErr != nil { + return pcErr + } + + passUpdate := graphrbac.PasswordCredentialsUpdateParameters{ + Value: pc, + } + + _, err := client.UpdatePasswordCredentials(ctx, d.Id(), passUpdate) + if err != nil { + return err + } + + d.SetPartial("password_credential") + } + + d.Partial(false) + + return resourceArmAdApplicationRead(d, meta) +} + +func resourceArmAdApplicationDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).applicationsClient + ctx := meta.(*ArmClient).StopContext + + resp, err := client.Delete(ctx, d.Id()) + if err != nil { + if !utils.ResponseWasNotFound(resp) { + return err + } + } + + return nil +} + +func expandAzureRmAdApplicationHomepage(d *schema.ResourceData, name string) *string { + if v, ok := d.GetOk("homepage"); ok { + return utils.String(v.(string)) + } + + return utils.String(fmt.Sprintf("http://%s", name)) +} + +func expandAzureRmAdApplicationIdentifierUris(d *schema.ResourceData, name string) *[]string { + identifierUris := d.Get("identifier_uris").([]interface{}) + identifiers := []string{} + for _, id := range identifierUris { + identifiers = append(identifiers, id.(string)) + } + if len(identifiers) == 0 { + identifiers = append(identifiers, fmt.Sprintf("http://%s", name)) + } + + return &identifiers +} + +func expandAzureRmAdApplicationReplyUrls(d *schema.ResourceData, name string) *[]string { + replyUrls := d.Get("reply_urls").([]interface{}) + urls := []string{} + for _, url := range replyUrls { + urls = append(urls, url.(string)) + } + + return &urls +} diff --git a/azurerm/resource_arm_ad_application_test.go b/azurerm/resource_arm_ad_application_test.go new file mode 100644 index 000000000000..68a856fbbd93 --- /dev/null +++ b/azurerm/resource_arm_ad_application_test.go @@ -0,0 +1,533 @@ +package azurerm + +import ( + "fmt" + "regexp" + "testing" + "time" + + "github.com/google/uuid" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMAdApplication_simple(t *testing.T) { + resourceName := "azurerm_ad_application.test" + id := uuid.New().String() + config := testAccAzureRMAdApplication_simple(id) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "display_name", id), + resource.TestCheckResourceAttr(resourceName, "homepage", fmt.Sprintf("http://%s", id)), + resource.TestCheckResourceAttrSet(resourceName, "app_id"), + resource.TestCheckResourceAttrSet(resourceName, "object_id"), + ), + }, + }, + }) +} + +func TestAccAzureRMAdApplication_advanced(t *testing.T) { + resourceName := "azurerm_ad_application.test" + id := uuid.New().String() + config := testAccAzureRMAdApplication_advanced(id) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "display_name", id), + resource.TestCheckResourceAttr(resourceName, "homepage", fmt.Sprintf("http://homepage-%s", id)), + resource.TestCheckResourceAttrSet(resourceName, "app_id"), + resource.TestCheckResourceAttrSet(resourceName, "object_id"), + ), + }, + }, + }) +} + +func TestAccAzureRMAdApplication_updateAdvanced(t *testing.T) { + resourceName := "azurerm_ad_application.test" + id := uuid.New().String() + config := testAccAzureRMAdApplication_simple(id) + + updatedId := uuid.New().String() + updatedConfig := testAccAzureRMAdApplication_advanced(updatedId) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "display_name", id), + resource.TestCheckResourceAttr(resourceName, "homepage", fmt.Sprintf("http://%s", id)), + ), + }, + { + Config: updatedConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "display_name", updatedId), + resource.TestCheckResourceAttr(resourceName, "homepage", fmt.Sprintf("http://homepage-%s", updatedId)), + ), + }, + }, + }) +} + +func TestAccAzureRMAdApplication_keyCredential(t *testing.T) { + resourceName := "azurerm_ad_application.test" + id := uuid.New().String() + keyId := uuid.New().String() + config := testAccAzureRMAdApplication_keyCredential_single(id, keyId, "AsymmetricX509Cert") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersWithTLS, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "display_name", id), + resource.TestCheckResourceAttr(resourceName, "homepage", fmt.Sprintf("http://%s", id)), + resource.TestCheckResourceAttr(resourceName, "key_credential.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "app_id"), + resource.TestCheckResourceAttrSet(resourceName, "object_id"), + ), + }, + }, + }) +} + +func TestAccAzureRMAdApplication_updateKeyCredential_changeAttributes(t *testing.T) { + resourceName := "azurerm_ad_application.test" + id := uuid.New().String() + keyId := uuid.New().String() + keyId2 := uuid.New().String() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersWithTLS, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMAdApplication_keyCredential_single(id, keyId, "AsymmetricX509Cert"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "key_credential.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "app_id"), + resource.TestCheckResourceAttrSet(resourceName, "object_id"), + ), + }, + { + Config: testAccAzureRMAdApplication_keyCredential_single(id, keyId, "Symmetric"), + ExpectError: regexp.MustCompile(`Error: changing Key Credential properties on existing KeyID`), + }, + { + Config: testAccAzureRMAdApplication_keyCredential_single(id, keyId2, "Symmetric"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "key_credential.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "app_id"), + resource.TestCheckResourceAttrSet(resourceName, "object_id"), + ), + }, + }, + }) +} + +func TestAccAzureRMAdApplication_updateKeyCredential_changeCount(t *testing.T) { + resourceName := "azurerm_ad_application.test" + id := uuid.New().String() + keyId := uuid.New().String() + keyId2 := uuid.New().String() + configSingle := testAccAzureRMAdApplication_keyCredential_single(id, keyId, "AsymmetricX509Cert") + configDouble := testAccAzureRMAdApplication_keyCredential_double(id, keyId, keyId2) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersWithTLS, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: configSingle, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "display_name", id), + resource.TestCheckResourceAttr(resourceName, "key_credential.#", "1"), + ), + }, + { + Config: configDouble, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "display_name", id), + resource.TestCheckResourceAttr(resourceName, "key_credential.#", "2"), + ), + }, + { + Config: configSingle, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "display_name", id), + resource.TestCheckResourceAttr(resourceName, "key_credential.#", "1"), + ), + }, + }, + }) +} + +func TestAccAzureRMAdApplication_passwordCredential(t *testing.T) { + resourceName := "azurerm_ad_application.test" + id := uuid.New().String() + keyId := uuid.New().String() + timeStart := time.Now().UTC() + timeEnd := timeStart.Add(time.Duration(1) * time.Hour) + config := testAccAzureRMAdApplication_passwordCredential_single(id, keyId, timeStart, timeEnd) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "display_name", id), + resource.TestCheckResourceAttr(resourceName, "homepage", fmt.Sprintf("http://%s", id)), + resource.TestCheckResourceAttr(resourceName, "password_credential.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "app_id"), + resource.TestCheckResourceAttrSet(resourceName, "object_id"), + ), + }, + }, + }) +} + +func TestAccAzureRMAdApplication_updatePasswordCredential_changeAttributes(t *testing.T) { + resourceName := "azurerm_ad_application.test" + id := uuid.New().String() + keyId := uuid.New().String() + keyId2 := uuid.New().String() + timeStart := time.Now().UTC() + timeEnd := timeStart.Add(time.Duration(1) * time.Hour) + timeEnd2 := timeEnd.Add(time.Duration(1) * time.Hour) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMAdApplication_passwordCredential_single(id, keyId, timeStart, timeEnd), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "password_credential.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "app_id"), + resource.TestCheckResourceAttrSet(resourceName, "object_id"), + ), + }, + { + Config: testAccAzureRMAdApplication_passwordCredential_single(id, keyId, timeStart, timeEnd2), + ExpectError: regexp.MustCompile(`Error: changing Password Credential properties on existing KeyID`), + }, + { + Config: testAccAzureRMAdApplication_passwordCredential_single(id, keyId2, timeStart, timeEnd2), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "password_credential.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "app_id"), + resource.TestCheckResourceAttrSet(resourceName, "object_id"), + ), + }, + }, + }) +} + +func TestAccAzureRMAdApplication_updatePasswordCredential_changeCount(t *testing.T) { + resourceName := "azurerm_ad_application.test" + id := uuid.New().String() + keyId := uuid.New().String() + keyId2 := uuid.New().String() + timeStart := time.Now().UTC() + timeEnd := timeStart.Add(time.Duration(1) * time.Hour) + configSingle := testAccAzureRMAdApplication_passwordCredential_single(id, keyId, timeStart, timeEnd) + configDouble := testAccAzureRMAdApplication_passwordCredential_double(id, keyId, keyId2, timeStart, timeEnd) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAdApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: configSingle, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "password_credential.#", "1"), + ), + }, + { + Config: configDouble, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "password_credential.#", "2"), + ), + }, + { + Config: configSingle, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAdApplicationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "password_credential.#", "1"), + ), + }, + }, + }) +} + +func testCheckAzureRMAdApplicationExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %q", name) + } + + objectId := rs.Primary.Attributes["object_id"] + + client := testAccProvider.Meta().(*ArmClient).applicationsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + resp, err := client.Get(ctx, objectId) + + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: AD Application %q does not exist", objectId) + } + return fmt.Errorf("Bad: Get on applicationsClient: %+v", err) + } + + return nil + } +} + +func testCheckAzureRMAdApplicationDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_ad_application" { + continue + } + + objectId := rs.Primary.Attributes["object_id"] + + client := testAccProvider.Meta().(*ArmClient).applicationsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + resp, err := client.Get(ctx, objectId) + + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return nil + } + + return err + } + + return fmt.Errorf("AD Application still exists:\n%#v", resp) + } + + return nil +} + +func testAccAzureRMAdApplication_simple(id string) string { + return fmt.Sprintf(` +resource "azurerm_ad_application" "test" { + display_name = "%s" +} +`, id) +} + +func testAccAzureRMAdApplication_advanced(id string) string { + return fmt.Sprintf(` +resource "azurerm_ad_application" "test" { + display_name = "%s" + homepage = "http://homepage-%s" + identifier_uris = ["http://uri-%s"] + reply_urls = ["http://replyurl-%s"] + available_to_other_tenants = false + oauth2_allow_implicit_flow = true +} +`, id, id, id, id) +} + +func testAccAzureRMAdApplication_keyCredential_single(id string, keyId string, usage string) string { + return fmt.Sprintf(` +resource "tls_private_key" "test" { + algorithm = "ECDSA" + ecdsa_curve = "P384" +} + +resource "tls_self_signed_cert" "test" { + key_algorithm = "${tls_private_key.test.algorithm}" + private_key_pem = "${tls_private_key.test.private_key_pem}" + + subject { + common_name = "example.com" + organization = "ACME Examples, Inc" + } + + validity_period_hours = 12 + + allowed_uses = [ + "key_encipherment", + "digital_signature", + "server_auth", + "cert_signing", + ] +} + +resource "azurerm_ad_application" "test" { + display_name = "%s" + + key_credential { + key_id = "%s" + type = "%s" + usage = "Verify" + start_date = "${tls_self_signed_cert.test.validity_start_time}" + end_date = "${tls_self_signed_cert.test.validity_end_time}" + value = "${tls_self_signed_cert.test.cert_pem}" + } +} +`, id, keyId, usage) +} + +func testAccAzureRMAdApplication_keyCredential_double(id string, keyId string, keyId2 string) string { + return fmt.Sprintf(` +resource "tls_private_key" "test" { + algorithm = "ECDSA" + ecdsa_curve = "P384" +} + +resource "tls_self_signed_cert" "test" { + key_algorithm = "${tls_private_key.test.algorithm}" + private_key_pem = "${tls_private_key.test.private_key_pem}" + + subject { + common_name = "example.com" + organization = "ACME Examples, Inc" + } + + validity_period_hours = 12 + + allowed_uses = [ + "key_encipherment", + "digital_signature", + "server_auth", + "cert_signing", + ] +} + +resource "tls_private_key" "test2" { + algorithm = "ECDSA" + ecdsa_curve = "P384" +} + +resource "tls_self_signed_cert" "test2" { + key_algorithm = "${tls_private_key.test2.algorithm}" + private_key_pem = "${tls_private_key.test2.private_key_pem}" + + subject { + common_name = "example.com" + organization = "ACME Examples, Inc" + } + + validity_period_hours = 12 + + allowed_uses = [ + "key_encipherment", + "digital_signature", + "server_auth", + "cert_signing", + ] +} + +resource "azurerm_ad_application" "test" { + display_name = "%s" + + key_credential { + key_id = "%s" + type = "AsymmetricX509Cert" + usage = "Verify" + start_date = "${tls_self_signed_cert.test.validity_start_time}" + end_date = "${tls_self_signed_cert.test.validity_end_time}" + value = "${tls_self_signed_cert.test.cert_pem}" + } + + key_credential { + key_id = "%s" + type = "AsymmetricX509Cert" + usage = "Verify" + start_date = "${tls_self_signed_cert.test2.validity_start_time}" + end_date = "${tls_self_signed_cert.test2.validity_end_time}" + value = "${tls_self_signed_cert.test2.cert_pem}" + } +} +`, id, keyId, keyId2) +} + +func testAccAzureRMAdApplication_passwordCredential_single(id string, keyId string, timeStart time.Time, timeEnd time.Time) string { + ts := string(timeStart.Format(time.RFC3339)) + te := string(timeEnd.Format(time.RFC3339)) + return fmt.Sprintf(` +resource "azurerm_ad_application" "test" { + display_name = "%s" + + password_credential { + key_id = "%s" + value = "test" + start_date = "%s" + end_date = "%s" + } +} +`, id, keyId, ts, te) +} + +func testAccAzureRMAdApplication_passwordCredential_double(id string, keyId string, keyId2 string, timeStart time.Time, timeEnd time.Time) string { + ts := string(timeStart.Format(time.RFC3339)) + te := string(timeEnd.Format(time.RFC3339)) + return fmt.Sprintf(` +resource "azurerm_ad_application" "test" { + display_name = "%s" + + password_credential { + key_id = "%s" + value = "test" + start_date = "%s" + end_date = "%s" + } + + password_credential { + key_id = "%s" + value = "test" + start_date = "%s" + end_date = "%s" + } +} +`, id, keyId, ts, te, keyId2, ts, te) +} diff --git a/azurerm/resource_arm_service_principal.go b/azurerm/resource_arm_service_principal.go new file mode 100644 index 000000000000..e80baa96fddd --- /dev/null +++ b/azurerm/resource_arm_service_principal.go @@ -0,0 +1,105 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" + "github.com/hashicorp/terraform/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmServicePrincipal() *schema.Resource { + return &schema.Resource{ + Create: resourceArmServicePrincipalCreate, + Read: resourceArmServicePrincipalRead, + Delete: resourceArmServicePrincipalDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "app_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateUUID, + }, + + "object_id": { + Type: schema.TypeString, + Computed: true, + }, + + "display_name": { + Type: schema.TypeString, + Computed: true, + }, + + "service_principal_names": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + } +} + +func resourceArmServicePrincipalCreate(d *schema.ResourceData, meta interface{}) error { + servicePrincipalsClient := meta.(*ArmClient).servicePrincipalsClient + ctx := meta.(*ArmClient).StopContext + + appId := d.Get("app_id").(string) + + properties := graphrbac.ServicePrincipalCreateParameters{ + AppID: &appId, + AccountEnabled: utils.Bool(true), + } + + spn, err := servicePrincipalsClient.Create(ctx, properties) + if err != nil { + return err + } + + d.SetId(*spn.ObjectID) + return resourceArmServicePrincipalRead(d, meta) +} + +func resourceArmServicePrincipalRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).servicePrincipalsClient + ctx := meta.(*ArmClient).StopContext + + resp, err := client.Get(ctx, d.Id()) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[DEBUG] Service Principal ID %q was not found - removing from state", d.Id()) + d.SetId("") + return nil + } + + return fmt.Errorf("Error loading Service Principal %q: %+v", d.Id(), err) + } + + d.Set("app_id", resp.AppID) + d.Set("object_id", resp.ObjectID) + d.Set("display_name", resp.DisplayName) + d.Set("service_principal_names", resp.ServicePrincipalNames) + + return nil +} + +func resourceArmServicePrincipalDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).servicePrincipalsClient + ctx := meta.(*ArmClient).StopContext + + resp, err := client.Delete(ctx, d.Id()) + if err != nil { + if !utils.ResponseWasNotFound(resp) { + return err + } + } + + return nil +} diff --git a/azurerm/resource_arm_service_principal_test.go b/azurerm/resource_arm_service_principal_test.go new file mode 100644 index 000000000000..190030e9c8c3 --- /dev/null +++ b/azurerm/resource_arm_service_principal_test.go @@ -0,0 +1,95 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/google/uuid" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMServicePrincipal_simple(t *testing.T) { + resourceName := "azurerm_service_principal.test" + id := uuid.New().String() + config := testAccAzureRMServicePrincipal_simple(id) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServicePrincipalDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServicePrincipalExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "object_id"), + resource.TestCheckResourceAttr(resourceName, "display_name", id), + ), + }, + }, + }) +} + +func testCheckAzureRMServicePrincipalExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %q", name) + } + + objectId := rs.Primary.Attributes["object_id"] + + client := testAccProvider.Meta().(*ArmClient).servicePrincipalsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + resp, err := client.Get(ctx, objectId) + + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Service Principal %q does not exist", objectId) + } + return fmt.Errorf("Bad: Get on servicePrincipalsClient: %+v", err) + } + + return nil + } +} + +func testCheckAzureRMServicePrincipalDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_service_principal" { + continue + } + + objectId := rs.Primary.Attributes["object_id"] + + client := testAccProvider.Meta().(*ArmClient).servicePrincipalsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + resp, err := client.Get(ctx, objectId) + + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return nil + } + + return err + } + + return fmt.Errorf("Service Principal still exists:\n%#v", resp) + } + + return nil +} + +func testAccAzureRMServicePrincipal_simple(id string) string { + return fmt.Sprintf(` +resource "azurerm_ad_application" "test" { + display_name = "%s" +} + +resource "azurerm_service_principal" "test" { + app_id = "${azurerm_ad_application.test.app_id}" +} +`, id) +} diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/CHANGELOG.md b/vendor/github.com/terraform-providers/terraform-provider-tls/CHANGELOG.md new file mode 100644 index 000000000000..2c7c3b46a7f2 --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/CHANGELOG.md @@ -0,0 +1,23 @@ +## 1.2.0 (Unreleased) +## 1.1.0 (March 09, 2018) + +FEATURES: + +* **New Data Source:** `tls_public_key` ([#11](https://github.com/terraform-providers/terraform-provider-tls/issues/11)) + +## 1.0.1 (November 09, 2017) + +BUG FIXES: + +* `tls_cert_request` and `tls_self_signed_cert` no longer cause a crash when `subject` isn't specified. ([#7](https://github.com/terraform-providers/terraform-provider-tls/issues/7)) +* `tls_cert_request` and `tls_self_signed_cert` no longer generate empty-string values for various subject fields when they are not set in configuration. ([#10](https://github.com/terraform-providers/terraform-provider-tls/issues/10)) + +## 1.0.0 (September 15, 2017) + +* No changes from 0.1.0; just adjusting to [the new version numbering scheme](https://www.hashicorp.com/blog/hashicorp-terraform-provider-versioning/). + +## 0.1.0 (June 21, 2017) + +NOTES: + +* Same functionality as that of Terraform 0.9.8. Repacked as part of [Provider Splitout](https://www.hashicorp.com/blog/upcoming-provider-changes-in-terraform-0-10/) diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/GNUmakefile b/vendor/github.com/terraform-providers/terraform-provider-tls/GNUmakefile new file mode 100644 index 000000000000..c9eacb4511da --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/GNUmakefile @@ -0,0 +1,47 @@ +TEST?=$$(go list ./... |grep -v 'vendor') +GOFMT_FILES?=$$(find . -name '*.go' |grep -v vendor) + +default: build + +build: fmtcheck + go install + +test: fmtcheck + go test -i $(TEST) || exit 1 + echo $(TEST) | \ + xargs -t -n4 go test $(TESTARGS) -timeout=30s -parallel=4 + +testacc: fmtcheck + TF_ACC=1 go test $(TEST) -v $(TESTARGS) -timeout 120m + +vet: + @echo "go vet ." + @go vet $$(go list ./... | grep -v vendor/) ; if [ $$? -eq 1 ]; then \ + echo ""; \ + echo "Vet found suspicious constructs. Please check the reported constructs"; \ + echo "and fix them if necessary before submitting the code for review."; \ + exit 1; \ + fi + +fmt: + gofmt -w $(GOFMT_FILES) + +fmtcheck: + @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" + +errcheck: + @sh -c "'$(CURDIR)/scripts/errcheck.sh'" + +vendor-status: + @govendor status + +test-compile: + @if [ "$(TEST)" = "./..." ]; then \ + echo "ERROR: Set TEST to a specific package. For example,"; \ + echo " make test-compile TEST=./aws"; \ + exit 1; \ + fi + go test -c $(TEST) $(TESTARGS) + +.PHONY: build test testacc vet fmt fmtcheck errcheck vendor-status test-compile + diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/LICENSE b/vendor/github.com/terraform-providers/terraform-provider-tls/LICENSE new file mode 100644 index 000000000000..a612ad9813b0 --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/README.md b/vendor/github.com/terraform-providers/terraform-provider-tls/README.md new file mode 100644 index 000000000000..de597d2348a5 --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/README.md @@ -0,0 +1,68 @@ +Terraform Provider +================== + +- Website: https://www.terraform.io +- [![Gitter chat](https://badges.gitter.im/hashicorp-terraform/Lobby.png)](https://gitter.im/hashicorp-terraform/Lobby) +- Mailing list: [Google Groups](http://groups.google.com/group/terraform-tool) + + + +Maintainers +----------- + +This provider plugin is maintained by the Terraform team at [HashiCorp](https://www.hashicorp.com/). + +Requirements +------------ + +- [Terraform](https://www.terraform.io/downloads.html) 0.10.x +- [Go](https://golang.org/doc/install) 1.8 (to build the provider plugin) + +Building The Provider +--------------------- + +Clone repository to: `$GOPATH/src/github.com/hashicorp/terraform-provider-$PROVIDER_NAME` + +```sh +$ mkdir -p $GOPATH/src/github.com/hashicorp; cd $GOPATH/src/github.com/hashicorp +$ git clone git@github.com:hashicorp/terraform-provider-$PROVIDER_NAME +``` + +Enter the provider directory and build the provider + +```sh +$ cd $GOPATH/src/github.com/hashicorp/terraform-provider-$PROVIDER_NAME +$ make build +``` + +Using the provider +---------------------- +## Fill in for each provider + +Developing the Provider +--------------------------- + +If you wish to work on the provider, you'll first need [Go](http://www.golang.org) installed on your machine (version 1.8+ is *required*). You'll also need to correctly setup a [GOPATH](http://golang.org/doc/code.html#GOPATH), as well as adding `$GOPATH/bin` to your `$PATH`. + +To compile the provider, run `make build`. This will build the provider and put the provider binary in the `$GOPATH/bin` directory. + +```sh +$ make bin +... +$ $GOPATH/bin/terraform-provider-$PROVIDER_NAME +... +``` + +In order to test the provider, you can simply run `make test`. + +```sh +$ make test +``` + +In order to run the full suite of Acceptance tests, run `make testacc`. + +*Note:* Acceptance tests create real resources, and often cost money to run. + +```sh +$ make testacc +``` diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/main.go b/vendor/github.com/terraform-providers/terraform-provider-tls/main.go new file mode 100644 index 000000000000..ea2843e7e694 --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/main.go @@ -0,0 +1,11 @@ +package main + +import ( + "github.com/hashicorp/terraform/plugin" + "github.com/terraform-providers/terraform-provider-tls/tls" +) + +func main() { + plugin.Serve(&plugin.ServeOpts{ + ProviderFunc: tls.Provider}) +} diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/tls/data_source_public_key.go b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/data_source_public_key.go new file mode 100644 index 000000000000..42a7ac74f017 --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/data_source_public_key.go @@ -0,0 +1,66 @@ +package tls + +import ( + "encoding/pem" + "fmt" + + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourcePublicKey() *schema.Resource { + return &schema.Resource{ + Read: dataSourcePublicKeyRead, + Schema: map[string]*schema.Schema{ + "private_key_pem": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "PEM formatted string to use as the private key", + }, + "algorithm": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Name of the algorithm to use to generate the private key", + }, + "public_key_pem": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "public_key_openssh": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourcePublicKeyRead(d *schema.ResourceData, meta interface{}) error { + // Read private key + bytes := []byte("") + if v, ok := d.GetOk("private_key_pem"); ok { + bytes = []byte(v.(string)) + } else { + return fmt.Errorf("invalid private key %#v", v) + } + // decode PEM encoding to ANS.1 PKCS1 DER + keyPemBlock, _ := pem.Decode(bytes) + + if keyPemBlock == nil || (keyPemBlock.Type != "RSA PRIVATE KEY" && keyPemBlock.Type != "EC PRIVATE KEY") { + return fmt.Errorf("failed to decode PEM block containing private key of type %#v", keyPemBlock.Type) + } + + keyAlgo := "" + switch keyPemBlock.Type { + case "RSA PRIVATE KEY": + keyAlgo = "RSA" + case "EC PRIVATE KEY": + keyAlgo = "ECDSA" + } + d.Set("algorithm", keyAlgo) + // Converts a private key from its ASN.1 PKCS#1 DER encoded form + key, err := parsePrivateKey(d, "private_key_pem", "algorithm") + if err != nil { + return fmt.Errorf("error converting key to algo: %s - %s", keyAlgo, err) + } + + return readPublicKey(d, key) +} diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/tls/provider.go b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/provider.go new file mode 100644 index 000000000000..b145c341d965 --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/provider.go @@ -0,0 +1,114 @@ +package tls + +import ( + "crypto/sha1" + "crypto/x509/pkix" + "encoding/hex" + "strings" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +func Provider() terraform.ResourceProvider { + return &schema.Provider{ + ResourcesMap: map[string]*schema.Resource{ + "tls_private_key": resourcePrivateKey(), + "tls_locally_signed_cert": resourceLocallySignedCert(), + "tls_self_signed_cert": resourceSelfSignedCert(), + "tls_cert_request": resourceCertRequest(), + }, + DataSourcesMap: map[string]*schema.Resource{ + "tls_public_key": dataSourcePublicKey(), + }, + } +} + +func hashForState(value string) string { + if value == "" { + return "" + } + hash := sha1.Sum([]byte(strings.TrimSpace(value))) + return hex.EncodeToString(hash[:]) +} + +func nameFromResourceData(nameMap map[string]interface{}) (*pkix.Name, error) { + result := &pkix.Name{} + + if value := nameMap["common_name"]; value != "" { + result.CommonName = value.(string) + } + if value := nameMap["organization"]; value != "" { + result.Organization = []string{value.(string)} + } + if value := nameMap["organizational_unit"]; value != "" { + result.OrganizationalUnit = []string{value.(string)} + } + if value := nameMap["street_address"].([]interface{}); len(value) > 0 { + result.StreetAddress = make([]string, len(value)) + for i, vi := range value { + result.StreetAddress[i] = vi.(string) + } + } + if value := nameMap["locality"]; value != "" { + result.Locality = []string{value.(string)} + } + if value := nameMap["province"]; value != "" { + result.Province = []string{value.(string)} + } + if value := nameMap["country"]; value != "" { + result.Country = []string{value.(string)} + } + if value := nameMap["postal_code"]; value != "" { + result.PostalCode = []string{value.(string)} + } + if value := nameMap["serial_number"]; value != "" { + result.SerialNumber = value.(string) + } + + return result, nil +} + +var nameSchema *schema.Resource = &schema.Resource{ + Schema: map[string]*schema.Schema{ + "organization": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "common_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "organizational_unit": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "street_address": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "locality": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "province": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "country": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "postal_code": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "serial_number": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + }, +} diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_cert_request.go b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_cert_request.go new file mode 100644 index 000000000000..22cc62424d4d --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_cert_request.go @@ -0,0 +1,130 @@ +package tls + +import ( + "crypto/rand" + "crypto/x509" + "encoding/pem" + "fmt" + "net" + + "github.com/hashicorp/terraform/helper/schema" +) + +const pemCertReqType = "CERTIFICATE REQUEST" + +func resourceCertRequest() *schema.Resource { + return &schema.Resource{ + Create: CreateCertRequest, + Delete: DeleteCertRequest, + Read: ReadCertRequest, + + Schema: map[string]*schema.Schema{ + + "dns_names": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "List of DNS names to use as subjects of the certificate", + ForceNew: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "ip_addresses": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "List of IP addresses to use as subjects of the certificate", + ForceNew: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "key_algorithm": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Name of the algorithm to use to generate the certificate's private key", + ForceNew: true, + }, + + "private_key_pem": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "PEM-encoded private key that the certificate will belong to", + ForceNew: true, + StateFunc: func(v interface{}) string { + return hashForState(v.(string)) + }, + }, + + "subject": &schema.Schema{ + Type: schema.TypeList, + Required: true, + Elem: nameSchema, + ForceNew: true, + }, + + "cert_request_pem": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func CreateCertRequest(d *schema.ResourceData, meta interface{}) error { + key, err := parsePrivateKey(d, "private_key_pem", "key_algorithm") + if err != nil { + return err + } + + subjectConfs := d.Get("subject").([]interface{}) + if len(subjectConfs) != 1 { + return fmt.Errorf("must have exactly one 'subject' block") + } + subjectConf, ok := subjectConfs[0].(map[string]interface{}) + if !ok { + return fmt.Errorf("subject block cannot be empty") + } + subject, err := nameFromResourceData(subjectConf) + if err != nil { + return fmt.Errorf("invalid subject block: %s", err) + } + + certReq := x509.CertificateRequest{ + Subject: *subject, + } + + dnsNamesI := d.Get("dns_names").([]interface{}) + for _, nameI := range dnsNamesI { + certReq.DNSNames = append(certReq.DNSNames, nameI.(string)) + } + ipAddressesI := d.Get("ip_addresses").([]interface{}) + for _, ipStrI := range ipAddressesI { + ip := net.ParseIP(ipStrI.(string)) + if ip == nil { + return fmt.Errorf("invalid IP address %#v", ipStrI.(string)) + } + certReq.IPAddresses = append(certReq.IPAddresses, ip) + } + + certReqBytes, err := x509.CreateCertificateRequest(rand.Reader, &certReq, key) + if err != nil { + return fmt.Errorf("Error creating certificate request: %s", err) + } + certReqPem := string(pem.EncodeToMemory(&pem.Block{Type: pemCertReqType, Bytes: certReqBytes})) + + d.SetId(hashForState(string(certReqBytes))) + d.Set("cert_request_pem", certReqPem) + + return nil +} + +func DeleteCertRequest(d *schema.ResourceData, meta interface{}) error { + d.SetId("") + return nil +} + +func ReadCertRequest(d *schema.ResourceData, meta interface{}) error { + return nil +} diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_certificate.go b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_certificate.go new file mode 100644 index 000000000000..d30efa7204da --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_certificate.go @@ -0,0 +1,210 @@ +package tls + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/sha1" + "crypto/x509" + "encoding/asn1" + "encoding/pem" + "errors" + "fmt" + "math/big" + "time" + + "github.com/hashicorp/terraform/helper/schema" +) + +const pemCertType = "CERTIFICATE" + +var keyUsages map[string]x509.KeyUsage = map[string]x509.KeyUsage{ + "digital_signature": x509.KeyUsageDigitalSignature, + "content_commitment": x509.KeyUsageContentCommitment, + "key_encipherment": x509.KeyUsageKeyEncipherment, + "data_encipherment": x509.KeyUsageDataEncipherment, + "key_agreement": x509.KeyUsageKeyAgreement, + "cert_signing": x509.KeyUsageCertSign, + "crl_signing": x509.KeyUsageCRLSign, + "encipher_only": x509.KeyUsageEncipherOnly, + "decipher_only": x509.KeyUsageDecipherOnly, +} + +var extKeyUsages map[string]x509.ExtKeyUsage = map[string]x509.ExtKeyUsage{ + "any_extended": x509.ExtKeyUsageAny, + "server_auth": x509.ExtKeyUsageServerAuth, + "client_auth": x509.ExtKeyUsageClientAuth, + "code_signing": x509.ExtKeyUsageCodeSigning, + "email_protection": x509.ExtKeyUsageEmailProtection, + "ipsec_end_system": x509.ExtKeyUsageIPSECEndSystem, + "ipsec_tunnel": x509.ExtKeyUsageIPSECTunnel, + "ipsec_user": x509.ExtKeyUsageIPSECUser, + "timestamping": x509.ExtKeyUsageTimeStamping, + "ocsp_signing": x509.ExtKeyUsageOCSPSigning, + "microsoft_server_gated_crypto": x509.ExtKeyUsageMicrosoftServerGatedCrypto, + "netscape_server_gated_crypto": x509.ExtKeyUsageNetscapeServerGatedCrypto, +} + +// rsaPublicKey reflects the ASN.1 structure of a PKCS#1 public key. +type rsaPublicKey struct { + N *big.Int + E int +} + +// generateSubjectKeyID generates a SHA-1 hash of the subject public key. +func generateSubjectKeyID(pub crypto.PublicKey) ([]byte, error) { + var publicKeyBytes []byte + var err error + + switch pub := pub.(type) { + case *rsa.PublicKey: + publicKeyBytes, err = asn1.Marshal(rsaPublicKey{N: pub.N, E: pub.E}) + if err != nil { + return nil, err + } + case *ecdsa.PublicKey: + publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) + default: + return nil, errors.New("only RSA and ECDSA public keys supported") + } + + hash := sha1.Sum(publicKeyBytes) + return hash[:], nil +} + +func resourceCertificateCommonSchema() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "validity_period_hours": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + Description: "Number of hours that the certificate will remain valid for", + ForceNew: true, + }, + + "early_renewal_hours": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Default: 0, + Description: "Number of hours before the certificates expiry when a new certificate will be generated", + ForceNew: true, + }, + + "is_ca_certificate": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Description: "Whether the generated certificate will be usable as a CA certificate", + ForceNew: true, + }, + + "allowed_uses": &schema.Schema{ + Type: schema.TypeList, + Required: true, + Description: "Uses that are allowed for the certificate", + ForceNew: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "cert_pem": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "validity_start_time": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "validity_end_time": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + } +} + +func createCertificate(d *schema.ResourceData, template, parent *x509.Certificate, pub crypto.PublicKey, priv interface{}) error { + var err error + + template.NotBefore = time.Now() + template.NotAfter = template.NotBefore.Add(time.Duration(d.Get("validity_period_hours").(int)) * time.Hour) + + serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) + template.SerialNumber, err = rand.Int(rand.Reader, serialNumberLimit) + if err != nil { + return fmt.Errorf("failed to generate serial number: %s", err) + } + + keyUsesI := d.Get("allowed_uses").([]interface{}) + for _, keyUseI := range keyUsesI { + keyUse := keyUseI.(string) + if usage, ok := keyUsages[keyUse]; ok { + template.KeyUsage |= usage + } + if usage, ok := extKeyUsages[keyUse]; ok { + template.ExtKeyUsage = append(template.ExtKeyUsage, usage) + } + } + + if d.Get("is_ca_certificate").(bool) { + template.IsCA = true + + template.SubjectKeyId, err = generateSubjectKeyID(pub) + if err != nil { + return fmt.Errorf("failed to set subject key identifier: %s", err) + } + } + + certBytes, err := x509.CreateCertificate(rand.Reader, template, parent, pub, priv) + if err != nil { + return fmt.Errorf("error creating certificate: %s", err) + } + certPem := string(pem.EncodeToMemory(&pem.Block{Type: pemCertType, Bytes: certBytes})) + + validFromBytes, err := template.NotBefore.MarshalText() + if err != nil { + return fmt.Errorf("error serializing validity_start_time: %s", err) + } + validToBytes, err := template.NotAfter.MarshalText() + if err != nil { + return fmt.Errorf("error serializing validity_end_time: %s", err) + } + + d.SetId(template.SerialNumber.String()) + d.Set("cert_pem", certPem) + d.Set("validity_start_time", string(validFromBytes)) + d.Set("validity_end_time", string(validToBytes)) + + return nil +} + +func DeleteCertificate(d *schema.ResourceData, meta interface{}) error { + d.SetId("") + return nil +} + +func ReadCertificate(d *schema.ResourceData, meta interface{}) error { + + endTimeStr := d.Get("validity_end_time").(string) + endTime := time.Now() + err := endTime.UnmarshalText([]byte(endTimeStr)) + if err != nil { + // If end time is invalid then we'll just throw away the whole + // thing so we can generate a new one. + d.SetId("") + return nil + } + + earlyRenewalPeriod := time.Duration(-d.Get("early_renewal_hours").(int)) * time.Hour + endTime = endTime.Add(earlyRenewalPeriod) + + if time.Now().After(endTime) { + // Treat an expired certificate as not existing, so we'll generate + // a new one with the next plan. + d.SetId("") + } + + return nil +} diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_locally_signed_cert.go b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_locally_signed_cert.go new file mode 100644 index 000000000000..39c90022f8d3 --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_locally_signed_cert.go @@ -0,0 +1,79 @@ +package tls + +import ( + "crypto/x509" + + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceLocallySignedCert() *schema.Resource { + s := resourceCertificateCommonSchema() + + s["cert_request_pem"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "PEM-encoded certificate request", + ForceNew: true, + StateFunc: func(v interface{}) string { + return hashForState(v.(string)) + }, + } + + s["ca_key_algorithm"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Name of the algorithm used to generate the certificate's private key", + ForceNew: true, + } + + s["ca_private_key_pem"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "PEM-encoded CA private key used to sign the certificate", + ForceNew: true, + StateFunc: func(v interface{}) string { + return hashForState(v.(string)) + }, + } + + s["ca_cert_pem"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "PEM-encoded CA certificate", + ForceNew: true, + StateFunc: func(v interface{}) string { + return hashForState(v.(string)) + }, + } + + return &schema.Resource{ + Create: CreateLocallySignedCert, + Delete: DeleteCertificate, + Read: ReadCertificate, + Schema: s, + } +} + +func CreateLocallySignedCert(d *schema.ResourceData, meta interface{}) error { + certReq, err := parseCertificateRequest(d, "cert_request_pem") + if err != nil { + return err + } + caKey, err := parsePrivateKey(d, "ca_private_key_pem", "ca_key_algorithm") + if err != nil { + return err + } + caCert, err := parseCertificate(d, "ca_cert_pem") + if err != nil { + return err + } + + cert := x509.Certificate{ + Subject: certReq.Subject, + DNSNames: certReq.DNSNames, + IPAddresses: certReq.IPAddresses, + BasicConstraintsValid: true, + } + + return createCertificate(d, &cert, caCert, certReq.PublicKey, caKey) +} diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_private_key.go b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_private_key.go new file mode 100644 index 000000000000..84e4c18db90a --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_private_key.go @@ -0,0 +1,154 @@ +package tls + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "fmt" + + "github.com/hashicorp/terraform/helper/schema" +) + +type keyAlgo func(d *schema.ResourceData) (interface{}, error) +type keyParser func([]byte) (interface{}, error) + +var keyAlgos map[string]keyAlgo = map[string]keyAlgo{ + "RSA": func(d *schema.ResourceData) (interface{}, error) { + rsaBits := d.Get("rsa_bits").(int) + return rsa.GenerateKey(rand.Reader, rsaBits) + }, + "ECDSA": func(d *schema.ResourceData) (interface{}, error) { + curve := d.Get("ecdsa_curve").(string) + switch curve { + case "P224": + return ecdsa.GenerateKey(elliptic.P224(), rand.Reader) + case "P256": + return ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + case "P384": + return ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + case "P521": + return ecdsa.GenerateKey(elliptic.P521(), rand.Reader) + default: + return nil, fmt.Errorf("invalid ecdsa_curve; must be P224, P256, P384 or P521") + } + }, +} + +var keyParsers map[string]keyParser = map[string]keyParser{ + "RSA": func(der []byte) (interface{}, error) { + return x509.ParsePKCS1PrivateKey(der) + }, + "ECDSA": func(der []byte) (interface{}, error) { + return x509.ParseECPrivateKey(der) + }, +} + +func resourcePrivateKey() *schema.Resource { + return &schema.Resource{ + Create: CreatePrivateKey, + Delete: DeletePrivateKey, + Read: ReadPrivateKey, + + Schema: map[string]*schema.Schema{ + "algorithm": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Name of the algorithm to use to generate the private key", + ForceNew: true, + }, + + "rsa_bits": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Number of bits to use when generating an RSA key", + ForceNew: true, + Default: 2048, + }, + + "ecdsa_curve": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "ECDSA curve to use when generating a key", + ForceNew: true, + Default: "P224", + }, + + "private_key_pem": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "public_key_pem": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "public_key_openssh": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func CreatePrivateKey(d *schema.ResourceData, meta interface{}) error { + keyAlgoName := d.Get("algorithm").(string) + var keyFunc keyAlgo + var ok bool + if keyFunc, ok = keyAlgos[keyAlgoName]; !ok { + return fmt.Errorf("invalid key_algorithm %#v", keyAlgoName) + } + + key, err := keyFunc(d) + if err != nil { + return err + } + + var keyPemBlock *pem.Block + switch k := key.(type) { + case *rsa.PrivateKey: + keyPemBlock = &pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(k), + } + case *ecdsa.PrivateKey: + keyBytes, err := x509.MarshalECPrivateKey(k) + if err != nil { + return fmt.Errorf("error encoding key to PEM: %s", err) + } + keyPemBlock = &pem.Block{ + Type: "EC PRIVATE KEY", + Bytes: keyBytes, + } + default: + return fmt.Errorf("unsupported private key type") + } + keyPem := string(pem.EncodeToMemory(keyPemBlock)) + + d.Set("private_key_pem", keyPem) + + return readPublicKey(d, key) +} + +func DeletePrivateKey(d *schema.ResourceData, meta interface{}) error { + d.SetId("") + return nil +} + +func ReadPrivateKey(d *schema.ResourceData, meta interface{}) error { + return nil +} + +func publicKey(priv interface{}) interface{} { + switch k := priv.(type) { + case *rsa.PrivateKey: + return &k.PublicKey + case *ecdsa.PrivateKey: + return &k.PublicKey + default: + return nil + } +} diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_self_signed_cert.go b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_self_signed_cert.go new file mode 100644 index 000000000000..c6edf7e4be93 --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/resource_self_signed_cert.go @@ -0,0 +1,104 @@ +package tls + +import ( + "crypto/x509" + "fmt" + "net" + + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceSelfSignedCert() *schema.Resource { + s := resourceCertificateCommonSchema() + + s["subject"] = &schema.Schema{ + Type: schema.TypeList, + Required: true, + Elem: nameSchema, + ForceNew: true, + } + + s["dns_names"] = &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "List of DNS names to use as subjects of the certificate", + ForceNew: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + } + + s["ip_addresses"] = &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "List of IP addresses to use as subjects of the certificate", + ForceNew: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + } + + s["key_algorithm"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Name of the algorithm to use to generate the certificate's private key", + ForceNew: true, + } + + s["private_key_pem"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "PEM-encoded private key that the certificate will belong to", + ForceNew: true, + StateFunc: func(v interface{}) string { + return hashForState(v.(string)) + }, + } + + return &schema.Resource{ + Create: CreateSelfSignedCert, + Delete: DeleteCertificate, + Read: ReadCertificate, + Schema: s, + } +} + +func CreateSelfSignedCert(d *schema.ResourceData, meta interface{}) error { + key, err := parsePrivateKey(d, "private_key_pem", "key_algorithm") + if err != nil { + return err + } + + subjectConfs := d.Get("subject").([]interface{}) + if len(subjectConfs) != 1 { + return fmt.Errorf("must have exactly one 'subject' block") + } + subjectConf, ok := subjectConfs[0].(map[string]interface{}) + if !ok { + return fmt.Errorf("subject block cannot be empty") + } + subject, err := nameFromResourceData(subjectConf) + if err != nil { + return fmt.Errorf("invalid subject block: %s", err) + } + + cert := x509.Certificate{ + Subject: *subject, + BasicConstraintsValid: true, + } + + dnsNamesI := d.Get("dns_names").([]interface{}) + for _, nameI := range dnsNamesI { + cert.DNSNames = append(cert.DNSNames, nameI.(string)) + } + ipAddressesI := d.Get("ip_addresses").([]interface{}) + for _, ipStrI := range ipAddressesI { + ip := net.ParseIP(ipStrI.(string)) + if ip == nil { + return fmt.Errorf("invalid IP address %#v", ipStrI.(string)) + } + cert.IPAddresses = append(cert.IPAddresses, ip) + } + + return createCertificate(d, &cert, &cert, publicKey(key), key) +} diff --git a/vendor/github.com/terraform-providers/terraform-provider-tls/tls/util.go b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/util.go new file mode 100644 index 000000000000..34daa3581358 --- /dev/null +++ b/vendor/github.com/terraform-providers/terraform-provider-tls/tls/util.go @@ -0,0 +1,103 @@ +package tls + +import ( + "crypto/x509" + "encoding/pem" + "fmt" + + "github.com/hashicorp/terraform/helper/schema" + "golang.org/x/crypto/ssh" +) + +func decodePEM(d *schema.ResourceData, pemKey, pemType string) (*pem.Block, error) { + block, _ := pem.Decode([]byte(d.Get(pemKey).(string))) + if block == nil { + return nil, fmt.Errorf("no PEM block found in %s", pemKey) + } + if pemType != "" && block.Type != pemType { + return nil, fmt.Errorf("invalid PEM type in %s: %s", pemKey, block.Type) + } + + return block, nil +} + +func parsePrivateKey(d *schema.ResourceData, pemKey, algoKey string) (interface{}, error) { + algoName := d.Get(algoKey).(string) + + keyFunc, ok := keyParsers[algoName] + if !ok { + return nil, fmt.Errorf("invalid %s: %#v", algoKey, algoName) + } + + block, err := decodePEM(d, pemKey, "") + if err != nil { + return nil, err + } + + key, err := keyFunc(block.Bytes) + if err != nil { + return nil, fmt.Errorf("failed to decode %s: %s", pemKey, err) + } + + return key, nil +} + +func parseCertificate(d *schema.ResourceData, pemKey string) (*x509.Certificate, error) { + block, err := decodePEM(d, pemKey, "") + if err != nil { + return nil, err + } + + certs, err := x509.ParseCertificates(block.Bytes) + if err != nil { + return nil, fmt.Errorf("failed to parse %s: %s", pemKey, err) + } + if len(certs) < 1 { + return nil, fmt.Errorf("no certificates found in %s", pemKey) + } + if len(certs) > 1 { + return nil, fmt.Errorf("multiple certificates found in %s", pemKey) + } + + return certs[0], nil +} + +func parseCertificateRequest(d *schema.ResourceData, pemKey string) (*x509.CertificateRequest, error) { + block, err := decodePEM(d, pemKey, pemCertReqType) + if err != nil { + return nil, err + } + + certReq, err := x509.ParseCertificateRequest(block.Bytes) + if err != nil { + return nil, fmt.Errorf("failed to parse %s: %s", pemKey, err) + } + + return certReq, nil +} + +func readPublicKey(d *schema.ResourceData, rsaKey interface{}) error { + pubKey := publicKey(rsaKey) + pubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey) + if err != nil { + return fmt.Errorf("failed to marshal public key error: %s", err) + } + pubKeyPemBlock := &pem.Block{ + Type: "PUBLIC KEY", + Bytes: pubKeyBytes, + } + + d.SetId(hashForState(string((pubKeyBytes)))) + d.Set("public_key_pem", string(pem.EncodeToMemory(pubKeyPemBlock))) + + sshPubKey, err := ssh.NewPublicKey(publicKey(rsaKey)) + if err == nil { + // Not all EC types can be SSH keys, so we'll produce this only + // if an appropriate type was selected. + sshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey) + d.Set("public_key_openssh", string(sshPubKeyBytes)) + } else { + d.Set("public_key_openssh", "") + } + return nil +} diff --git a/vendor/vendor.json b/vendor/vendor.json index f7f29678221b..a45b59e2e644 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -1244,6 +1244,18 @@ "revision": "7166230c635fa24bbe613c5a53e75ad15c42c059", "revisionTime": "2018-02-27T16:32:37Z" }, + { + "checksumSHA1": "f7B1ltZmnRIciTmTZdMphVeYPZU=", + "path": "github.com/terraform-providers/terraform-provider-tls", + "revision": "efce60e4a963b38de99f5be2745602d0678b78c6", + "revisionTime": "2018-03-09T18:48:51Z" + }, + { + "checksumSHA1": "23FDSLO460yDo9qyHLjr0lHZd+4=", + "path": "github.com/terraform-providers/terraform-provider-tls/tls", + "revision": "efce60e4a963b38de99f5be2745602d0678b78c6", + "revisionTime": "2018-03-09T18:48:51Z" + }, { "checksumSHA1": "vE43s37+4CJ2CDU6TlOUOYE0K9c=", "path": "golang.org/x/crypto/bcrypt", diff --git a/website/azurerm.erb b/website/azurerm.erb index 8a205cdae715..d602f3f348a4 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -168,6 +168,15 @@ +