Skip to content

Commit 2a17946

Browse files
DaanHooglandGaOrtigaCopilot
authored
make password an optional parameter/field in createAccount (#13955)
* make password an optional parameter/field in createAccount * Update api/src/main/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java Co-authored-by: GaOrtiga <49285692+GaOrtiga@users.noreply.github.com> * Apply suggestion from @vishesh92 * disallow empty passwords * make null-password test not depend on the internal-error path * Remove extra space Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * space after punctuation Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * Apply suggestion from @DaanHoogland --------- Co-authored-by: GaOrtiga <49285692+GaOrtiga@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
1 parent 5232d6d commit 2a17946

4 files changed

Lines changed: 58 additions & 22 deletions

File tree

‎api/src/main/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,14 @@
3737

3838
import com.cloud.user.Account;
3939
import com.cloud.user.UserAccount;
40+
import com.cloud.utils.PasswordGenerator;
4041

4142

4243
@APICommand(name = "createAccount", description = "Creates an account", responseObject = AccountResponse.class, entityType = {Account.class},
4344
requestHasSensitiveInfo = true, responseHasSensitiveInfo = true)
4445
public class CreateAccountCmd extends BaseCmd {
4546

47+
private static final int GENERATED_PASSWORD_LENGTH = 12;
4648

4749
/////////////////////////////////////////////////////
4850
//////////////// API parameters /////////////////////
@@ -75,8 +77,8 @@ public class CreateAccountCmd extends BaseCmd {
7577

7678
@Parameter(name = ApiConstants.PASSWORD,
7779
type = CommandType.STRING,
78-
required = true,
79-
description = "Clear text password (Default hashed to SHA256SALT). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section.")
80+
description = "Clear text password (Default hashed to SHA256SALT). If you wish to use any other hashing algorithm, you will need to write a custom authentication adapter. See Docs section."
81+
+ " If omitted, a random password is generated, e.g. for an account that will only ever authenticate externally via SAML/LDAP.")
8082
private String password;
8183

8284
@Parameter(name = ApiConstants.TIMEZONE,
@@ -191,10 +193,16 @@ public void execute() {
191193

192194
/**
193195
* TODO: this should be done through a validator. for now replicating the validation logic in create account and user
196+
*
197+
* <p>An omitted password generates a random one instead of failing, since an account that will
198+
* only ever authenticate externally (SAML/LDAP) has no need for the admin to set one. A password
199+
* that is passed but blank is still rejected, as that is more likely a client error.
194200
*/
195201
private void validateParams() {
196-
if(StringUtils.isEmpty(getPassword())) {
197-
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Empty passwords are not allowed");
202+
if (getPassword() == null) {
203+
password = PasswordGenerator.generateRandomPassword(GENERATED_PASSWORD_LENGTH);
204+
} else if (StringUtils.isBlank(getPassword())) {
205+
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Blank passwords are not allowed");
198206
}
199207
if (getAccountType() == null && (getRoleId() == null || getRoleId() < 1L)) {
200208
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Neither account type and role ID are not provided");

‎api/src/test/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmdTest.java‎

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@
2020

2121
import org.apache.cloudstack.acl.RoleService;
2222
import org.apache.cloudstack.api.ApiErrorCode;
23+
import org.apache.cloudstack.api.ResponseGenerator;
24+
import org.apache.cloudstack.api.ResponseObject.ResponseView;
2325
import org.apache.cloudstack.api.ServerApiException;
26+
import org.apache.cloudstack.api.response.AccountResponse;
2427
import org.apache.cloudstack.context.CallContext;
2528
import org.apache.logging.log4j.Logger;
2629
import org.apache.logging.log4j.LogManager;
@@ -37,6 +40,7 @@
3740
import com.cloud.user.Account;
3841
import com.cloud.user.AccountService;
3942
import com.cloud.user.User;
43+
import com.cloud.user.UserAccount;
4044

4145
public class CreateAccountCmdTest {
4246
protected Logger logger = LogManager.getLogger(getClass());
@@ -45,6 +49,8 @@ public class CreateAccountCmdTest {
4549
private AccountService accountService;
4650
@Mock
4751
private RoleService roleService;
52+
@Mock
53+
private ResponseGenerator responseGenerator;
4854

4955
@InjectMocks
5056
private CreateAccountCmd createAccountCmd = new CreateAccountCmd();
@@ -81,28 +87,33 @@ public void testExecuteWithNotBlankPassword() {
8187
}
8288

8389
@Test
84-
public void testExecuteWithNullPassword() {
90+
public void testExecuteWithNullPasswordGeneratesOne() {
8591
ReflectionTestUtils.setField(createAccountCmd, "password", null);
86-
try {
87-
createAccountCmd.execute();
88-
Assert.fail("should throw exception for a null password");
89-
} catch (ServerApiException e) {
90-
Assert.assertEquals(ApiErrorCode.PARAM_ERROR, e.getErrorCode());
91-
Assert.assertEquals("Empty passwords are not allowed", e.getMessage());
92-
}
93-
Mockito.verify(accountService, Mockito.never()).createUserAccount(createAccountCmd);
92+
UserAccount userAccount = Mockito.mock(UserAccount.class);
93+
Mockito.when(accountService.createUserAccount(createAccountCmd)).thenReturn(userAccount);
94+
Mockito.when(responseGenerator.createUserAccountResponse(ResponseView.Full, userAccount)).thenReturn(Mockito.mock(AccountResponse.class));
95+
96+
createAccountCmd.execute();
97+
98+
Assert.assertEquals("a password should be generated for accounts that authenticate externally",
99+
12, createAccountCmd.getPassword().length());
100+
Mockito.verify(accountService, Mockito.times(1)).createUserAccount(createAccountCmd);
94101
}
95102

96103
@Test
97104
public void testExecuteWithEmptyPassword() {
98105
ReflectionTestUtils.setField(createAccountCmd, "password", "");
99-
try {
100-
createAccountCmd.execute();
101-
Assert.fail("should throw exception for a empty password");
102-
} catch (ServerApiException e) {
103-
Assert.assertEquals(ApiErrorCode.PARAM_ERROR, e.getErrorCode());
104-
Assert.assertEquals("Empty passwords are not allowed", e.getMessage());
105-
}
106+
ServerApiException e = Assert.assertThrows(ServerApiException.class, () -> createAccountCmd.execute());
107+
Assert.assertEquals(ApiErrorCode.PARAM_ERROR, e.getErrorCode());
108+
Assert.assertEquals("Blank passwords are not allowed", e.getMessage());
109+
Mockito.verify(accountService, Mockito.never()).createUserAccount(createAccountCmd);
110+
}
111+
112+
@Test
113+
public void testExecuteWithWhitespacePassword() {
114+
ReflectionTestUtils.setField(createAccountCmd, "password", " ");
115+
ServerApiException e = Assert.assertThrows(ServerApiException.class, () -> createAccountCmd.execute());
116+
Assert.assertEquals(ApiErrorCode.PARAM_ERROR, e.getErrorCode());
106117
Mockito.verify(accountService, Mockito.never()).createUserAccount(createAccountCmd);
107118
}
108119
}

‎ui/public/locales/en.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4112,6 +4112,7 @@
41124112
"message.restart.vpc": "Please confirm that you want to restart the VPC.",
41134113
"message.restart.vpc.remark": "Please confirm that you want to restart the VPC <p><i>Remark: making a non-redundant VPC redundant will force a clean up. The Networks will not be available for a couple of minutes</i>.</p>",
41144114
"message.running.custom.action": "Running action",
4115+
"message.saml.account.no.password": "This account will authenticate via SAML SSO, so no password is needed — one will be generated automatically.",
41154116
"message.scale.processing": "Scale in progress",
41164117
"message.scaledown.policies": "Please add at least a ScaleDown policy. The AutoScale Group will be scaled down when all conditions in a ScaleDown policy are matched. ScaleDown policies will be checked after ScaleUp policies.",
41174118
"message.scaledown.policy.continue": "Please add at least condition to ScaleDown policy to continue",

‎ui/src/views/iam/AddAccount.vue‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@
6060
v-model:value="form.username"
6161
:placeholder="apiParams.username.description" />
6262
</a-form-item>
63-
<a-row :gutter="12">
63+
<a-row :gutter="12" v-if="!form.samlenable">
6464
<a-col :md="24" :lg="12">
6565
<a-form-item ref="password" name="password">
6666
<template #label>
@@ -82,6 +82,12 @@
8282
</a-form-item>
8383
</a-col>
8484
</a-row>
85+
<a-alert
86+
v-else
87+
type="info"
88+
show-icon
89+
:message="$t('message.saml.account.no.password')"
90+
style="margin-bottom: 12px;" />
8591
<a-form-item ref="email" name="email">
8692
<template #label>
8793
<tooltip-label :title="$t('label.email')" :tooltip="apiParams.email.description"/>
@@ -257,6 +263,14 @@ export default {
257263
}
258264
},
259265
immediate: false
266+
},
267+
'form.samlenable' (samlEnabled) {
268+
// a SAML-authenticated account never logs in with a native password
269+
this.rules.password = samlEnabled ? [] : [{ required: true, message: this.$t('message.error.required.input') }]
270+
this.rules.confirmpassword = samlEnabled ? [] : [
271+
{ required: true, message: this.$t('message.error.required.input') },
272+
{ validator: this.validateConfirmPassword }
273+
]
260274
}
261275
},
262276
methods: {
@@ -415,12 +429,14 @@ export default {
415429
const params = {
416430
roleid: values.roleid,
417431
username: values.username,
418-
password: values.password,
419432
email: values.email,
420433
firstname: values.firstname,
421434
lastname: values.lastname,
422435
domainid: values.domainid
423436
}
437+
if (!values.samlenable) {
438+
params.password = values.password
439+
}
424440
if (this.isValidValueForKey(values, 'account') && values.account.length > 0) {
425441
params.account = values.account
426442
}

0 commit comments

Comments
 (0)