Skip to content

Commit 369c063

Browse files
nafizhaider32nafizhaider
andauthored
Updating Nexus Identity to Version 1.0.0b5 (#8611)
* updated network fabric extension to reflect version 2024-02-15-preview * updates based on code review * version updated to 7.0.0 * fix linting * new api changes * Update for bugfix with 7.1 CLI * fixing lint issue * aligning with new api short description * reverting version change * new cli version for network fabric * lint fixes * fixing lint rule * fix * testing yaml update again * some more updates * nf create lint rules * internal network lint rule * last lint rules * fix file name * fix password scan * updated to say redacted * fix redacted with quotes * this is the one * updating nexus identity --------- Co-authored-by: nafizhaider <[email protected]>
1 parent bfe439b commit 369c063

File tree

12 files changed

+132
-66
lines changed

12 files changed

+132
-66
lines changed

src/nexusidentity/HISTORY.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
Release History
44
===============
55

6+
1.0.0b5
7+
+++++++
8+
* Adding support for older algorithm ssh keys
9+
610
1.0.0b4
711
+++++++
812
* Adding support for Linux platform

src/nexusidentity/README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Azure CLI nexusidentity Extension #
2+
3+
This is an extension to Azure CLI to manage nexusidentity resources.
4+
5+
## How to use ##
6+
7+
Install the extension:
8+
9+
```
10+
az extension add --name nexusidentity
11+
```
12+
13+
Validate that the extension is installed correctly:
14+
15+
```
16+
az nexusidentity --help
17+
```
18+
19+
## Included Features ##
20+
21+
Below is a high-level overview of nexusidentity commands.
22+
23+
| Commands | Description |
24+
|---------------------------|------------------------|
25+
| az nexusidentity gen-keys | Manage key generation. |

src/nexusidentity/README.rst

Lines changed: 0 additions & 5 deletions
This file was deleted.

src/nexusidentity/azext_nexusidentity/__init__.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,21 @@ class NexusidentityCommandsLoader(AzCommandsLoader):
1111

1212
def __init__(self, cli_ctx=None):
1313
from azure.cli.core.commands import CliCommandType
14+
1415
custom_command_type = CliCommandType(
15-
operations_tmpl='azext_nexusidentity.custom#{}')
16-
super(
17-
NexusidentityCommandsLoader,
18-
self).__init__(
19-
cli_ctx=cli_ctx,
20-
custom_command_type=custom_command_type)
16+
operations_tmpl="azext_nexusidentity.custom#{}"
17+
)
18+
super().__init__(cli_ctx=cli_ctx, custom_command_type=custom_command_type)
2119

2220
def load_command_table(self, args):
2321
from azext_nexusidentity.commands import load_command_table
22+
2423
load_command_table(self, args)
2524
return self.command_table
2625

2726
def load_arguments(self, command):
2827
from azext_nexusidentity._params import load_arguments
28+
2929
load_arguments(self, command)
3030

3131

src/nexusidentity/azext_nexusidentity/_help.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,7 @@
1515
helps['nexusidentity gen-keys'] = """
1616
type: command
1717
short-summary: Generate Nexusidentity keys.
18+
parameters:
19+
- name: --algorithm
20+
short-summary: Algorithm to use for generating keys. It can either be ecdsa-sk or ed25519-sk
1821
"""

src/nexusidentity/azext_nexusidentity/_params.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,18 @@
66
# pylint: disable=unused-import
77

88
from knack.arguments import CLIArgumentType
9+
from azure.cli.core.commands.parameters import get_enum_type
910

1011

11-
def load_arguments(_, __):
12-
pass
12+
def load_arguments(self, _):
13+
with self.argument_context("nexusidentity gen-keys") as c:
14+
c.argument(
15+
"algorithm",
16+
arg_type=get_enum_type(
17+
[
18+
"ed25519-sk",
19+
"ecdsa-sk",
20+
]
21+
),
22+
help="Algorithm to use for generating keys. It can either be ecdsa-sk or ed25519-sk",
23+
)

src/nexusidentity/azext_nexusidentity/commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99

1010

1111
def load_command_table(self, _):
12-
with self.command_group('nexusidentity') as g:
13-
g.custom_command('gen-keys', 'generate_nexus_identity_keys')
12+
with self.command_group("nexusidentity") as g:
13+
g.custom_command("gen-keys", "generate_nexus_identity_keys")

