Skip to content

Api keypair restructure #9504

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

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
3 changes: 2 additions & 1 deletion api/src/main/java/com/cloud/event/EventTypes.java
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,9 @@ public class EventTypes {
//registering userdata events
public static final String EVENT_REGISTER_USER_DATA = "REGISTER.USER.DATA";

//register for user API and secret keys
//user API and secret keys
public static final String EVENT_REGISTER_FOR_SECRET_API_KEY = "REGISTER.USER.KEY";
public static final String EVENT_DELETE_SECRET_API_KEY = "DELETE.USER.KEY";
public static final String API_KEY_ACCESS_UPDATE = "API.KEY.ACCESS.UPDATE";

// Template Events
Expand Down
33 changes: 28 additions & 5 deletions api/src/main/java/com/cloud/user/AccountService.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.acl.apikeypair.ApiKeyPair;
import org.apache.cloudstack.acl.apikeypair.ApiKeyPairPermission;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.command.admin.account.CreateAccountCmd;
import org.apache.cloudstack.api.command.admin.user.GetUserKeysCmd;
import org.apache.cloudstack.api.command.admin.user.RegisterCmd;
import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd;

import com.cloud.dc.DataCenter;
import com.cloud.domain.Domain;
Expand All @@ -35,6 +35,14 @@
import com.cloud.offering.DiskOffering;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.ServiceOffering;
import org.apache.cloudstack.api.command.admin.user.DeleteUserKeysCmd;
import org.apache.cloudstack.api.command.admin.user.GetUserKeysCmd;
import org.apache.cloudstack.api.command.admin.user.ListUserKeyRulesCmd;
import org.apache.cloudstack.api.command.admin.user.ListUserKeysCmd;
import org.apache.cloudstack.api.command.admin.user.RegisterUserKeysCmd;
import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd;
import org.apache.cloudstack.api.response.ApiKeyPairResponse;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.auth.UserTwoFactorAuthenticator;

public interface AccountService {
Expand Down Expand Up @@ -93,7 +101,7 @@ User createUser(String userName, String password, String firstName, String lastN

void markUserRegistered(long userId);

public String[] createApiKeyAndSecretKey(RegisterCmd cmd);
ApiKeyPair createApiKeyAndSecretKey(RegisterUserKeysCmd cmd);

public String[] createApiKeyAndSecretKey(final long userId);

Expand All @@ -119,6 +127,8 @@ User createUser(String userName, String password, String firstName, String lastN

void validateAccountHasAccessToResource(Account account, AccessType accessType, Object resource);

void validateCallingUserHasAccessToDesiredUser(Long userId);

Long finalyzeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly);

/**
Expand All @@ -130,7 +140,13 @@ User createUser(String userName, String password, String firstName, String lastN

public Pair<Boolean, Map<String, String>> getKeys(GetUserKeysCmd cmd);

public Pair<Boolean, Map<String, String>> getKeys(Long userId);
ListResponse<ApiKeyPairResponse> listKeys(ListUserKeysCmd cmd);

List<ApiKeyPairPermission> listKeyRules(ListUserKeyRulesCmd cmd);

void deleteApiKey(DeleteUserKeysCmd cmd);

void deleteApiKey(ApiKeyPair id);

/**
* Lists user two-factor authentication provider plugins
Expand All @@ -145,4 +161,11 @@ User createUser(String userName, String password, String firstName, String lastN
*/
UserTwoFactorAuthenticator getUserTwoFactorAuthenticationProvider(final Long domainId);

ApiKeyPair getLatestUserKeyPair(Long userId);

ApiKeyPair getKeyPairById(Long id);

ApiKeyPair getKeyPairByApiKey(String apiKey);

String getAccessingApiKey(BaseCmd cmd);
}
21 changes: 21 additions & 0 deletions api/src/main/java/com/cloud/user/ApiKeyPairState.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.user;

public enum ApiKeyPairState {
ENABLED, REMOVED, EXPIRED

Check warning on line 20 in api/src/main/java/com/cloud/user/ApiKeyPairState.java

View check run for this annotation

Codecov / codecov/patch

api/src/main/java/com/cloud/user/ApiKeyPairState.java#L19-L20

Added lines #L19 - L20 were not covered by tests
}
8 changes: 0 additions & 8 deletions api/src/main/java/com/cloud/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,6 @@ public enum Source {

public void setState(Account.State state);

public String getApiKey();

public void setApiKey(String apiKey);

public String getSecretKey();

public void setSecretKey(String secretKey);

public String getTimezone();

public void setTimezone(String timezone);
Expand Down
4 changes: 0 additions & 4 deletions api/src/main/java/com/cloud/user/UserAccount.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,6 @@ public interface UserAccount extends InternalIdentity {

String getState();

String getApiKey();

String getSecretKey();

Date getCreated();

Date getRemoved();
Expand Down
5 changes: 3 additions & 2 deletions api/src/main/java/org/apache/cloudstack/acl/APIChecker.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.component.Adapter;
import org.apache.cloudstack.acl.apikeypair.ApiKeyPairPermission;

import java.util.List;

Expand All @@ -31,8 +32,8 @@ public interface APIChecker extends Adapter {
// If true, apiChecker has checked the operation
// If false, apiChecker is unable to handle the operation or not implemented
// On exception, checkAccess failed don't allow
boolean checkAccess(User user, String apiCommandName) throws PermissionDeniedException;
boolean checkAccess(Account account, String apiCommandName) throws PermissionDeniedException;
boolean checkAccess(User user, String apiCommandName, ApiKeyPairPermission... apiKeyPairPermissions) throws PermissionDeniedException;
boolean checkAccess(Account account, String apiCommandName, ApiKeyPairPermission... apiKeyPairPermissions) throws PermissionDeniedException;
/**
* Verifies if the account has permission for the given list of APIs and returns only the allowed ones.
*
Expand Down
21 changes: 21 additions & 0 deletions api/src/main/java/org/apache/cloudstack/acl/RoleService.java
Original file line number Diff line number Diff line change
Expand Up @@ -104,5 +104,26 @@ public interface RoleService {

List<RolePermission> findAllPermissionsBy(Long roleId);

List<RolePermissionEntity> findAllRolePermissionsEntityBy(Long roleId);

Permission getRolePermission(String permission);

int removeRolesIfNeeded(List<? extends Role> roles);

/**
* Checks if the role of the caller account has compatible permissions of the specified role permissions.
* For each permission of the roleToAccess, the role of the caller needs to contain the same permission.
*
* @param rolePermissions the permissions of the caller role.
* @param rolePermissionsToAccess the permissions for the role that the caller role wants to access.
* @return True if the role can be accessed with the given permissions; false otherwise.
*/
boolean roleHasPermission(Map<String, Permission> rolePermissions, List<RolePermissionEntity> rolePermissionsToAccess);

/**
* Given a list of role permissions, returns a {@link Map} containing the API name as the key and the {@link Permission} for the API as the value.
*
* @param rolePermissions Permissions for the role from role.
*/
Map<String, Permission> getRoleRulesAndPermissions(List<RolePermissionEntity> rolePermissions);
}
6 changes: 4 additions & 2 deletions api/src/main/java/org/apache/cloudstack/acl/Rule.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,18 @@

public final class Rule {
private final String rule;
private final Pattern matchingPattern;
private final static Pattern ALLOWED_PATTERN = Pattern.compile("^[a-zA-Z0-9*]+$");

public Rule(final String rule) {
validate(rule);
this.rule = rule;
matchingPattern = Pattern.compile(rule.toLowerCase().replace("*", "(\\w*\\*?)+"));
}

public boolean matches(final String commandName) {
return StringUtils.isNotEmpty(commandName)
&& commandName.toLowerCase().matches(rule.toLowerCase().replace("*", "\\w*"));
return StringUtils.isNotEmpty(commandName) &&
matchingPattern.matcher(commandName.toLowerCase()).matches();
}

public String getRuleString() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.acl.apikeypair;

import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;

import java.util.Date;

public interface ApiKeyPair extends ControlledEntity, InternalIdentity, Identity {
Long getUserId();
Date getStartDate();
Date getEndDate();
Date getCreated();
String getDescription();
String getApiKey();
String getSecretKey();
String getName();
Date getRemoved();
void setRemoved(Date date);
void validateDate();
boolean hasEndDatePassed();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.acl.apikeypair;

import org.apache.cloudstack.acl.RolePermissionEntity;

public interface ApiKeyPairPermission extends RolePermissionEntity {
long getApiKeyPairId();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.acl.apikeypair;

import java.util.List;

public interface ApiKeyPairService {
List<ApiKeyPairPermission> findAllPermissionsByKeyPairId(Long apiKeyPairId, Long roleId);

ApiKeyPair findByApiKey(String apiKey);

ApiKeyPair findById(Long id);

void validateCallingUserHasAccessToDesiredUser(Long userId);
}
10 changes: 7 additions & 3 deletions api/src/main/java/org/apache/cloudstack/api/ApiConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
public class ApiConstants {
public static final String ACCOUNT = "account";
public static final String ACCOUNTS = "accounts";
public static final String ACCOUNT_NAME = "accountname";
public static final String ACCOUNT_TYPE = "accounttype";
public static final String ACCOUNT_ID = "accountid";
public static final String ACCOUNT_IDS = "accountids";
Expand All @@ -42,6 +43,7 @@ public class ApiConstants {
public static final String AS_NUMBER_ID = "asnumberid";
public static final String ASN_RANGE = "asnrange";
public static final String ASN_RANGE_ID = "asnrangeid";
public static final String API_KEY_FILTER = "apikeyfilter";
public static final String ASYNC_BACKUP = "asyncbackup";
public static final String AUTO_SELECT = "autoselect";
public static final String USER_API_KEY = "userapikey";
Expand Down Expand Up @@ -311,6 +313,7 @@ public class ApiConstants {
public static final String JOB_STATUS = "jobstatus";
public static final String KEEPALIVE_ENABLED = "keepaliveenabled";
public static final String KERNEL_VERSION = "kernelversion";
public static final String KEYPAIR_ID = "keypairid";
public static final String KEY = "key";
public static final String LABEL = "label";
public static final String LASTNAME = "lastname";
Expand Down Expand Up @@ -446,9 +449,9 @@ public class ApiConstants {
public static final String SCHEDULE = "schedule";
public static final String SCHEDULE_ID = "scheduleid";
public static final String SCOPE = "scope";
public static final String USER_SECRET_KEY = "usersecretkey";
public static final String SEARCH_BASE = "searchbase";
public static final String SECONDARY_IP = "secondaryip";
public static final String SECRET_KEY = "secretkey";
public static final String SECURITY_GROUP_IDS = "securitygroupids";
public static final String SECURITY_GROUP_NAMES = "securitygroupnames";
public static final String SECURITY_GROUP_NAME = "securitygroupname";
Expand All @@ -463,6 +466,7 @@ public class ApiConstants {
public static final String SHOW_RESOURCE_ICON = "showicon";
public static final String SHOW_INACTIVE = "showinactive";
public static final String SHOW_UNIQUE = "showunique";
public static final String SHOW_PERMISSIONS = "showpermissions";
public static final String SIGNATURE = "signature";
public static final String SIGNATURE_VERSION = "signatureversion";
public static final String SINCE = "since";
Expand Down Expand Up @@ -533,7 +537,6 @@ public class ApiConstants {
public static final String USERNAME = "username";
public static final String USER_CONFIGURABLE = "userconfigurable";
public static final String USER_SECURITY_GROUP_LIST = "usersecuritygrouplist";
public static final String USER_SECRET_KEY = "usersecretkey";
public static final String USE_VIRTUAL_NETWORK = "usevirtualnetwork";
public static final String UPDATE_IN_SEQUENCE = "updateinsequence";
public static final String VALUE = "value";
Expand Down Expand Up @@ -659,6 +662,7 @@ public class ApiConstants {
public static final String ROLE_TYPE = "roletype";
public static final String ROLE_NAME = "rolename";
public static final String PERMISSION = "permission";
public static final String PERMISSIONS = "permissions";
public static final String RULE = "rule";
public static final String RULES = "rules";
public static final String RULE_ID = "ruleid";
Expand Down Expand Up @@ -918,7 +922,7 @@ public class ApiConstants {
public static final String NSX_PROVIDER_PORT = "nsxproviderport";
public static final String NSX_CONTROLLER_ID = "nsxcontrollerid";
public static final String S3_ACCESS_KEY = "accesskey";
public static final String S3_SECRET_KEY = "secretkey";
public static final String SECRET_KEY = "secretkey";
public static final String S3_END_POINT = "endpoint";
public static final String S3_BUCKET_NAME = "bucket";
public static final String S3_SIGNER = "s3signer";
Expand Down
2 changes: 2 additions & 0 deletions api/src/main/java/org/apache/cloudstack/api/BaseAsyncCmd.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ public abstract class BaseAsyncCmd extends BaseCmd {
public static final String migrationSyncObject = "migration";
public static final String snapshotHostSyncObject = "snapshothost";
public static final String gslbSyncObject = "globalserverloadbalancer";
public static final String apiKeySyncObject = "apikey";
public static final String user = "user";

private Object job;

Expand Down
3 changes: 3 additions & 0 deletions api/src/main/java/org/apache/cloudstack/api/BaseCmd.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.apache.cloudstack.acl.ProjectRoleService;
import org.apache.cloudstack.acl.RoleService;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.acl.apikeypair.ApiKeyPairService;
import org.apache.cloudstack.affinity.AffinityGroupService;
import org.apache.cloudstack.alert.AlertService;
import org.apache.cloudstack.annotation.AnnotationService;
Expand Down Expand Up @@ -216,6 +217,8 @@ public static enum CommandType {
@Inject
public Ipv6Service ipv6Service;
@Inject
public ApiKeyPairService apiKeyPairService;
@Inject
public VnfTemplateManager vnfTemplateManager;
@Inject
public BucketApiService _bucketService;
Expand Down
Loading
Loading