Hi Another issues with new management key API and ...
# ask-a-descoper
v
Hi Another issues with new management key API and terraform
Copy code
resource "descope_management_key" "project_key" {
  count = var.create_management_key ? 1 : 0
  name  = "${descope_project.descope_project.name} Management Key"

  rebac = {
    project_roles = [{
      project_ids = [descope_project.descope_project.id]
      roles       = ["Full Access"]
    }]
  }
}
gives an error:
Copy code
│
│   with module.descope_project.descope_management_key.project_key[0],
│   on ../../../base/terraform/descope_project/main.tf line 656, in resource "descope_management_key" "project_key":
│  656: resource "descope_management_key" "project_key" {
│
│ [E111901] Failed managing management key [Status-Code:400]
I tried the script
Copy code
#!/usr/bin/env python3
"""
Descope management key operations via the Descope SDK.

Usage:
    python test_mgmt_key.py --project-id <id> --management-key <key> [--base-url <url>]
"""

import argparse
import json
import sys

from descope import (
    DescopeClient,
    MgmtKeyProjectRole,
    MgmtKeyReBac,
    MgmtKeyStatus,
    MgmtKeyTagRole,
)


def _print_json(obj):
    print(json.dumps(obj, indent=2, default=str))


def main():
    parser = argparse.ArgumentParser(
        description="Descope management key operations",
    )
    parser.add_argument("--project-id", required=True)
    parser.add_argument("--management-key", required=True)
    parser.add_argument("--base-url", default=None)
    args = parser.parse_args()

    client_kwargs = {
        "project_id": args.project_id,
        "management_key": args.management_key,
    }
    if args.base_url:
        client_kwargs["base_url"] = args.base_url

    descope_client = DescopeClient(**client_kwargs)

    # Search all management keys
    print("=== Search all management keys ===")
    search_resp = descope_client.mgmt.management_key.search()
    keys = search_resp["keys"]
    for key in keys:
        _print_json(key)
        print()

    # Create a new management key with RBAC configuration
    print("=== Create a new management key ===")
    rebac = MgmtKeyReBac(
        company_roles=["company-full-access"],
        project_roles=[
            MgmtKeyProjectRole(
                project_ids=["project-id-1", "project-id-2"],
                roles=["project-admin"],
            )
        ],
        tag_roles=[
            MgmtKeyTagRole(
                tags=["production"],
                roles=["read-only"],
            )
        ],
    )

    create_resp = descope_client.mgmt.management_key.create(
        name="My Management Key",
        rebac=rebac,
        description="Optional description for the management key",
        expires_in=0,
        permitted_ips=["10.0.0.1", "192.168.1.0/24"],
    )
    key = create_resp["key"]
    cleartext = create_resp["cleartext"]
    print("Created key:")
    _print_json(key)
    print(f"Cleartext (save securely, will not be shown again): {cleartext}")

    key_id = key["id"]

    # Load a specific management key by ID
    print(f"\n=== Load management key {key_id} ===")
    load_resp = descope_client.mgmt.management_key.load(key_id)
    loaded_key = load_resp["key"]
    _print_json(loaded_key)

    # Update the management key
    print(f"\n=== Update management key {key_id} ===")
    update_resp = descope_client.mgmt.management_key.update(
        id=key_id,
        name="Updated Key Name",
        description="Updated description",
        permitted_ips=["10.0.0.2"],
        status=MgmtKeyStatus.ACTIVE,
    )
    updated_key = update_resp["key"]
    print("Updated key:")
    _print_json(updated_key)

    # Delete the management key
    print(f"\n=== Delete management key {key_id} ===")
    delete_resp = descope_client.mgmt.management_key.delete([key_id])
    total_deleted = delete_resp["total"]
    print(f"Deleted {total_deleted} key(s).")


if __name__ == "__main__":
    main()
and this gives exact same error with given project_id. Am holding this wrong?
a
Hi @Ville Mattila The error
[E111901] Failed managing management key
is not coming from Terraform itself, it’s coming from the Descope API validation of the ReBAC roles payload. In your Terraform config you’re passing:
Copy code
roles = ["Full Access"]
But in Descope ReBAC roles must use the internal role identifiers, not the display name. So
"Full Access"
is not a valid role identifier which is why the API returns 400.
Can you please verify Roles under your project roles once ?
And in your python script you have passed
Copy code
roles=["project-admin"]
If the
project_ids
don’t belong to the same region / project or the role mapping is invalid for that project, the API rejects it with the same error.
v
hi @Akash Jivane, I don't quite grasp the ReBAC roles. I'm trying to create key like this. Where the blurred project id the one that I'm working. Can you show me the exact descope console path to the roles configuration where I could see the internal ID
a
@Bhagwanta Yeole Could please assist here?
b
Yeah, sure 👍
Hello @Ville Mattila, You can check the roles under the Authorization section on the descope console.
v
Hi @Akash Jivane and @Bhagwanta Yeole I don't see the "Full Access" Roles there. I believe the "Full Access" is Descope builtin role. If I try to create Management key with one of our Custom Roles (RBAC, not FGA). I get same error as before. What I'm looking for is that I could get same kind mkey as what I get when I'm creating key in Console with "Full Access".
Copy code
# Create a new management key with RBAC configuration
    print("=== Create a new management key ===")
    rebac = MgmtKeyReBac(
        company_roles=[],
        project_roles=[
            MgmtKeyProjectRole(
                project_ids=["Peuc13xxxxxx"],
                roles=["ROL3A9wTrxxx"],
            )
        ],
        tag_roles=[],
    )
a
Hi @Ville Mattila You’re absolutely right that “Full Access” exists in the Console, but the important detail is: “Full Access” is a company-level role, not a project RBAC role So when you create a key from the Console with Full Access. Create the same kind of key via Terraform / SDK, you should not use
project_roles
at all, and instead use company roles.
Please try these changes this will resolve your issue.
v
Thanks, I tried this and I'm still getting the same error.
Copy code
print(f"PRJ: {args.project_id}")
    # Create a new management key with RBAC configuration
    print("=== Create a new management key ===")
    rebac = MgmtKeyReBac(
        company_roles=["company-full-access"], # I also tried "Full Access" but error
        project_roles=[],
        tag_roles=[],
    )

    create_resp = descope_client.mgmt.management_key.create(
        name="My Management Key",
        rebac=rebac,
        description="Optional description for the management key",
        expires_in=0,
        permitted_ips=[],
    )
a
@Ville Mattila Can you please DM your projectID?
Thanks for sharing the projectId. As I can see in the error logs I can see -
Copy code
[E111901] Failed managing management key:
- invalid mgmt key project role
- invalid mgmt key company role
- missing mgmt key roles
This seems the roles are not matching due to which you are getting this error. Can you please list the available roles in your project and use one of those exact names?
Just let me know if this is working for or not ?
v
Hi sorry for delay. I'm just trying to have the "Full Access" role for the managment key. Honestly I'm bit lost.
Copy code
rebac = MgmtKeyReBac(
        company_roles=["Security Admin"],
        project_roles=[],
        tag_roles=[],
    )
The "Security Admin" above is one of the RBAC roles in Authorization. I've have also tried the id ROL... None of this works I've tried the "Full Access" and it is not working I've tried Company Descoper role "admin" and custom role "testing" These do not work either. It would be great to get step by step guide how to get python SDK mgmt key created for real. The example codes makes a lot of assumption about the environment. It would really help to see what needs to be there in managment console. At the end of the day I'm looking for getting Full Access management key for the project.
a
Okay, got it!
@Bhagwanta Yeole Please assist here
👀 1
The key point here is that Management Keys do NOT use your RBAC roles from Authorization (like “Security Admin”, custom roles, etc.). They use Descope’s built-in management roles, which are different. That’s why passing things like: •
"Full Access", "Security Admin"
• custom RBAC role IDs (
ROL...
) is failing with
invalid mgmt key role
. To create a “Full Access” management key via SDK, you need to use the built-in Descope management role:
company-full-access
Can you try this once and let me know if this works for you ?
v
Hi! With this code:
Copy code
print(f"PRJ: {args.project_id}")
    # Create a new management key with RBAC configuration
    print("=== Create a new management key ===")
    rebac = MgmtKeyReBac(
        company_roles=["company-full-access"],
        project_roles=[],
        tag_roles=[],
    )

    create_resp = descope_client.mgmt.management_key.create(
        name="My Management Key",
        rebac=rebac,
        description="Optional description for the management key",
        expires_in=0,
        permitted_ips=[],
    )
I'm getting this:
Copy code
PRJ: Peuc13.....
=== Create a new management key ===
Traceback (most recent call last):
  File "test_mgmt_key.py", line 111, in <module>
    main()
    ~~~~^^
  File "test_mgmt_key.py", line 69, in main
    create_resp = descope_client.mgmt.management_key.create(
        name="My Management Key",
    ...<3 lines>...
        permitted_ips=[],
    )
  File "management_key.py", line 53, in create
    response = self._http.put(
        MgmtV1.mgmt_key_create_path,
        body=body,
    )
  File "python3.13/site-packages/descope/http_client.py", line 239, in put
    self._raise_from_response(response)
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
  File "python3.13/site-packages/descope/http_client.py", line 356, in _raise_from_response
    raise AuthException(
    ...<3 lines>...
    )
descope.exceptions.AuthException: {'status_code': 400, 'error_type': 'server error', 'error_message': '{"errorCode":"E111901","errorDescription":"Failed managing management key"}'}
a
The error
[E111901] Failed managing management key
this usually means the request is valid *b*ut the key you’re using to create the new management key does NOT have sufficient permissions to create company-level keys. The parent management key you are using must itself already have company-level (Full Access) permissions. Have you verified your current management key permissions ?
v
Hi Akash, the keys that I'm using do have the "Full Access" set. I just tested that above script works, when I'm using US region and api.descope.com, but If I'm using EU region and api.euc1.descope.com then I get the error above
a
Oh, Okay! Let me check this with our internal team and will get back to you on this. Thanks!
b
Have you created the management key for the EU region?
v
yes. Here is the screenshot the keys I'm using Both keys works ok with all other API actions either in EU or US.
👍 1
b
Okay, so now it's working fine.
v
the us key is working ok. but eu is not, when it comes to trying to create management key. All other API actions are ok with both keys.
b
Please check once where both the keys have the same permissions or not.
v
Hi, the keys are correct with proper permission. Infact I created another managment test key for EU region with full project permissions and I had exactly same problem. e.g
Copy code
{"errorCode":"E111901","errorDescription":"Failed managing management key"}'}
again if use US region and API then the script above works ok, but If try to use script with key that is for EU projects and with EU api endpoint then I have the problem
a
Can you share project ids ? And what are the API calls that you did ?
v
@Aviad Lichtenstadt Here is the test script.
I shared the project id with DM
m
Hi @Ville Mattila, working on reproducing this on our end - think you could rerun the script in that failure case with the EU region so we can isolate the logs from just that?
v
HI @Mei. I just run the script again. I'll send you the project id in DM.
👍 1
m
Excellent, captured - thanks
👍 1
Hey @Ville Mattila, FYI we are still working on a fix for this.
The root cause is known and a fix is planned
v
Great, thanks for the update!
m
@Ville Mattila Hi again, the fix will be deployed Sunday. Sorry for the delay with this one.
v
Excellent. I was about to ask the update. I'll test this next Monday then..
m
Deployment might be delayed another day or two FYI, LMK if it's a problem
👍 1
v
Hi @Mei, any updates for this one?
m
It should be available soon, we are actively working on it 🙂
👍 1
Hi @Ville Mattila this is now confirmed working
v
I just tested this and my test script now works correctly. Thank you!!
🙌 1