Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New resources: azuread_application_certificate and azuread_service_principal_certificate #262

Merged
merged 6 commits into from
Jun 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
226 changes: 217 additions & 9 deletions azuread/helpers/graph/credentials.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package graph

import (
"encoding/base64"
"fmt"
"strings"
"time"
Expand All @@ -17,6 +18,77 @@ import (
"github.com/terraform-providers/terraform-provider-azuread/azuread/helpers/validate"
)

// valid types are `application` and `service_principal`
func CertificateResourceSchema(object_type string) map[string]*schema.Schema {
var idAttribute string

switch object_type {
case "application":
idAttribute = "application_object_id"
case "service_principal":
idAttribute = "service_principal_id"
}

return map[string]*schema.Schema{
idAttribute: {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.UUID,
},

"key_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validate.UUID,
},

"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"AsymmetricX509Cert",
"Symmetric",
}, false),
},

"value": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Sensitive: true,
},

"start_date": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.IsRFC3339Time,
},

"end_date": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"end_date_relative"},
ValidateFunc: validation.IsRFC3339Time,
},

"end_date_relative": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"end_date"},
ValidateFunc: validate.NoEmptyStrings,
},
}
}

// valid types are `application` and `service_principal`
func PasswordResourceSchema(object_type string) map[string]*schema.Schema {
return map[string]*schema.Schema{
Expand Down Expand Up @@ -77,37 +149,37 @@ func PasswordResourceSchema(object_type string) map[string]*schema.Schema {
}
}

type PasswordCredentialId struct {
type CredentialId struct {
ObjectId string
KeyId string
}

func (id PasswordCredentialId) String() string {
func (id CredentialId) String() string {
return id.ObjectId + "/" + id.KeyId
}

func ParsePasswordCredentialId(id string) (PasswordCredentialId, error) {
func ParseCredentialId(id string) (CredentialId, error) {
parts := strings.Split(id, "/")
if len(parts) != 2 {
return PasswordCredentialId{}, fmt.Errorf("Password Credential ID should be in the format {objectId}/{keyId} - but got %q", id)
return CredentialId{}, fmt.Errorf("Password Credential ID should be in the format {objectId}/{keyId} - but got %q", id)
}

if _, err := uuid.ParseUUID(parts[0]); err != nil {
return PasswordCredentialId{}, fmt.Errorf("Object ID isn't a valid UUID (%q): %+v", id[0], err)
return CredentialId{}, fmt.Errorf("Object ID isn't a valid UUID (%q): %+v", id[0], err)
}

if _, err := uuid.ParseUUID(parts[1]); err != nil {
return PasswordCredentialId{}, fmt.Errorf("Credential ID isn't a valid UUID (%q): %+v", id[1], err)
return CredentialId{}, fmt.Errorf("Credential ID isn't a valid UUID (%q): %+v", id[1], err)
}

return PasswordCredentialId{
return CredentialId{
ObjectId: parts[0],
KeyId: parts[1],
}, nil
}

func PasswordCredentialIdFrom(objectId, keyId string) PasswordCredentialId {
return PasswordCredentialId{
func CredentialIdFrom(objectId, keyId string) CredentialId {
return CredentialId{
ObjectId: objectId,
KeyId: keyId,
}
Expand Down Expand Up @@ -249,3 +321,139 @@ func WaitForPasswordCredentialReplication(keyId string, f func() (graphrbac.Pass
},
}).WaitForState()
}

func KeyCredentialForResource(d *schema.ResourceData) (*graphrbac.KeyCredential, error) {
keyType := d.Get("type").(string)
value := d.Get("value").(string)
encodedValue := base64.StdEncoding.EncodeToString([]byte(value))

// errors should be handled by the validation
var keyId string
if v, ok := d.GetOk("key_id"); ok {
keyId = v.(string)
} else {
kid, err := uuid.GenerateUUID()
if err != nil {
return nil, err
}

keyId = kid
}

var endDate time.Time
if v := d.Get("end_date").(string); v != "" {
endDate, _ = time.Parse(time.RFC3339, v)
} else if v := d.Get("end_date_relative").(string); v != "" {
d, err := time.ParseDuration(v)
if err != nil {
return nil, fmt.Errorf("unable to parse `end_date_relative` (%s) as a duration", v)
}
endDate = time.Now().Add(d)
} else {
return nil, fmt.Errorf("one of `end_date` or `end_date_relative` must be specified")
}

credential := graphrbac.KeyCredential{
KeyID: p.String(keyId),
Type: p.String(keyType),
Usage: p.String("verify"),
Value: p.String(encodedValue),
EndDate: &date.Time{Time: endDate},
}

if v, ok := d.GetOk("start_date"); ok {
// errors will be handled by the validation
startDate, _ := time.Parse(time.RFC3339, v.(string))
credential.StartDate = &date.Time{Time: startDate}
}

return &credential, nil
}

func KeyCredentialResultFindByKeyId(creds graphrbac.KeyCredentialListResult, keyId string) *graphrbac.KeyCredential {
var cred *graphrbac.KeyCredential

if creds.Value != nil {
for _, c := range *creds.Value {
if c.KeyID == nil {
continue
}

if *c.KeyID == keyId {
cred = &c
break
}
}
}

return cred
}

func KeyCredentialResultAdd(existing graphrbac.KeyCredentialListResult, cred *graphrbac.KeyCredential, errorOnDuplicate bool) (*[]graphrbac.KeyCredential, error) {
newCreds := make([]graphrbac.KeyCredential, 0)

if existing.Value != nil {
if errorOnDuplicate {
for _, v := range *existing.Value {
if v.KeyID == nil {
continue
}

if *v.KeyID == *cred.KeyID {
return nil, fmt.Errorf("credential already exists found")
}
}
}

newCreds = *existing.Value
}
newCreds = append(newCreds, *cred)

return &newCreds, nil
}

func KeyCredentialResultRemoveByKeyId(existing graphrbac.KeyCredentialListResult, keyId string) *[]graphrbac.KeyCredential {
newCreds := make([]graphrbac.KeyCredential, 0)

if existing.Value != nil {
for _, v := range *existing.Value {
if v.KeyID == nil {
continue
}

if *v.KeyID == keyId {
continue
}

newCreds = append(newCreds, v)
}
}

return &newCreds
}

func WaitForKeyCredentialReplication(keyId string, f func() (graphrbac.KeyCredentialListResult, error)) (interface{}, error) {
return (&resource.StateChangeConf{
Pending: []string{"404", "BadCast", "NotFound"},
Target: []string{"Found"},
Timeout: 5 * time.Minute,
MinTimeout: 1 * time.Second,
ContinuousTargetOccurence: 10,
Refresh: func() (interface{}, string, error) {
creds, err := f()
if err != nil {
if ar.ResponseWasNotFound(creds.Response) {
return creds, "404", nil
}
return creds, "Error", fmt.Errorf("calling f, response was not 404 (%d): %v", creds.Response.StatusCode, err)
}

credential := KeyCredentialResultFindByKeyId(creds, keyId)
if credential == nil {
return creds, "NotFound", nil
}

return creds, "Found", nil
},
}).WaitForState()
}
16 changes: 9 additions & 7 deletions azuread/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,15 @@ func Provider() terraform.ResourceProvider {
},

ResourcesMap: map[string]*schema.Resource{
"azuread_application": resourceApplication(),
"azuread_application_password": resourceApplicationPassword(),
"azuread_group": resourceGroup(),
"azuread_group_member": resourceGroupMember(),
"azuread_service_principal": resourceServicePrincipal(),
"azuread_service_principal_password": resourceServicePrincipalPassword(),
"azuread_user": resourceUser(),
"azuread_application": resourceApplication(),
"azuread_application_certificate": resourceApplicationCertificate(),
"azuread_application_password": resourceApplicationPassword(),
"azuread_group": resourceGroup(),
"azuread_group_member": resourceGroupMember(),
"azuread_service_principal": resourceServicePrincipal(),
"azuread_service_principal_certificate": resourceServicePrincipalCertificate(),
"azuread_service_principal_password": resourceServicePrincipalPassword(),
"azuread_user": resourceUser(),
},
}

Expand Down
Loading