src/nexusidentity/azext_nexusidentity/custom.py

Lines changed: 60 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,19 @@
22
# Copyright (c) Microsoft Corporation. All rights reserved.
33
# Licensed under the MIT License. See License.txt in the project root for license information.
44
# --------------------------------------------------------------------------------------------
5+
# pylint: disable=too-many-statements
6+
7+
import logging
58

69
from knack.util import CLIError # pylint: disable=unused-import
710
from knack.log import get_logger
811

9-
import logging
10-
1112
# Set up logging
1213
logging.basicConfig(level=logging.INFO)
1314
logger = get_logger(__name__)
1415

1516

16-
def generate_nexus_identity_keys() -> None:
17+
def generate_nexus_identity_keys(algorithm=None):
1718

1819
import os
1920
import subprocess
@@ -30,6 +31,13 @@ def generate_nexus_identity_keys() -> None:
3031
# Generate SSH key
3132
if sys.platform.startswith("win") or sys.platform.startswith("linux"):
3233

34+
algoToBeUsed = "ed25519-sk"
35+
key_name = "id_ed25519_sk"
36+
37+
if algorithm and algorithm == "ecdsa-sk":
38+
algoToBeUsed = "ecdsa-sk"
39+
key_name = "id_ecdsa_sk"
40+
3341
if sys.platform.startswith("win"):
3442
dir_path = os.path.expanduser("~\\.ssh")
3543
elif sys.platform.startswith("linux"):
@@ -42,54 +50,63 @@ def generate_nexus_identity_keys() -> None:
4250
os.makedirs(dir_path)
4351
except OSError as e:
4452
logger.error("Error creating directory: %s", e)
45-
raise CLIError(f"Error creating directory: {e}")
53+
raise CLIError(f"Error creating directory: {e}") from e
4654

4755
# Generate ed25519-sk key
48-
subprocess.run(['ssh-keygen',
49-
'-t',
50-
'ed25519-sk',
51-
'-O',
52-
'resident',
53-
'-O',
54-
'verify-required',
55-
'-f',
56-
os.path.join(dir_path, "id_ed25519_sk")],
57-
check=False)
58-
59-
# read the key from the file
56+
subprocess.run(
57+
[
58+
"ssh-keygen",
59+
"-t",
60+
algoToBeUsed,
61+
"-O",
62+
"resident",
63+
"-O",
64+
"verify-required",
65+
"-C",
66+
"NexusIdentitySSHKey",
67+
"-f",
68+
os.path.join(dir_path, key_name),
69+
],
70+
check=False,
71+
)
72+
73+
# read the key from the file
6074
try:
6175
# Read public key
62-
with open(os.path.join(dir_path, "id_ed25519_sk.pub"), "r") as key_file:
76+
file_path = key_name + ".pub"
77+
with open(
78+
os.path.join(dir_path, file_path), "r", encoding="utf-8"
79+
) as key_file:
6380
public_key = key_file.read()
6481
except FileNotFoundError as e:
65-
raise CLIError(f"Error reading public key: {e}")
82+
raise CLIError(f"Error reading public key: {e}") from e
6683
except OSError as e:
67-
raise CLIError(f"Unexpected error reading public key: {e}")
84+
raise CLIError(f"Unexpected error reading public key: {e}") from e
6885

6986
try:
7087
credential = AzureCliCredential()
71-
scopes = ['https://graph.microsoft.com//.default']
72-
graph_client = GraphServiceClient(
73-
credentials=credential, scopes=scopes)
88+
scopes = ["https://graph.microsoft.com//.default"]
89+
graph_client = GraphServiceClient(credentials=credential, scopes=scopes)
7490

7591
except ClientAuthenticationError as e:
7692
logger.error("Authentication failed: %s", e)
77-
raise CLIError(f"Authentication failed: {e}")
93+
raise CLIError(f"Authentication failed: {e}") from e
7894
except Exception as e:
7995
logger.error("An unexpected error occurred: %s", e)
80-
raise CLIError(f"An unexpected error occurred: {e}")
96+
raise CLIError(f"An unexpected error occurred: {e}") from e
8197

8298
async def me():
8399
extension_id = "com.nexusidentity.keys"
84100

85101
# Get user object
86102
user = await graph_client.me.get()
87103

88-
# Get extensions assoicated with the user
104+
# Get extensions associated with the user
89105
extensions = await graph_client.me.extensions.get()
90106

