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

Added support to add client role on service account user #208

Closed
wants to merge 1 commit into from
Closed
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
62 changes: 62 additions & 0 deletions keycloak/openid_client_service_account_client_role.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package keycloak

import (
"fmt"
)

type OpenidClientServiceAccountClientRole struct {
Id string `json:"id"`
RealmId string `json:"-"`
ClientId string `json:"-"`
ServiceAccountUserId string `json:"-"`
Name string `json:"name,omitempty"`
Description string `json:"description"`
}

func (keycloakClient *KeycloakClient) NewOpenidClientServiceAccountClientRole(serviceAccountRole *OpenidClientServiceAccountClientRole) error {
serviceAccountRoles := []OpenidClientServiceAccountClientRole{*serviceAccountRole}

_, _, err := keycloakClient.post(fmt.Sprintf("/realms/%s/users/%s/role-mappings/clients/%s", serviceAccountRole.RealmId, serviceAccountRole.ServiceAccountUserId, serviceAccountRole.ClientId), serviceAccountRoles)

if err != nil {
return err
}
return nil
}

func (keycloakClient *KeycloakClient) DeleteOpenidClientServiceAccountClientRole(realm, client, serviceAccountUserId, roleId string) error {
serviceAccountRole, err := keycloakClient.GetOpenidClientServiceAccountClientRole(realm, client, serviceAccountUserId, roleId)
if err != nil {
return err
}
serviceAccountRoles := []OpenidClientServiceAccountClientRole{*serviceAccountRole}
err = keycloakClient.delete(fmt.Sprintf("/realms/%s/users/%s/role-mappings/clients/%s", realm, serviceAccountUserId, serviceAccountRole.ClientId), &serviceAccountRoles)
if err != nil {
return err
}
return nil
}

