From 21bfaf8672f096aad0187cd8796fa0089b32382f Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Fri, 26 Jul 2024 12:57:42 +0200 Subject: [PATCH] nethsm: Improve namespace handling in add-user To make the namespace creation less confusing, this patch introduces two changes to the add-user subcommand: - If a user is created in a new namespace and the --create-namespace option is set, the namespace is added after creating the user. - Otherwise, a warning is shown indicating that the namespace needs to be added manually. --- pynitrokey/cli/nethsm.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/pynitrokey/cli/nethsm.py b/pynitrokey/cli/nethsm.py index a7d730b6..23d5231b 100644 --- a/pynitrokey/cli/nethsm.py +++ b/pynitrokey/cli/nethsm.py @@ -297,6 +297,11 @@ def get_user(ctx: Context, user_id: str) -> None: ) @click.option("-u", "--user-id", help="The user ID of the new user") @click.option("-N", "--namespace", help="The namespace of the new user") +@click.option( + "--create-namespace", + is_flag=True, + help="Create the namespace after adding the user", +) @click.pass_context def add_user( ctx: Context, @@ -305,6 +310,7 @@ def add_user( passphrase: str, user_id: Optional[str], namespace: Optional[str], + create_namespace: bool, ) -> None: """Create a new user on the NetHSM. @@ -312,6 +318,14 @@ def add_user( specified interactively. If the user ID is not set, it is generated by the NetHSM. + If a namespace is specified, the user will be created within the namespace. + This means that the resulting user name will follow the pattern + namespace~userid, i. e. the same user ID can be used in different + namespaces. + + If the --create-namespace option is set and a namespace is specified, the + namespace will be created after the user has been added. + This command requires authentication as a user with the Administrator role.""" with connect(ctx) as nethsm: @@ -320,6 +334,23 @@ def add_user( ) print(f"User {user_id} added to NetHSM {nethsm.host}") + if namespace and nethsm.auth is not None and "~" not in nethsm.auth.username: + # user added to non-existing namespace + if create_namespace: + nethsm.add_namespace(namespace) + print(f"Namespace {namespace} added to NetHSM {nethsm.host}") + else: + print( + f"Warning: The namespace {namespace} does not exist. Add it to the NetHSM with ", + file=sys.stderr, + ) + print(f" nitropy nethsm add-namespace {namespace}", file=sys.stderr) + print( + "to be able to use it. Once the namespace has been added, it can only be managed " + "by users in the same namespace.", + file=sys.stderr, + ) + @nethsm.command() @click.argument("user-id")