91107
extension_exists = any(
92-
extension.id == extension_id for extension in extensions.value)
108+
extension.id == extension_id for extension in extensions.value
109+
)
93110

94111
try:
95112
# Update or create extension
@@ -98,31 +115,36 @@ async def me():
98115
odata_type="microsoft.graph.openTypeExtension",
99116
additional_data={
100117
"extension_name": extension_id,
101-
"publicKey": public_key
102-
}
118+
"publicKey": public_key,
119+
},
103120
)
104-
await graph_client.me.extensions.by_extension_id(extension_id).patch(request_body)
121+
await graph_client.me.extensions.by_extension_id(
122+
extension_id
123+
).patch(request_body)
105124

106-
print(f"Successfully updated public key to Microsoft Entra Id account {user.mail}")
125+
print(
126+
f"Successfully updated public key to Microsoft Entra Id account {user.mail}"
127+
)
107128
else:
108129
request_body = OpenTypeExtension(
109130
odata_type="microsoft.graph.openTypeExtension",
110131
extension_name=extension_id,
111-
additional_data={
112-
"publicKey": public_key
113-
}
132+
additional_data={"publicKey": public_key},
114133
)
115134
await graph_client.me.extensions.post(request_body)
116135

117-
print(f"Successfully uploaded public key to Microsoft Entra Id account {user.mail}")
136+
print(
137+
f"Successfully uploaded public key to Microsoft Entra Id account {user.mail}"
138+
)
118139
except ODataError as e:
119140
logger.error("Error updating extension: %s", e)
120-
raise CLIError(f"Error updating extension: {e}")
121-
except (HttpResponseError) as e:
141+
raise CLIError(f"Error updating extension: {e}") from e
142+
except HttpResponseError as e:
122143
logger.error("Failed to update or create extension: %s", e)
123-
raise CLIError(f"Failed to update or create extension: {e}")
144+
raise CLIError(f"Failed to update or create extension: {e}") from e
124145

125146
asyncio.run(me())
126147
else:
127148
logger.warning(
128-
"This command is currently supported only on Windows and linux platforms")
149+
"This command is currently supported only on Windows and linux platforms"
150+
)

src/nexusidentity/azext_nexusidentity/tests/latest/recordings/test_nexusidentity_scenario1.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,4 +119,4 @@ interactions:
119119
status:
120120
code: 204
121121
message: No Content
122-
version: 1
122+
version: 1

src/nexusidentity/azext_nexusidentity/tests/latest/test_nexusidentity_scenario.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,45 @@
33
# Licensed under the MIT License. See License.txt in the project root for license information.
44
# --------------------------------------------------------------------------------------------
55

6-
'''
6+
"""
77
Nexus Identity Ssh-Key Geneation Scenario Test
8-
'''
8+
"""
99

1010
from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer, live_only
1111

12+
1213
def setup_scenario1(test):
13-
''' Env setup_scenario1 '''
14+
"""Env setup_scenario1"""
1415
pass
1516

1617

1718
def cleanup_scenario1(test):
18-
'''Env cleanup_scenario1 '''
19+
"""Env cleanup_scenario1"""
1920
pass
2021

22+
2123
def call_scenario1(test):
22-
''' # Testcase: scenario1'''
24+
"""# Testcase: scenario1"""
2325
setup_scenario1(test)
2426
step_gen_keys(test, checks=[])
2527
cleanup_scenario1(test)
2628

29+
2730
def step_gen_keys(test, checks=None):
28-
'''Generate Nexus Identity ssh keys '''
31+
"""Generate Nexus Identity ssh keys"""
2932
if checks is None:
3033
checks = []
31-
test.cmd('az nexusidentity gen-keys')
34+
test.cmd("az nexusidentity gen-keys")
35+
test.cmd("az nexusidentity gen-keys --algorithm ecdsa-sk")
36+
test.cmd("az nexusidentity gen-keys --algorithm ed25519-sk")
37+
3238

3339
class NexusidentityScenarioTest(ScenarioTest):
34-
''' Nexus Identity Ssh-Key Generation Scenario Test '''
40+
"""Nexus Identity Ssh-Key Generation Scenario Test"""
3541

3642
def __init__(self, *args, **kwargs):
3743
super().__init__(*args, **kwargs)
38-
44+
3945
@live_only()
4046
def test_nexusidentity_scenario1(self):
4147

0 commit comments

Comments
 (0)