func (keycloakClient *KeycloakClient) GetOpenidClientServiceAccountClientRole(realm, client, serviceAccountUserId, roleId string) (*OpenidClientServiceAccountClientRole, error) {
serviceAccountRoles := []OpenidClientServiceAccountClientRole{
{
Id: roleId,
RealmId: realm,
ClientId: client,
ServiceAccountUserId: serviceAccountUserId,
},
}
err := keycloakClient.get(fmt.Sprintf("/realms/%s/users/%s/role-mappings/clients/%s", realm, serviceAccountUserId, client), &serviceAccountRoles, nil)
if err != nil {
return nil, err
}
for _, serviceAccountRole := range serviceAccountRoles {
if serviceAccountRole.Id == roleId {
serviceAccountRole.RealmId = realm
serviceAccountRole.ClientId = client
serviceAccountRole.ServiceAccountUserId = serviceAccountUserId
return &serviceAccountRole, nil
}
}
return &OpenidClientServiceAccountClientRole{}, nil
}
1 change: 1 addition & 0 deletions provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ func KeycloakProvider() *schema.Provider {
"keycloak_openid_client_authorization_permission": resourceKeycloakOpenidClientAuthorizationPermission(),
"keycloak_openid_client_service_account_role": resourceKeycloakOpenidClientServiceAccountRole(),
"keycloak_openid_client_service_account_realm_role": resourceKeycloakOpenidClientServiceAccountRealmRole(),
"keycloak_openid_client_service_account_client_role": resourceKeycloakOpenidClientServiceAccountClientRole(),
"keycloak_role": resourceKeycloakRole(),
},
Schema: map[string]*schema.Schema{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package provider

import (
"fmt"
"github.com/hashicorp/terraform/helper/schema"
"github.com/mrparkers/terraform-provider-keycloak/keycloak"
"strings"
)

func resourceKeycloakOpenidClientServiceAccountClientRole() *schema.Resource {
return &schema.Resource{
Create: resourceKeycloakOpenidClientServiceAccountClientRoleCreate,
Read: resourceKeycloakOpenidClientServiceAccountClientRoleRead,
Delete: resourceKeycloakOpenidClientServiceAccountClientRoleDelete,
Importer: &schema.ResourceImporter{
State: resourceKeycloakOpenidClientServiceAccountClientRoleImport,
},
Schema: map[string]*schema.Schema{
"service_account_user_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"realm_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"client_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"role": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}

func getOpenidClientServiceAccountClientRoleFromData(data *schema.ResourceData, keycloakClient *keycloak.KeycloakClient) (*keycloak.OpenidClientServiceAccountClientRole, error) {
roleName := data.Get("role").(string)
realmId := data.Get("realm_id").(string)
clientId := data.Get("client_id").(string)
serviceAccountRoleId := data.Get("service_account_user_id").(string)

role, err := keycloakClient.GetRoleByName(realmId, clientId, roleName)
if err != nil {
if keycloak.ErrorIs404(err) {
role = &keycloak.Role{Id: ""}
} else {
return nil, err
}
}

return &keycloak.OpenidClientServiceAccountClientRole{
Id: role.Id,
Name: roleName,
RealmId: realmId,
ClientId: clientId,
ServiceAccountUserId: serviceAccountRoleId,
}, nil
}

func setOpenidClientServiceAccountClientRoleData(data *schema.ResourceData, serviceAccountRole *keycloak.OpenidClientServiceAccountClientRole) {
data.SetId(fmt.Sprintf("%s/%s", serviceAccountRole.ServiceAccountUserId, serviceAccountRole.Id))
data.Set("realm_id", serviceAccountRole.RealmId)
data.Set("client_id", serviceAccountRole.ClientId)
data.Set("service_account_user_id", serviceAccountRole.ServiceAccountUserId)
data.Set("role", serviceAccountRole.Name)
}

func resourceKeycloakOpenidClientServiceAccountClientRoleCreate(data *schema.ResourceData, meta interface{}) error {
keycloakClient := meta.(*keycloak.KeycloakClient)
serviceAccountRole, err := getOpenidClientServiceAccountClientRoleFromData(data, keycloakClient)
if err != nil {
return err
}

err = keycloakClient.NewOpenidClientServiceAccountClientRole(serviceAccountRole)
if err != nil {
return err
}
setOpenidClientServiceAccountClientRoleData(data, serviceAccountRole)
return resourceKeycloakOpenidClientServiceAccountClientRoleRead(data, meta)
}

func resourceKeycloakOpenidClientServiceAccountClientRoleRead(data *schema.ResourceData, meta interface{}) error {
keycloakClient := meta.(*keycloak.KeycloakClient)

serviceAccountRole, err := getOpenidClientServiceAccountClientRoleFromData(data, keycloakClient)
if err != nil {
return err
}

serviceAccountRole, err = keycloakClient.GetOpenidClientServiceAccountClientRole(serviceAccountRole.RealmId, serviceAccountRole.ClientId, serviceAccountRole.ServiceAccountUserId, serviceAccountRole.Id)
if err != nil {
return handleNotFoundError(err, data)
}

setOpenidClientServiceAccountClientRoleData(data, serviceAccountRole)

return nil
}

func resourceKeycloakOpenidClientServiceAccountClientRoleDelete(data *schema.ResourceData, meta interface{}) error {
keycloakClient := meta.(*keycloak.KeycloakClient)

serviceAccountRole, err := getOpenidClientServiceAccountClientRoleFromData(data, keycloakClient)
if err != nil {
return err
}

err = keycloakClient.DeleteOpenidClientServiceAccountClientRole(serviceAccountRole.RealmId, serviceAccountRole.ClientId, serviceAccountRole.ServiceAccountUserId, serviceAccountRole.Id)
if err != nil {
return handleNotFoundError(err, data)
}
return nil
}

func resourceKeycloakOpenidClientServiceAccountClientRoleImport(d *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) {
parts := strings.Split(d.Id(), "/")
if len(parts) != 2 {
return nil, fmt.Errorf("Invalid import. Supported import formats: {{realmId}}/{{serviceAccountUserId}}/{{roleId}}")
}
d.Set("realm_id", parts[0])
d.Set("client_id", parts[1])
d.Set("service_account_user_id", parts[2])
d.SetId(fmt.Sprintf("%s/%s/%s", parts[1], parts[2], parts[3]))

return []*schema.ResourceData{d}, nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
package provider

import (
"fmt"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"github.com/mrparkers/terraform-provider-keycloak/keycloak"
"strings"
"testing"
)

func TestAccKeycloakOpenidClientServiceAccountClientRole_basic(t *testing.T) {
realmName := "terraform-" + acctest.RandString(10)
clientId := "terraform-" + acctest.RandString(10)

resource.Test(t, resource.TestCase{
Providers: testAccProviders,
PreCheck: func() { testAccPreCheck(t) },
CheckDestroy: testAccCheckKeycloakOpenidClientServiceAccountClientRoleDestroy(),
Steps: []resource.TestStep{
{
Config: testKeycloakOpenidClientServiceAccountClientRole_basic(realmName, clientId),
Check: testAccCheckKeycloakOpenidClientServiceAccountClientRoleExists("keycloak_openid_client_service_account_realm_role.test"),
},
},
})
}

func TestAccKeycloakOpenidClientServiceAccountClientRole_createAfterManualDestroy(t *testing.T) {
var serviceAccountRole = &keycloak.OpenidClientServiceAccountClientRole{}

realmName := "terraform-" + acctest.RandString(10)
clientId := "terraform-" + acctest.RandString(10)

resource.Test(t, resource.TestCase{
Providers: testAccProviders,
PreCheck: func() { testAccPreCheck(t) },
CheckDestroy: testAccCheckKeycloakOpenidClientServiceAccountClientRoleDestroy(),
Steps: []resource.TestStep{
{
Config: testKeycloakOpenidClientServiceAccountClientRole_basic(realmName, clientId),
Check: testAccCheckKeycloakOpenidClientServiceAccountClientRoleFetch("keycloak_openid_client_service_account_realm_role.test", serviceAccountRole),
},
{
PreConfig: func() {
keycloakClient := testAccProvider.Meta().(*keycloak.KeycloakClient)

err := keycloakClient.DeleteOpenidClientServiceAccountClientRole(serviceAccountRole.RealmId,serviceAccountRole.ClientId, serviceAccountRole.ServiceAccountUserId, serviceAccountRole.Id)
if err != nil {
t.Fatal(err)
}
},
Config: testKeycloakOpenidClientServiceAccountClientRole_basic(realmName, clientId),
Check: testAccCheckKeycloakOpenidClientServiceAccountClientRoleExists("keycloak_openid_client_service_account_realm_role.test"),
},
},
})
}

func TestAccKeycloakOpenidClientServiceAccountClientRole_basicUpdateRealm(t *testing.T) {
firstRealm := "terraform-" + acctest.RandString(10)
secondRealm := "terraform-" + acctest.RandString(10)
clientId := "terraform-" + acctest.RandString(10)

resource.Test(t, resource.TestCase{
Providers: testAccProviders,
PreCheck: func() { testAccPreCheck(t) },
CheckDestroy: testAccCheckKeycloakOpenidClientServiceAccountClientRoleDestroy(),
Steps: []resource.TestStep{
{
Config: testKeycloakOpenidClientServiceAccountClientRole_basic(firstRealm, clientId),
Check: resource.ComposeTestCheckFunc(
testAccCheckKeycloakOpenidClientServiceAccountClientRoleExists("keycloak_openid_client_service_account_realm_role.test"),
resource.TestCheckResourceAttr("keycloak_openid_client_service_account_realm_role.test", "realm_id", firstRealm),
),
},
{
Config: testKeycloakOpenidClientServiceAccountClientRole_basic(secondRealm, clientId),
Check: resource.ComposeTestCheckFunc(
testAccCheckKeycloakOpenidClientServiceAccountClientRoleExists("keycloak_openid_client_service_account_realm_role.test"),
resource.TestCheckResourceAttr("keycloak_openid_client_service_account_realm_role.test", "realm_id", secondRealm),
),
},
},
})
}

func testAccCheckKeycloakOpenidClientServiceAccountClientRoleExists(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, err := getKeycloakOpenidClientServiceAccountClientRoleFromState(s, resourceName)
if err != nil {
return err
}

return nil
}
}

func testAccCheckKeycloakOpenidClientServiceAccountClientRoleFetch(resourceName string, serviceAccountRole *keycloak.OpenidClientServiceAccountClientRole) resource.TestCheckFunc {
return func(s *terraform.State) error {
fetchedServiceAccountRole, err := getKeycloakOpenidClientServiceAccountClientRoleFromState(s, resourceName)
if err != nil {
return err
}

serviceAccountRole.ServiceAccountUserId = fetchedServiceAccountRole.ServiceAccountUserId
serviceAccountRole.RealmId = fetchedServiceAccountRole.RealmId
serviceAccountRole.ClientId = fetchedServiceAccountRole.ClientId
serviceAccountRole.Id = fetchedServiceAccountRole.Id

return nil
}
}

func testAccCheckKeycloakOpenidClientServiceAccountClientRoleDestroy() resource.TestCheckFunc {
return func(s *terraform.State) error {
for _, rs := range s.RootModule().Resources {
if rs.Type != "keycloak_openid_client_service_account_realm_role" {
continue
}

realmId := rs.Primary.Attributes["realm_id"]
clientId := rs.Primary.Attributes["client_id"]
serviceAccountUserId := rs.Primary.Attributes["service_account_user_id"]
id := strings.Split(rs.Primary.ID, "/")[1]

keycloakClient := testAccProvider.Meta().(*keycloak.KeycloakClient)

serviceAccountRole, _ := keycloakClient.GetOpenidClientServiceAccountClientRole(realmId, clientId, serviceAccountUserId, id)
if serviceAccountRole != nil {
return fmt.Errorf("service account role exists")
}
}

return nil
}
}

func getKeycloakOpenidClientServiceAccountClientRoleFromState(s *terraform.State, resourceName string) (*keycloak.OpenidClientServiceAccountClientRole, error) {
keycloakClient := testAccProvider.Meta().(*keycloak.KeycloakClient)

rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return nil, fmt.Errorf("resource not found: %s", resourceName)
}

realmId := rs.Primary.Attributes["realm_id"]
clientId := rs.Primary.Attributes["client_id"]
serviceAccountUserId := rs.Primary.Attributes["service_account_user_id"]
id := strings.Split(rs.Primary.ID, "/")[1]

serviceAccountRole, err := keycloakClient.GetOpenidClientServiceAccountClientRole(realmId, clientId, serviceAccountUserId, id)
if err != nil {
return nil, fmt.Errorf("error getting service account role mapping: %s", err)
}

return serviceAccountRole, nil
}

func testKeycloakOpenidClientServiceAccountClientRole_basic(realm, clientId string) string {
return fmt.Sprintf(`
resource keycloak_realm test {
realm = "%s"
}

resource keycloak_openid_client test {
client_id = "%s"
realm_id = "${keycloak_realm.test.id}"
access_type = "CONFIDENTIAL"
service_accounts_enabled = true
}

resource keycloak_openid_client_service_account_realm_role test {
service_account_user_id = "${keycloak_openid_client.test.service_account_user_id}"
realm_id = "${keycloak_realm.test.id}"
role = "offline_access"
}
`, realm, clientId)
}