Add conditional email access feature changes

apps-11010
Rajitha Kumara 1 year ago
parent d62e671a5c
commit 2ad8f54a46

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. 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.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>cea-mgt</artifactId>
<version>5.0.38-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.cea.mgt.common</artifactId>
<packaging>bundle</packaging>
<name>Entgra IoT - CEA Management Common</name>
<description>Entgra IoT - Conditional Email Access Management Common</description>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>CEA Management Common Bundle</Bundle-Description>
<Import-Package>
org.apache.commons.logging,
io.entgra.device.mgt.core.device.mgt.common.*
</Import-Package>
<Export-Package>
io.entgra.device.mgt.core.cea.mgt.common.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,66 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.DefaultAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.EmailOutlookAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.POPIMAPAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.WebOutlookAccessPolicy;
import java.util.Set;
public class AccessPolicy {
private DefaultAccessPolicy defaultAccessPolicy;
private Set<EmailOutlookAccessPolicy> emailOutlookAccessPolicy;
private POPIMAPAccessPolicy POPIMAPAccessPolicy;
private WebOutlookAccessPolicy webOutlookAccessPolicy;
public DefaultAccessPolicy getDefaultAccessPolicy() {
return defaultAccessPolicy;
}
public void setDefaultAccessPolicy(DefaultAccessPolicy defaultAccessPolicy) {
this.defaultAccessPolicy = defaultAccessPolicy;
}
public Set<EmailOutlookAccessPolicy> getEmailOutlookAccessPolicy() {
return emailOutlookAccessPolicy;
}
public void setEmailOutlookAccessPolicy(Set<EmailOutlookAccessPolicy> emailOutlookAccessPolicy) {
this.emailOutlookAccessPolicy = emailOutlookAccessPolicy;
}
public POPIMAPAccessPolicy getPOPIMAPAccessPolicy() {
return POPIMAPAccessPolicy;
}
public void setPOPIMAPAccessPolicy(POPIMAPAccessPolicy POPIMAPAccessPolicy) {
this.POPIMAPAccessPolicy = POPIMAPAccessPolicy;
}
public WebOutlookAccessPolicy getWebOutlookAccessPolicy() {
return webOutlookAccessPolicy;
}
public void setWebOutlookAccessPolicy(WebOutlookAccessPolicy webOutlookAccessPolicy) {
this.webOutlookAccessPolicy = webOutlookAccessPolicy;
}
}

@ -0,0 +1,84 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import java.util.Objects;
public class ActiveSyncDevice {
@JsonProperty(value = "DeviceID", required = true)
private String deviceId;
@JsonProperty(value = "FirstSyncTime", required = true)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
private Date firstSyncTime;
@JsonProperty(value = "UserPrincipalName", required = true)
private String userPrincipalName;
@JsonProperty(value = "Identity", required = true)
private String identity;
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public Date getFirstSyncTime() {
return firstSyncTime;
}
public void setFirstSyncTime(Date firstSyncTime) {
this.firstSyncTime = firstSyncTime;
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public String getUserPrincipalName() {
return userPrincipalName;
}
public void setUserPrincipalName(String userPrincipalName) {
this.userPrincipalName = userPrincipalName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ActiveSyncDevice)) return false;
ActiveSyncDevice that = (ActiveSyncDevice) o;
return Objects.equals(deviceId, that.deviceId)
&& Objects.equals(userPrincipalName, that.userPrincipalName);
}
@Override
public int hashCode() {
return Objects.hash(deviceId, userPrincipalName, identity);
}
}

@ -0,0 +1,74 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "ActiveSyncServer", description = "Active sync server properties")
public class ActiveSyncServer {
@JsonProperty(value = "key", required = true)
@ApiModelProperty(name = "key", value = "Key describing the server type according to cea-config.xml", required = true)
private String key;
@JsonProperty(value = "gatewayUrl", required = true)
@ApiModelProperty(name = "gatewayUrl", value = "Gateway URL of the active sync server", required = true)
private String gatewayUrl;
@JsonProperty(value = "client", required = true)
@ApiModelProperty(name = "client", value = "Client identifier", required = true)
private String client;
@JsonProperty(value = "secret", required = true)
@ApiModelProperty(name = "secret", value = "Client secret", required = true)
private String secret;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getGatewayUrl() {
return gatewayUrl;
}
public void setGatewayUrl(String gatewayUrl) {
this.gatewayUrl = gatewayUrl;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}

@ -0,0 +1,50 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean;
public class ActiveSyncServerUIConfiguration {
private String name;
private String description;
private String key;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}

@ -0,0 +1,32 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean;
public class AndroidEASIdentifier {
private String identifier;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
}

@ -0,0 +1,99 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean;
import java.io.Serializable;
import java.util.Date;
public class CEAPolicy implements Serializable {
private static final long serialVersionUID = -4578284769501447L;
private ActiveSyncServer activeSyncServer;
private AccessPolicy accessPolicy;
private GracePeriod gracePeriod;
private Date created;
private Date lastUpdated;
private Date lastSynced;
private boolean isSynced;
private int tenantId;
public boolean isSynced() {
return isSynced;
}
public void setSynced(boolean synced) {
isSynced = synced;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Date getLastSynced() {
return lastSynced;
}
public void setLastSynced(Date lastSynced) {
this.lastSynced = lastSynced;
}
public AccessPolicy getAccessPolicy() {
return accessPolicy;
}
public void setAccessPolicy(AccessPolicy accessPolicy) {
this.accessPolicy = accessPolicy;
}
public GracePeriod getGracePeriod() {
return gracePeriod;
}
public void setGracePeriod(GracePeriod gracePeriod) {
this.gracePeriod = gracePeriod;
}
public ActiveSyncServer getActiveSyncServer() {
return activeSyncServer;
}
public void setActiveSyncServer(ActiveSyncServer activeSyncServer) {
this.activeSyncServer = activeSyncServer;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
}

@ -0,0 +1,43 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean;
import java.util.List;
public class CEAPolicyEASWrapper {
private List<ActiveSyncDevice> activeSyncDevices;
private CEAPolicy ceaPolicy;
public List<ActiveSyncDevice> getActiveSyncDevices() {
return activeSyncDevices;
}
public void setActiveSyncDevices(List<ActiveSyncDevice> activeSyncDevices) {
this.activeSyncDevices = activeSyncDevices;
}
public CEAPolicy getCeaPolicy() {
return ceaPolicy;
}
public void setCeaPolicy(CEAPolicy ceaPolicy) {
this.ceaPolicy = ceaPolicy;
}
}

@ -0,0 +1,43 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.GraceAllowedPolicy;
public class GracePeriod {
private int gracePeriod;
private GraceAllowedPolicy graceAllowedPolicy;
public int getGracePeriod() {
return gracePeriod;
}
public void setGracePeriod(int gracePeriod) {
this.gracePeriod = gracePeriod;
}
public GraceAllowedPolicy getGraceAllowedPolicy() {
return graceAllowedPolicy;
}
public void setGraceAllowedPolicy(GraceAllowedPolicy graceAllowedPolicy) {
this.graceAllowedPolicy = graceAllowedPolicy;
}
}

@ -0,0 +1,123 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class MailboxProfile {
private final Set<String> activeSyncAllowedEASIdentifiers = new HashSet<>();
private final Set<String> activeSyncBlockedEASIdentifiers = new HashSet<>();
private String identity;
public Set<String> getActiveSyncAllowedEASIdentifiers() {
return activeSyncAllowedEASIdentifiers;
}
public Set<String> getActiveSyncBlockedEASIdentifiers() {
return activeSyncBlockedEASIdentifiers;
}
public void addActiveSyncAllowedEASIdentifier(String EASIdentifier) {
activeSyncAllowedEASIdentifiers.add(EASIdentifier);
}
public void addActiveSyncBlockEASIdentifier(String EASIdentifier) {
activeSyncBlockedEASIdentifiers.add(EASIdentifier);
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public String getAllowedEASIdentifierString() {
String add = "", remove = "";
if (!activeSyncAllowedEASIdentifiers.isEmpty()) {
Set<String> processedEASIdentifiers = new HashSet<>();
for (String activeSyncAllowedEASIdentifier : activeSyncAllowedEASIdentifiers) {
processedEASIdentifiers.add("'" + activeSyncAllowedEASIdentifier + "'");
}
add = String.join(",", processedEASIdentifiers);
}
if (!activeSyncBlockedEASIdentifiers.isEmpty()) {
Set<String> processedEASIdentifiers = new HashSet<>();
for (String activeSyncBlockedEASIdentifier : activeSyncBlockedEASIdentifiers) {
processedEASIdentifiers.add("'" + activeSyncBlockedEASIdentifier + "'");
}
remove = String.join(",", processedEASIdentifiers);
}
String begin = "@{", end = "}";
if (!add.isEmpty()) {
begin = begin + "Add=" + add + ";";
}
if (!remove.isEmpty()) {
begin = begin + "Remove=" + remove + ";";
}
return begin + end;
}
public String getBlockedEASIdentifierString() {
String add = "", remove = "";
if (!activeSyncAllowedEASIdentifiers.isEmpty()) {
Set<String> processedEASIdentifiers = new HashSet<>();
for (String activeSyncAllowedEASIdentifier : activeSyncAllowedEASIdentifiers) {
processedEASIdentifiers.add("'" + activeSyncAllowedEASIdentifier + "'");
}
remove = String.join(",", processedEASIdentifiers);
}
if (!activeSyncBlockedEASIdentifiers.isEmpty()) {
Set<String> processedEASIdentifiers = new HashSet<>();
for (String activeSyncBlockedEASIdentifier : activeSyncBlockedEASIdentifiers) {
processedEASIdentifiers.add("'" + activeSyncBlockedEASIdentifier + "'");
}
add = String.join(",", processedEASIdentifiers);
}
String begin = "@{", end = "}";
if (!add.isEmpty()) {
begin = begin + "Add=" + add + ";";
}
if (!remove.isEmpty()) {
begin = begin + "Remove=" + remove + ";";
}
return begin + end;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MailboxProfile)) return false;
MailboxProfile that = (MailboxProfile) o;
return Objects.equals(identity, that.identity);
}
@Override
public int hashCode() {
return Objects.hash(identity);
}
}

@ -0,0 +1,40 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.enums;
public enum DefaultAccessPolicy {
ALLOW("ALLOW"),
QUARANTINE("QUARANTINE"),
BLOCK("BLOCK");
private final String name;
DefaultAccessPolicy(String name) {
this.name = name;
}
public boolean equalsName(String thatName) {
return name.equals(thatName);
}
public String toString() {
return name;
}
}

@ -0,0 +1,42 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.enums;
public enum EmailOutlookAccessPolicy {
MOBILE_OUTLOOK_BLOCK("MOBILE_OUTLOOK_BLOCK"),
WINDOWS_OUTLOOK_BLOCK("WINDOWS_OUTLOOK_BLOCK"),
MAC_OUTLOOK_BLOCK("MAC_OUTLOOK_BLOCK"),
MAC_OLD_OUTLOOK_BLOCK("MAC_OLD_OUTLOOK_BLOCK"),
NOT_CONFIGURED("NOT_CONFIGURED");
private final String name;
EmailOutlookAccessPolicy(String name) {
this.name = name;
}
public boolean equalsName(String thatName) {
return name.equals(thatName);
}
public String toString() {
return name;
}
}

@ -0,0 +1,41 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.enums;
public enum GraceAllowedPolicy {
NEW_AND_EXISTING("NEW_AND_EXISTING"),
EXISTING_ONLY("EXISTING_ONLY"),
NEW_ONLY("NEW_ONLY"),
NOT_ALLOWED("NOT_ALLOWED");
private final String name;
GraceAllowedPolicy(String name) {
this.name = name;
}
public boolean equalsName(String thatName) {
return name.equals(thatName);
}
public String toString() {
return name;
}
}

@ -0,0 +1,40 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.enums;
public enum POPIMAPAccessPolicy {
ALLOW("ALLOW"),
BLOCK("BLOCK"),
NOT_CONFIGURED("NOT_CONFIGURED");
private final String name;
POPIMAPAccessPolicy(String name) {
this.name = name;
}
public boolean equalsName(String thatName) {
return name.equals(thatName);
}
public String toString() {
return name;
}
}

@ -0,0 +1,40 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.enums;
public enum WebOutlookAccessPolicy {
ALLOW("ALLOW"),
BLOCK("BLOCK"),
NOT_CONFIGURED("NOT_CONFIGURED");
private final String name;
WebOutlookAccessPolicy(String name) {
this.name = name;
}
public boolean equalsName(String thatName) {
return name.equals(thatName);
}
public String toString() {
return name;
}
}

@ -0,0 +1,40 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "CEAPolicyUIConfiguration")
public class CEAPolicyUIConfiguration {
private List<ServerUIConfiguration> serverUIConfigurations;
public List<ServerUIConfiguration> getServerConfigurations() {
return serverUIConfigurations;
}
@XmlElementWrapper(name = "ServerUIConfigurations", required = true)
@XmlElement(name = "ServerUIConfiguration")
public void setServerConfigurations(List<ServerUIConfiguration> serverUIConfigurations) {
this.serverUIConfigurations = serverUIConfigurations;
}
}

@ -0,0 +1,47 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Checkbox")
public class Checkbox {
private String label;
private String value;
public String getLabel() {
return label;
}
@XmlElement(name = "Label", required = true)
public void setLabel(String label) {
this.label = label;
}
public String getValue() {
return value;
}
@XmlElement(name = "Value", required = true)
public void setValue(String value) {
this.value = value;
}
}

@ -0,0 +1,50 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "CheckboxGroup")
public class CheckboxGroup {
private String name;
private List<Checkbox> checkboxes;
public String getName() {
return name;
}
@XmlElement(name = "Name", required = true)
public void setName(String name) {
this.name = name;
}
public List<Checkbox> getCheckboxes() {
return checkboxes;
}
@XmlElementWrapper(name = "Checkboxes", required = true)
@XmlElement(name = "Checkbox")
public void setCheckboxes(List<Checkbox> checkboxes) {
this.checkboxes = checkboxes;
}
}

@ -0,0 +1,137 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Entry")
public class Entry {
private String code;
private boolean required;
private String label;
private String tooltip;
private boolean hidden;
private Supportability supportability;
private String docLink;
private Input input;
private Select select;
private CheckboxGroup checkboxGroup;
private Switch inputSwitch;
public String getCode() {
return code;
}
@XmlElement(name = "Code", required = true)
public void setCode(String code) {
this.code = code;
}
public boolean isRequired() {
return required;
}
@XmlElement(name = "Required", defaultValue = "false")
public void setRequired(boolean required) {
this.required = required;
}
public String getLabel() {
return label;
}
@XmlElement(name = "Label", required = true)
public void setLabel(String label) {
this.label = label;
}
public String getTooltip() {
return tooltip;
}
@XmlElement(name = "Tooltip")
public void setTooltip(String tooltip) {
this.tooltip = tooltip;
}
public boolean isHidden() {
return hidden;
}
@XmlElement(name = "Hidden", defaultValue = "false")
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public Supportability getSupportability() {
return supportability;
}
@XmlElement(name = "Supportability")
public void setSupportability(Supportability supportability) {
this.supportability = supportability;
}
public String getDocLink() {
return docLink;
}
@XmlElement(name = "DocLink")
public void setDocLink(String docLink) {
this.docLink = docLink;
}
public Input getInput() {
return input;
}
@XmlElement(name = "Input", nillable = true)
public void setInput(Input input) {
this.input = input;
}
public Select getSelect() {
return select;
}
@XmlElement(name = "Select", nillable = true)
public void setSelect(Select select) {
this.select = select;
}
public CheckboxGroup getCheckboxGroup() {
return checkboxGroup;
}
@XmlElement(name = "CheckboxGroup", nillable = true)
public void setCheckboxGroup(CheckboxGroup checkboxGroup) {
this.checkboxGroup = checkboxGroup;
}
public Switch getInputSwitch() {
return inputSwitch;
}
@XmlElement(name = "Switch", nillable = true)
public void setInputSwitch(Switch inputSwitch) {
this.inputSwitch = inputSwitch;
}
}

@ -0,0 +1,57 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Input")
public class Input {
private String name;
private String placeholder;
private String type;
public String getName() {
return name;
}
@XmlElement(name = "Name", required = true)
public void setName(String name) {
this.name = name;
}
public String getPlaceholder() {
return placeholder;
}
@XmlElement(name = "Placeholder", required = true)
public void setPlaceholder(String placeholder) {
this.placeholder = placeholder;
}
public String getType() {
return type;
}
@XmlElement(name = "Type", required = true)
public void setType(String type) {
this.type = type;
}
}

@ -0,0 +1,47 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Option")
public class Option {
private String value;
private String label;
public String getValue() {
return value;
}
@XmlElement(name = "Value", required = true)
public void setValue(String value) {
this.value = value;
}
public String getLabel() {
return label;
}
@XmlElement(name = "Label", required = true)
public void setLabel(String label) {
this.label = label;
}
}

@ -0,0 +1,62 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "PolicyEntries")
public class PolicyEntries {
private List<Entry> activeSyncServerEntries;
private List<Entry> conditionalAccessPolicyEntries;
private List<Entry> gracePeriodEntries;
public List<Entry> getActiveSyncServerEntries() {
return activeSyncServerEntries;
}
@XmlElementWrapper(name = "ActiveSyncServerEntries", required = true)
@XmlElement(name = "Entry", required = true)
public void setActiveSyncServerEntries(List<Entry> activeSyncServerEntries) {
this.activeSyncServerEntries = activeSyncServerEntries;
}
public List<Entry> getConditionalAccessPolicyEntries() {
return conditionalAccessPolicyEntries;
}
@XmlElementWrapper(name = "ConditionalAccessPolicyEntries", required = true)
@XmlElement(name = "Entry", required = true)
public void setConditionalAccessPolicyEntries(List<Entry> conditionalAccessPolicyEntries) {
this.conditionalAccessPolicyEntries = conditionalAccessPolicyEntries;
}
public List<Entry> getGracePeriodEntries() {
return gracePeriodEntries;
}
@XmlElementWrapper(name = "GracePeriodEntries", required = true)
@XmlElement(name = "Entry", required = true)
public void setGracePeriodEntries(List<Entry> gracePeriodEntries) {
this.gracePeriodEntries = gracePeriodEntries;
}
}

@ -0,0 +1,60 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "Select")
public class Select {
private String name;
private String placeholder;
private List<Option> options;
public String getPlaceholder() {
return placeholder;
}
@XmlElement(name = "Placeholder", required = true)
public void setPlaceholder(String placeholder) {
this.placeholder = placeholder;
}
public String getName() {
return name;
}
@XmlElement(name = "Name", required = true)
public void setName(String name) {
this.name = name;
}
public List<Option> getOptions() {
return options;
}
@XmlElementWrapper(name = "Options", required = true)
@XmlElement(name = "Option")
public void setOptions(List<Option> options) {
this.options = options;
}
}

@ -0,0 +1,67 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ServerUIConfiguration")
public class ServerUIConfiguration {
private String name;
private String key;
private String description;
private PolicyEntries policyEntries;
public String getName() {
return name;
}
@XmlElement(name = "Name", required = true)
public void setName(String name) {
this.name = name;
}
public String getKey() {
return key;
}
@XmlElement(name = "Key", required = true)
public void setKey(String key) {
this.key = key;
}
public String getDescription() {
return description;
}
@XmlElement(name = "Description")
public void setDescription(String description) {
this.description = description;
}
public PolicyEntries getPolicyEntries() {
return policyEntries;
}
@XmlElement(name = "PolicyEntries")
public void setPolicyEntries(PolicyEntries policyEntries) {
this.policyEntries = policyEntries;
}
}

@ -0,0 +1,57 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Supportability")
public class Supportability {
private boolean support;
private String infoText;
private String defaultValue;
public boolean isSupport() {
return support;
}
@XmlElement(name = "Support", defaultValue = "true")
public void setSupport(boolean support) {
this.support = support;
}
public String getInfoText() {
return infoText;
}
@XmlElement(name = "InfoText")
public void setInfoText(String infoText) {
this.infoText = infoText;
}
public String getDefaultValue() {
return defaultValue;
}
@XmlElement(name = "DefaultValue")
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
}

@ -0,0 +1,47 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Switch")
public class Switch {
private String name;
private Toggle toggle;
public String getName() {
return name;
}
@XmlElement(name = "Name", required = true)
public void setName(String name) {
this.name = name;
}
public Toggle getToggle() {
return toggle;
}
@XmlElement(name = "Toggle", required = true)
public void setToggle(Toggle toggle) {
this.toggle = toggle;
}
}

@ -0,0 +1,67 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.bean.ui;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Toggle")
public class Toggle {
private String toggleOnValue;
private String toggleOffValue;
private String toggleOnLabel;
private String toggleOffLabel;
public String getToggleOnValue() {
return toggleOnValue;
}
@XmlElement(name = "ToggleOnValue", required = true)
public void setToggleOnValue(String toggleOnValue) {
this.toggleOnValue = toggleOnValue;
}
public String getToggleOffValue() {
return toggleOffValue;
}
@XmlElement(name = "ToggleOffValue", required = true)
public void setToggleOffValue(String toggleOffValue) {
this.toggleOffValue = toggleOffValue;
}
public String getToggleOnLabel() {
return toggleOnLabel;
}
@XmlElement(name = "ToggleOnLabel", required = true)
public void setToggleOnLabel(String toggleOnLabel) {
this.toggleOnLabel = toggleOnLabel;
}
public String getToggleOffLabel() {
return toggleOffLabel;
}
@XmlElement(name = "ToggleOffLabel", required = true)
public void setToggleOffLabel(String toggleOffLabel) {
this.toggleOffLabel = toggleOffLabel;
}
}

@ -0,0 +1,31 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.exception;
public class CEAConfigManagerException extends Exception {
public CEAConfigManagerException(String msg) {
super(msg);
}
public CEAConfigManagerException(String msg, Throwable t) {
super(msg, t);
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.exception;
public class CEAEnforcementException extends Exception {
public CEAEnforcementException(String msg) {
super(msg);
}
public CEAEnforcementException(String msg, Throwable t) {
super(msg, t);
}
}

@ -0,0 +1,34 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.exception;
public class CEAManagementException extends Exception {
public CEAManagementException(String msg) {
super(msg);
}
public CEAManagementException(String msg, Throwable t) {
super(msg, t);
}
public CEAManagementException() {
super();
}
}

@ -0,0 +1,26 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.exception;
public class CEAPolicyAlreadyExistsException extends Exception {
public CEAPolicyAlreadyExistsException(String msg) {
super(msg);
}
}

@ -0,0 +1,26 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.exception;
public class CEAPolicyNotFoundException extends Exception {
public CEAPolicyNotFoundException(String msg) {
super(msg);
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.exception;
public class EnforcementServiceManagerException extends Exception {
public EnforcementServiceManagerException(String msg) {
super(msg);
}
public EnforcementServiceManagerException(String msg, Throwable t) {
super(msg, t);
}
}

@ -0,0 +1,65 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.service;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAEnforcementException;
public interface CEAEnforcementService {
/**
* Sync default access policy with active sync server
*
* @param ceaPolicy {@link CEAPolicy}
* @throws CEAEnforcementException Throws when error occurred while enforcing the policy
*/
void enforceDefaultAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException;
/**
* Enforce email outlook access policy
*
* @param ceaPolicy {@link CEAPolicy}
* @throws CEAEnforcementException Throws when error occurred while enforcing the policy
*/
void enforceEmailOutlookAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException;
/**
* Enforce POP/IMAP access policy
*
* @param ceaPolicy {@link CEAPolicy}
* @throws CEAEnforcementException Throws when error occurred while enforcing the policy
*/
void enforcePOPIMAPAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException;
/**
* Enforce web outlook access policy
*
* @param ceaPolicy {@link CEAPolicy}
* @throws CEAEnforcementException Throws when error occurred while enforcing the policy
*/
void enforceWebOutlookAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException;
/**
* Enforce conditional email access policy honoring to the grace period
*
* @param ceaPolicy {@link CEAPolicy}
* @throws CEAEnforcementException Throws when error occurred while enforcing the policy
*/
void enforceConditionalAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException;
}

@ -0,0 +1,79 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.service;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ui.CEAPolicyUIConfiguration;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAManagementException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyAlreadyExistsException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyNotFoundException;
public interface CEAManagementService {
/**
* Retrieve conditional access policy UI configuration
*
* @return {@link CEAPolicyUIConfiguration}
* @throws CEAManagementException Throws when retrieving UI configurations
*/
CEAPolicyUIConfiguration getCEAPolicyUIConfiguration() throws CEAManagementException;
/**
* Create conditional access policy
*
* @param ceaPolicy {@link CEAPolicy}
* @return {@link CEAPolicy} Created conditional access policy
* @throws CEAManagementException Throws when error occurred while creating the policy
* @throws CEAPolicyAlreadyExistsException Throws when conflict occurs
*/
CEAPolicy createCEAPolicy(CEAPolicy ceaPolicy) throws CEAManagementException, CEAPolicyAlreadyExistsException;
/**
* Retrieve conditional access policy for the tenant
*
* @return {@link CEAPolicy}
* @throws CEAManagementException Throws when error occurred while retrieving the policy
*/
CEAPolicy retrieveCEAPolicy() throws CEAManagementException;
/**
* Update conditional access policy
*
* @param ceaPolicy {@link CEAPolicy}
* @return {@link CEAPolicy} Returns update conditional access policy
* @throws CEAManagementException Throws when error occurred while updating the policy
* @throws CEAPolicyNotFoundException Throws when policy doesn't exist
*/
CEAPolicy updateCEAPolicy(CEAPolicy ceaPolicy) throws CEAManagementException, CEAPolicyNotFoundException;
/**
* Delete the conditional access policy
*
* @throws CEAManagementException Throws when error occurred while deleting the policy
* @throws CEAPolicyNotFoundException Throws when a conditional access policy doesn't exist
*/
void deleteCEAPolicy() throws CEAManagementException, CEAPolicyNotFoundException;
/**
* Trigger sync task with active sync server
*
* @throws CEAManagementException Throws when error occurred while triggering the sync operation
*/
void syncNow() throws CEAManagementException;
}

@ -0,0 +1,34 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.service;
import io.entgra.device.mgt.core.cea.mgt.common.exception.EnforcementServiceManagerException;
public interface EnforcementServiceManager {
/**
* Return enforcement service implementation for the specified enforcement service class name
*
* @param enforcementServiceClassName Enforcement service class name
* @return Return enforcement service implementation
* @throws EnforcementServiceManagerException Throws when error occurred while generating enforcement service
*/
CEAEnforcementService getEnforcementService(String enforcementServiceClassName)
throws EnforcementServiceManagerException;
}

@ -0,0 +1,25 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.util;
public class Constants {
public static final String EAS_KEY = "ENTGRA";
public static final int MAX_GRACE_PERIOD_IN_DAYS = 30;
}

@ -0,0 +1,42 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.common.util;
import io.entgra.device.mgt.core.cea.mgt.common.bean.AndroidEASIdentifier;
public class EASMgtUtil {
public static AndroidEASIdentifier generateAndroidEASIdentifier(String androidId) {
AndroidEASIdentifier androidEASIdentifier = new AndroidEASIdentifier();
androidEASIdentifier.setIdentifier((Constants.EAS_KEY + androidId).toUpperCase());
return androidEASIdentifier;
}
public static boolean isManageByUEM(AndroidEASIdentifier androidEASIdentifier) {
if (androidEASIdentifier == null)
throw new IllegalArgumentException("Null retrieved for Android EAS Identifier");
return androidEASIdentifier.getIdentifier().startsWith(Constants.EAS_KEY);
}
public static boolean isManageByUEM(String androidEASIdentifier) {
if (androidEASIdentifier == null)
throw new IllegalArgumentException("Null retrieved for Android EAS Identifier");
return androidEASIdentifier.startsWith(Constants.EAS_KEY);
}
}

@ -0,0 +1,115 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. 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.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>cea-mgt</artifactId>
<version>5.0.38-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.cea.mgt.core</artifactId>
<packaging>bundle</packaging>
<name>Entgra IoT - CEA Management Core</name>
<description>Entgra IoT - Conditional Email Access Management Core</description>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>CEA Management Core Bundle</Bundle-Description>
<Private-Package>io.entgra.device.mgt.core.cea.mgt.core.internal</Private-Package>
<Import-Package>
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.apache.commons.logging,
org.wso2.carbon.utils,
org.wso2.carbon.context.*,
org.wso2.carbon.ndatasource.core,
io.entgra.device.mgt.core.cea.mgt.enforce.*,
io.entgra.device.mgt.core.cea.mgt.common.*,
io.entgra.device.mgt.core.device.mgt.common.*,
io.entgra.device.mgt.core.device.mgt.core.*,
org.wso2.carbon.ntask.*
</Import-Package>
<Export-Package>
!io.entgra.device.mgt.core.cea.mgt.core.internal,
io.entgra.device.mgt.core.cea.mgt.core.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.cea.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.cea.mgt.enforce</artifactId>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.commons</groupId>
<artifactId>org.wso2.carbon.ntask.core</artifactId>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.core</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,57 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.bean;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ActiveSyncServerConfiguration")
public class ActiveSyncServerConfiguration {
private String key;
private String gatewayService;
private String enforcementService;
public String getKey() {
return key;
}
@XmlElement(name = "Key", required = true)
public void setKey(String key) {
this.key = key;
}
public String getGatewayService() {
return gatewayService;
}
@XmlElement(name = "GatewayService", required = true)
public void setGatewayService(String gatewayService) {
this.gatewayService = gatewayService;
}
public String getEnforcementService() {
return enforcementService;
}
@XmlElement(name = "EnforcementService", required = true)
public void setEnforcementService(String enforcementService) {
this.enforcementService = enforcementService;
}
}

@ -0,0 +1,72 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.bean;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServer;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import java.util.Objects;
@XmlRootElement(name = "CEAConfiguration")
public class CEAConfiguration {
private List<ActiveSyncServerConfiguration> activeSyncServerConfigurations;
private MonitoringConfiguration monitoringConfiguration;
public List<ActiveSyncServerConfiguration> getActiveSyncServerConfigurations() {
return activeSyncServerConfigurations;
}
@XmlElementWrapper(name = "ActiveSyncServerConfigurations", required = true)
@XmlElement(name = "ActiveSyncServerConfiguration", required = true)
public void setActiveSyncServerConfigurations(List<ActiveSyncServerConfiguration> activeSyncServerConfigurations) {
this.activeSyncServerConfigurations = activeSyncServerConfigurations;
}
public ActiveSyncServerConfiguration getActiveSyncServerConfiguration(ActiveSyncServer activeSyncServer) {
ActiveSyncServerConfiguration activeSyncServerConfiguration = null;
for (ActiveSyncServerConfiguration config : activeSyncServerConfigurations) {
if (Objects.equals(config.getKey(), activeSyncServer.getKey())) {
activeSyncServerConfiguration = config;
}
}
return activeSyncServerConfiguration;
}
public boolean isServerSupport(ActiveSyncServer activeSyncServer) {
for (ActiveSyncServerConfiguration config : activeSyncServerConfigurations) {
if (Objects.equals(config.getKey(), activeSyncServer.getKey())) {
return true;
}
}
return false;
}
public MonitoringConfiguration getMonitoringConfiguration() {
return monitoringConfiguration;
}
@XmlElement(name = "MonitoringConfiguration", required = true)
public void setMonitoringConfiguration(MonitoringConfiguration monitoringConfiguration) {
this.monitoringConfiguration = monitoringConfiguration;
}
}

@ -0,0 +1,57 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.bean;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "MonitoringConfiguration")
public class MonitoringConfiguration {
private boolean monitoringEnable;
private long monitoringFrequency;
private String monitoringClazz;
public boolean isMonitoringEnable() {
return monitoringEnable;
}
@XmlElement(name = "MonitoringEnable", required = true)
public void setMonitoringEnable(boolean monitoringEnable) {
this.monitoringEnable = monitoringEnable;
}
public long getMonitoringFrequency() {
return monitoringFrequency;
}
@XmlElement(name = "MonitoringFrequency", required = true)
public void setMonitoringFrequency(long monitoringFrequency) {
this.monitoringFrequency = monitoringFrequency;
}
public String getMonitoringClazz() {
return monitoringClazz;
}
@XmlElement(name = "MonitoringClazz", required = true)
public void setMonitoringClazz(String monitoringClazz) {
this.monitoringClazz = monitoringClazz;
}
}

@ -0,0 +1,116 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.config;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ui.CEAPolicyUIConfiguration;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAConfigManagerException;
import io.entgra.device.mgt.core.cea.mgt.core.bean.CEAConfiguration;
import io.entgra.device.mgt.core.cea.mgt.core.config.datasource.CEADeviceMgtConfiguration;
import io.entgra.device.mgt.core.cea.mgt.core.config.datasource.CEAPolicyManagementRepository;
import io.entgra.device.mgt.core.cea.mgt.core.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public class CEAConfigManager {
private static final Log log = LogFactory.getLog(CEAConfigManager.class);
private static final String CDM_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + File.separator +
Constants.CDM_CONFIG_FILE_NAME;
private static final String CEA_UI_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + File.separator +
Constants.CEA_POLICY_UI_FILE_NAME;
private static final String CEA_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + File.separator +
Constants.CEA_CONFIG_FILE_NAME;
private CEAPolicyManagementRepository ceaPolicyManagementRepository;
private CEAConfiguration ceaConfiguration;
private CEAPolicyUIConfiguration ceaPolicyUIConfiguration;
CEAConfigManager() {
}
public static CEAConfigManager getInstance() {
return CEAConfigManagerHolder.INSTANCE;
}
private <T> T initConfig(String docPath, Class<T> configClass) throws JAXBException {
File doc = new File(docPath);
JAXBContext jaxbContext = JAXBContext.newInstance(configClass);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return configClass.cast(jaxbUnmarshaller.unmarshal(doc));
}
private void initDatasourceConfig() throws JAXBException {
ceaPolicyManagementRepository = initConfig(CDM_CONFIG_PATH, CEADeviceMgtConfiguration.class)
.getCeaPolicyManagementRepository();
}
private void initCEAPConfig() throws JAXBException {
ceaConfiguration = initConfig(CEA_CONFIG_PATH, CEAConfiguration.class);
}
private void initCEAPolicyUIConfig() throws JAXBException {
ceaPolicyUIConfiguration = initConfig(CEA_UI_CONFIG_PATH, CEAPolicyUIConfiguration.class);
}
public CEAPolicyManagementRepository getCeaPolicyManagementRepository() throws CEAConfigManagerException {
try {
if (ceaPolicyManagementRepository == null) {
initDatasourceConfig();
}
return ceaPolicyManagementRepository;
} catch (JAXBException e) {
String msg = "Error occurred while initializing datasource configuration";
throw new CEAConfigManagerException(msg, e);
}
}
public CEAConfiguration getCeaConfiguration() throws CEAConfigManagerException {
try {
if (ceaConfiguration == null) {
initCEAPConfig();
}
return ceaConfiguration;
} catch (JAXBException e) {
String msg = "Error occurred while initializing CEA configuration";
throw new CEAConfigManagerException(msg, e);
}
}
public CEAPolicyUIConfiguration getCeaPolicyUIConfiguration() throws CEAConfigManagerException {
try {
if (ceaPolicyUIConfiguration == null) {
initCEAPolicyUIConfig();
}
return ceaPolicyUIConfiguration;
} catch (JAXBException e) {
String msg = "Error occurred while initializing policy UI configuration";
throw new CEAConfigManagerException(msg, e);
}
}
private static class CEAConfigManagerHolder {
public static final CEAConfigManager INSTANCE = new CEAConfigManager();
}
}

@ -0,0 +1,37 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.config.datasource;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DataSourceConfiguration")
public class CEADatasourceConfiguration {
private JNDILookupDefinition jndiLookupDefinition;
public JNDILookupDefinition getJndiLookupDefinition() {
return jndiLookupDefinition;
}
@XmlElement(name = "JndiLookupDefinition", nillable = true)
public void setJndiLookupDefinition(JNDILookupDefinition jndiLookupDefinition) {
this.jndiLookupDefinition = jndiLookupDefinition;
}
}

@ -0,0 +1,37 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.config.datasource;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DeviceMgtConfiguration")
public class CEADeviceMgtConfiguration {
private CEAPolicyManagementRepository ceaPolicyManagementRepository;
public CEAPolicyManagementRepository getCeaPolicyManagementRepository() {
return ceaPolicyManagementRepository;
}
@XmlElement(name = "ManagementRepository", nillable = false)
public void setCeaPolicyManagementRepository(CEAPolicyManagementRepository ceaPolicyManagementRepository) {
this.ceaPolicyManagementRepository = ceaPolicyManagementRepository;
}
}

@ -0,0 +1,37 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.config.datasource;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ManagementRepository")
public class CEAPolicyManagementRepository {
private CEADatasourceConfiguration ceaDatasourceConfiguration;
@XmlElement(name = "DataSourceConfiguration", nillable = false)
public CEADatasourceConfiguration getDataSourceConfig() {
return ceaDatasourceConfiguration;
}
public void setDataSourceConfig(CEADatasourceConfiguration ceaDatasourceConfiguration) {
this.ceaDatasourceConfiguration = ceaDatasourceConfiguration;
}
}

@ -0,0 +1,74 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.config.datasource;
import javax.xml.bind.annotation.*;
import java.util.List;
@XmlRootElement(name = "JndiLookupDefinition")
public class JNDILookupDefinition {
private String jndiName;
private List<JNDIProperty> jndiProperties;
@XmlElement(name = "Name", nillable = false)
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
@XmlElementWrapper(name = "Environment", nillable = false)
@XmlElement(name = "Property", nillable = false)
public List<JNDIProperty> getJndiProperties() {
return jndiProperties;
}
public void setJndiProperties(List<JNDIProperty> jndiProperties) {
this.jndiProperties = jndiProperties;
}
@XmlRootElement(name = "Property")
public static class JNDIProperty {
private String name;
private String value;
@XmlAttribute(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlValue
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}

@ -0,0 +1,76 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.dao;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.core.exception.CEAPolicyManagementDAOException;
import java.util.Date;
import java.util.List;
/**
* DAO class for Conditional Email Access management
*/
public interface CEAPolicyDAO {
/**
* Create CEA policy for a tenant if a CEA policy not already exists
* @param ceaPolicy {@link CEAPolicy}
* @return Created CEA policy
* @throws CEAPolicyManagementDAOException Throws when error occurred while creating CEA policy
*/
CEAPolicy createCEAPolicy(CEAPolicy ceaPolicy) throws CEAPolicyManagementDAOException;
/**
* Retrieve CEA policy
* @return {@link CEAPolicy}
* @throws CEAPolicyManagementDAOException Throws when error occurred while retrieving CEA policy
*/
CEAPolicy retrieveCEAPolicy() throws CEAPolicyManagementDAOException;
/**
* Retrieve all available CEA policies
* @return List of CEA policies
* @throws CEAPolicyManagementDAOException Throws when error occurred while retrieving CEA policies
*/
List<CEAPolicy> retrieveAllCEAPolicies() throws CEAPolicyManagementDAOException;
/**
* Update CEA policy
* @param existingCEAPolicy Existing CEA policy
* @param ceaPolicy Updated CEA policy
* @return Updated CEA policy
* @throws CEAPolicyManagementDAOException Throws when error occurred while updating CEA policy
*/
CEAPolicy updateCEAPolicy(CEAPolicy existingCEAPolicy, CEAPolicy ceaPolicy) throws CEAPolicyManagementDAOException;
/**
* Update last sync time with the active sync server
* @param status True on a successful sync, otherwise false
* @param syncedTime Synced time stamp
* @throws CEAPolicyManagementDAOException Throws when error occurred while updating sync time
*/
void updateLastSyncedTime(boolean status, Date syncedTime) throws CEAPolicyManagementDAOException;
/**
* Delete CEA policy
* @throws CEAPolicyManagementDAOException Throws when error occurred while deleting CEA policy
*/
void deleteCEAPolicy() throws CEAPolicyManagementDAOException;
}

@ -0,0 +1,204 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.dao.factory;
import io.entgra.device.mgt.core.cea.mgt.core.config.datasource.CEADatasourceConfiguration;
import io.entgra.device.mgt.core.cea.mgt.core.config.datasource.JNDILookupDefinition;
import io.entgra.device.mgt.core.cea.mgt.core.dao.CEAPolicyDAO;
import io.entgra.device.mgt.core.cea.mgt.core.dao.impl.GenericCEAPolicyDAO;
import io.entgra.device.mgt.core.cea.mgt.core.exception.CEAPolicyManagementDAOException;
import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnsupportedDatabaseEngineException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.List;
public class CEAPolicyManagementDAOFactory {
private static final Log log = LogFactory.getLog(CEAPolicyManagementDAOFactory.class);
private static final ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
private static DataSource dataSource;
private static String productName;
public static void init(CEADatasourceConfiguration ceaDatasourceConfiguration) {
dataSource = resolveDatasource(ceaDatasourceConfiguration);
if (dataSource == null) {
throw new IllegalStateException("Datasource is not initialized properly");
}
try {
productName = dataSource.getConnection().getMetaData().getDatabaseProductName();
} catch (SQLException e) {
log.error("Error occurred while initializing database product name");
}
}
private static DataSource resolveDatasource(CEADatasourceConfiguration ceaDatasourceConfiguration) {
if (ceaDatasourceConfiguration == null) {
throw new IllegalArgumentException("Null is retrieved for Datasource configuration");
}
JNDILookupDefinition jndiLookupDefinition = ceaDatasourceConfiguration.getJndiLookupDefinition();
if (jndiLookupDefinition == null) {
throw new IllegalArgumentException("Null is retrieved for JNDI lookup definition");
}
String datasourceName = jndiLookupDefinition.getJndiName();
List<JNDILookupDefinition.JNDIProperty> jndiProperties = ceaDatasourceConfiguration.getJndiLookupDefinition().getJndiProperties();
if (jndiProperties == null || jndiProperties.isEmpty()) {
return lookupDatasource(datasourceName);
}
Hashtable<Object, Object> jndiPropertiesTable = new Hashtable<>();
for (JNDILookupDefinition.JNDIProperty property : jndiProperties) {
jndiPropertiesTable.put(property.getName(), property.getValue());
}
return lookupDatasource(datasourceName, jndiPropertiesTable);
}
private static DataSource lookupDatasource(String datasourceName) {
try {
return InitialContext.doLookup(datasourceName);
} catch (NamingException e) {
String msg = "Error occurred while JNDI lookup for the datasource";
throw new IllegalStateException(msg, e);
}
}
private static DataSource lookupDatasource(String datasourceName, Hashtable<Object, Object> jndiProperties) {
try {
InitialContext initialContext = new InitialContext(jndiProperties);
return (DataSource) initialContext.lookup(datasourceName);
} catch (NamingException e) {
String msg = "Error occurred while JNDI lookup for the datasource";
throw new IllegalStateException(msg, e);
}
}
public static CEAPolicyDAO getCEAPolicyDAO() {
if (productName == null) {
throw new IllegalStateException("Database is not initialized properly");
}
switch (productName) {
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_DB2:
return new GenericCEAPolicyDAO();
default:
throw new UnsupportedDatabaseEngineException("Unsupported database product " + productName);
}
}
public static void openConnection() throws CEAPolicyManagementDAOException {
Connection connection = currentConnection.get();
if (connection != null) {
throw new IllegalTransactionStateException("A transaction is already active within the context of " +
"this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
"transaction is already active is a sign of improper transaction handling");
}
try {
connection = dataSource.getConnection();
currentConnection.set(connection);
} catch (SQLException e) {
String msg = "Error encountered while acquiring connection from the datasource";
log.error(msg, e);
throw new CEAPolicyManagementDAOException(msg, e);
}
}
public static Connection getConnection() {
Connection connection = currentConnection.get();
if (connection == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
}
return connection;
}
public static void closeConnection() {
Connection connection = currentConnection.get();
if (connection == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
}
try {
connection.close();
} catch (SQLException e) {
log.warn("Error encountered while closing the connection", e);
}
currentConnection.remove();
}
public static void beginTransaction() throws CEAPolicyManagementDAOException {
Connection connection = currentConnection.get();
if (connection == null) {
throw new IllegalTransactionStateException("A transaction is already active within the context of " +
"this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
"transaction is already active is a sign of improper transaction handling");
}
try {
connection = dataSource.getConnection();
connection.setAutoCommit(false);
currentConnection.set(connection);
} catch (SQLException e) {
String msg = "Error encountered while acquiring connection from the datasource";
log.error(msg, e);
throw new CEAPolicyManagementDAOException(msg, e);
}
}
public static void rollbackTransaction() {
Connection connection = currentConnection.get();
if (connection == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
}
try {
connection.rollback();
} catch (SQLException e) {
log.error("Error encountered while performing rollback operation on transaction", e);
}
}
public static void commitTransaction() {
Connection connection = currentConnection.get();
if (connection == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
}
try {
connection.commit();
} catch (SQLException e) {
log.error("Error encountered while committing the transaction", e);
}
}
}

@ -0,0 +1,249 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.dao.impl;
import com.google.gson.Gson;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServer;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.core.dao.CEAPolicyDAO;
import io.entgra.device.mgt.core.cea.mgt.core.dao.factory.CEAPolicyManagementDAOFactory;
import io.entgra.device.mgt.core.cea.mgt.core.dto.CEAPolicyContent;
import io.entgra.device.mgt.core.cea.mgt.core.dto.CEAPolicyDTO;
import io.entgra.device.mgt.core.cea.mgt.core.exception.CEAPolicyManagementDAOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
public class AbstractCEAPolicyDAO implements CEAPolicyDAO {
private static final Log log = LogFactory.getLog(AbstractCEAPolicyDAO.class);
private static final Gson gson = new Gson();
@Override
public CEAPolicy createCEAPolicy(CEAPolicy ceaPolicy) throws CEAPolicyManagementDAOException {
ceaPolicy.setCreated(new Date());
ceaPolicy.setLastUpdated(new Date());
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
ceaPolicy.setTenantId(tenantId);
CEAPolicyDTO ceaPolicyDTO = toCEAPolicyDTO(ceaPolicy);
String query = "INSERT INTO DM_CEA_POLICIES " +
"(POLICY_CONTENT, " +
"CREATED_TIMESTAMP, " +
"UPDATED_TIMESTAMP, " +
"TENANT_ID) VALUES (?, ?, ?, ?)";
Connection connection = CEAPolicyManagementDAOFactory.getConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, ceaPolicyDTO.getPolicyContent());
preparedStatement.setTimestamp(2, ceaPolicyDTO.getCreatedTimestamp());
preparedStatement.setTimestamp(3, ceaPolicyDTO.getUpdatedTimestamp());
preparedStatement.setInt(4, tenantId);
preparedStatement.execute();
} catch (SQLException e) {
String msg = "Error occurred while creating CEA policy for tenant id : " + tenantId;
log.error(msg, e);
throw new CEAPolicyManagementDAOException(msg, e);
}
return ceaPolicy;
}
@Override
public CEAPolicy retrieveCEAPolicy() throws CEAPolicyManagementDAOException {
CEAPolicy ceaPolicy = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String query = "SELECT POLICY_CONTENT, " +
"CREATED_TIMESTAMP, " +
"UPDATED_TIMESTAMP, " +
"LAST_SYNCED_TIMESTAMP, " +
"IS_SYNCED " +
"FROM DM_CEA_POLICIES WHERE TENANT_ID = ?";
Connection connection = CEAPolicyManagementDAOFactory.getConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setInt(1, tenantId);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
CEAPolicyDTO ceaPolicyDTO;
while (resultSet.next()) {
ceaPolicyDTO = new CEAPolicyDTO();
ceaPolicyDTO.setPolicyContent(resultSet.getString("POLICY_CONTENT"));
ceaPolicyDTO.setCreatedTimestamp(resultSet.getTimestamp("CREATED_TIMESTAMP"));
ceaPolicyDTO.setUpdatedTimestamp(resultSet.getTimestamp("UPDATED_TIMESTAMP"));
ceaPolicyDTO.setLastSyncedTimestamp(resultSet.getTimestamp("LAST_SYNCED_TIMESTAMP"));
ceaPolicyDTO.setSynced(resultSet.getBoolean("IS_SYNCED"));
ceaPolicyDTO.setTenantId(tenantId);
ceaPolicy = toCEAPolicy(ceaPolicyDTO);
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving CEA policy for tenant id : " + tenantId;
log.error(msg, e);
throw new CEAPolicyManagementDAOException(msg, e);
}
return ceaPolicy;
}
@Override
public List<CEAPolicy> retrieveAllCEAPolicies() throws CEAPolicyManagementDAOException {
List<CEAPolicy> ceaPolicies = new ArrayList<>();
String query = "SELECT POLICY_CONTENT, " +
"CREATED_TIMESTAMP, " +
"UPDATED_TIMESTAMP, " +
"LAST_SYNCED_TIMESTAMP, " +
"IS_SYNCED, " +
"TENANT_ID FROM DM_CEA_POLICIES";
Connection connection = CEAPolicyManagementDAOFactory.getConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
CEAPolicyDTO ceaPolicyDTO;
while (resultSet.next()) {
ceaPolicyDTO = new CEAPolicyDTO();
ceaPolicyDTO.setPolicyContent(resultSet.getString("POLICY_CONTENT"));
ceaPolicyDTO.setCreatedTimestamp(resultSet.getTimestamp("CREATED_TIMESTAMP"));
ceaPolicyDTO.setUpdatedTimestamp(resultSet.getTimestamp("UPDATED_TIMESTAMP"));
ceaPolicyDTO.setLastSyncedTimestamp(resultSet.getTimestamp("LAST_SYNCED_TIMESTAMP"));
ceaPolicyDTO.setSynced(resultSet.getBoolean("IS_SYNCED"));
ceaPolicyDTO.setTenantId(resultSet.getInt("TENANT_ID"));
ceaPolicies.add(toCEAPolicy(ceaPolicyDTO));
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving All CEA policies";
log.error(msg, e);
throw new CEAPolicyManagementDAOException(msg, e);
}
return ceaPolicies;
}
@Override
public CEAPolicy updateCEAPolicy(CEAPolicy existingCEAPolicy, CEAPolicy ceaPolicy) throws CEAPolicyManagementDAOException {
ceaPolicy.setCreated(existingCEAPolicy.getCreated());
ceaPolicy.setSynced(existingCEAPolicy.isSynced());
ceaPolicy.setLastSynced(existingCEAPolicy.getLastSynced());
ceaPolicy.setLastUpdated(new Date());
CEAPolicyDTO ceaPolicyDTO = toCEAPolicyDTO(ceaPolicy);
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String query = "UPDATE DM_CEA_POLICIES " +
"SET POLICY_CONTENT = ?, " +
"UPDATED_TIMESTAMP = ? " +
"WHERE TENANT_ID = ?";
Connection connection = CEAPolicyManagementDAOFactory.getConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, ceaPolicyDTO.getPolicyContent());
preparedStatement.setTimestamp(2, ceaPolicyDTO.getUpdatedTimestamp());
preparedStatement.setInt(3, tenantId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
String msg = "Error occurred while updating CEA policy for tenant id : " + tenantId;
log.error(msg, e);
throw new CEAPolicyManagementDAOException(msg, e);
}
return ceaPolicy;
}
@Override
public void updateLastSyncedTime(boolean status, Date syncedTime) throws CEAPolicyManagementDAOException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String query = "UPDATE DM_CEA_POLICIES " +
"SET LAST_SYNCED_TIMESTAMP = ?, " +
"IS_SYNCED = ? " +
"WHERE TENANT_ID = ?";
Connection connection = CEAPolicyManagementDAOFactory.getConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setTimestamp(1, new Timestamp(syncedTime.getTime()));
preparedStatement.setBoolean(2, status);
preparedStatement.setInt(3, tenantId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
String msg = "Error occurred while updating CEA policy last sync timestamp for tenant id : " + tenantId;
log.error(msg, e);
throw new CEAPolicyManagementDAOException(msg, e);
}
}
@Override
public void deleteCEAPolicy() throws CEAPolicyManagementDAOException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String query = "DELETE FROM DM_CEA_POLICIES WHERE TENANT_ID = ?";
Connection connection = CEAPolicyManagementDAOFactory.getConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setInt(1, tenantId);
preparedStatement.execute();
} catch (SQLException e) {
String msg = "Error occurred while deleting CEA policy for tenant id : " + tenantId;
log.error(msg, e);
throw new CEAPolicyManagementDAOException(msg, e);
}
}
private CEAPolicyDTO toCEAPolicyDTO(CEAPolicy ceaPolicy) throws CEAPolicyManagementDAOException {
if (ceaPolicy == null) {
throw new CEAPolicyManagementDAOException("CEAPolicy can't be null");
}
CEAPolicyDTO ceaPolicyDTO = new CEAPolicyDTO();
CEAPolicyContent ceaPolicyContent = new CEAPolicyContent();
ActiveSyncServer activeSyncServer = new ActiveSyncServer();
activeSyncServer.setSecret(Base64.getEncoder().
encodeToString(ceaPolicy.getActiveSyncServer().getSecret().getBytes(StandardCharsets.UTF_8)));
activeSyncServer.setClient(ceaPolicy.getActiveSyncServer().getClient());
activeSyncServer.setKey(ceaPolicy.getActiveSyncServer().getKey());
activeSyncServer.setGatewayUrl(ceaPolicy.getActiveSyncServer().getGatewayUrl());
ceaPolicyContent.setAccessPolicy(ceaPolicy.getAccessPolicy());
ceaPolicyContent.setGracePeriod(ceaPolicy.getGracePeriod());
ceaPolicyContent.setActiveSyncServer(activeSyncServer);
ceaPolicyDTO.setPolicyContent(gson.toJson(ceaPolicyContent));
ceaPolicyDTO.setSynced(ceaPolicy.isSynced());
ceaPolicyDTO.setCreatedTimestamp(new Timestamp(ceaPolicy.getCreated().getTime()));
ceaPolicyDTO.setUpdatedTimestamp(new Timestamp(ceaPolicy.getLastUpdated().getTime()));
ceaPolicyDTO.setTenantId(ceaPolicy.getTenantId());
if (ceaPolicy.getLastSynced() != null) {
ceaPolicyDTO.setLastSyncedTimestamp(new Timestamp(ceaPolicy.getLastSynced().getTime()));
}
return ceaPolicyDTO;
}
private CEAPolicy toCEAPolicy(CEAPolicyDTO ceaPolicyDTO) throws CEAPolicyManagementDAOException{
if (ceaPolicyDTO == null) {
throw new CEAPolicyManagementDAOException("CEAPolicyDTO can't be null");
}
CEAPolicy ceaPolicy = new CEAPolicy();
CEAPolicyContent ceaPolicyContent = gson.fromJson(ceaPolicyDTO.getPolicyContent(), CEAPolicyContent.class);
ActiveSyncServer activeSyncServer = ceaPolicyContent.getActiveSyncServer();
activeSyncServer.setSecret(new String(Base64.getDecoder().decode(activeSyncServer.getSecret())));
ceaPolicy.setActiveSyncServer(activeSyncServer);
ceaPolicy.setAccessPolicy(ceaPolicyContent.getAccessPolicy());
ceaPolicy.setGracePeriod(ceaPolicyContent.getGracePeriod());
ceaPolicy.setLastUpdated(new Date(ceaPolicyDTO.getUpdatedTimestamp().getTime()));
ceaPolicy.setSynced(ceaPolicyDTO.isSynced());
ceaPolicy.setTenantId(ceaPolicyDTO.getTenantId());
if (ceaPolicyDTO.getLastSyncedTimestamp() != null) {
ceaPolicy.setLastSynced(new Date(ceaPolicyDTO.getLastSyncedTimestamp().getTime()));
}
ceaPolicy.setCreated(new Date(ceaPolicyDTO.getCreatedTimestamp().getTime()));
return ceaPolicy;
}
}

@ -0,0 +1,26 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.dao.impl;
public class GenericCEAPolicyDAO extends AbstractCEAPolicyDAO {
public GenericCEAPolicyDAO() {
super();
}
}

@ -0,0 +1,54 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.dto;
import io.entgra.device.mgt.core.cea.mgt.common.bean.AccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServer;
import io.entgra.device.mgt.core.cea.mgt.common.bean.GracePeriod;
public class CEAPolicyContent {
private ActiveSyncServer activeSyncServer;
private GracePeriod gracePeriod;
private AccessPolicy accessPolicy;
public ActiveSyncServer getActiveSyncServer() {
return activeSyncServer;
}
public void setActiveSyncServer(ActiveSyncServer activeSyncServer) {
this.activeSyncServer = activeSyncServer;
}
public GracePeriod getGracePeriod() {
return gracePeriod;
}
public void setGracePeriod(GracePeriod gracePeriod) {
this.gracePeriod = gracePeriod;
}
public AccessPolicy getAccessPolicy() {
return accessPolicy;
}
public void setAccessPolicy(AccessPolicy accessPolicy) {
this.accessPolicy = accessPolicy;
}
}

@ -0,0 +1,79 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.dto;
import java.sql.Timestamp;
public class CEAPolicyDTO {
private String policyContent;
private Timestamp createdTimestamp;
private Timestamp updatedTimestamp;
private Timestamp lastSyncedTimestamp;
private boolean isSynced;
private int tenantId;
public String getPolicyContent() {
return policyContent;
}
public void setPolicyContent(String policyContent) {
this.policyContent = policyContent;
}
public Timestamp getCreatedTimestamp() {
return createdTimestamp;
}
public void setCreatedTimestamp(Timestamp createdTimestamp) {
this.createdTimestamp = createdTimestamp;
}
public Timestamp getUpdatedTimestamp() {
return updatedTimestamp;
}
public void setUpdatedTimestamp(Timestamp updatedTimestamp) {
this.updatedTimestamp = updatedTimestamp;
}
public Timestamp getLastSyncedTimestamp() {
return lastSyncedTimestamp;
}
public void setLastSyncedTimestamp(Timestamp lastSyncedTimestamp) {
this.lastSyncedTimestamp = lastSyncedTimestamp;
}
public boolean isSynced() {
return isSynced;
}
public void setSynced(boolean synced) {
isSynced = synced;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.exception;
public class CEAPolicyManagementDAOException extends Exception {
public CEAPolicyManagementDAOException(String msg) {
super(msg);
}
public CEAPolicyManagementDAOException(String msg, Throwable t) {
super(msg, t);
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.exception;
public class CEAPolicyMonitoringTaskManagerException extends Exception {
public CEAPolicyMonitoringTaskManagerException(String msg) {
super(msg);
}
public CEAPolicyMonitoringTaskManagerException(String msg, Throwable t) {
super(msg, t);
}
}

@ -0,0 +1,72 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.impl;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ui.CEAPolicyUIConfiguration;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAManagementException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyAlreadyExistsException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyNotFoundException;
import io.entgra.device.mgt.core.cea.mgt.common.service.CEAManagementService;
import io.entgra.device.mgt.core.cea.mgt.core.mgt.CEAManager;
import io.entgra.device.mgt.core.cea.mgt.core.mgt.impl.CEAManagerImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CEAManagementServiceImpl implements CEAManagementService {
private static final Log log = LogFactory.getLog(CEAManagementServiceImpl.class);
private final CEAManager ceaManager;
public CEAManagementServiceImpl() {
ceaManager = CEAManagerImpl.getInstance();
}
@Override
public CEAPolicyUIConfiguration getCEAPolicyUIConfiguration() throws CEAManagementException {
return ceaManager.getCEAPolicyUIConfiguration();
}
@Override
public CEAPolicy createCEAPolicy(CEAPolicy ceaPolicy) throws CEAManagementException,
CEAPolicyAlreadyExistsException {
return ceaManager.createCEAPolicy(ceaPolicy);
}
@Override
public CEAPolicy retrieveCEAPolicy() throws CEAManagementException {
return ceaManager.retrieveCEAPolicy();
}
@Override
public CEAPolicy updateCEAPolicy(CEAPolicy ceaPolicy) throws CEAManagementException, CEAPolicyNotFoundException {
return ceaManager.updateCEAPolicy(ceaPolicy);
}
@Override
public void deleteCEAPolicy() throws CEAManagementException, CEAPolicyNotFoundException {
ceaManager.deleteCEAPolicy();
}
@Override
public void syncNow() throws CEAManagementException {
ceaManager.syncNow();
}
}

@ -0,0 +1,64 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.internal;
import io.entgra.device.mgt.core.cea.mgt.common.service.EnforcementServiceManager;
import io.entgra.device.mgt.core.cea.mgt.core.task.CEAPolicyMonitoringTaskManager;
import org.wso2.carbon.ntask.core.service.TaskService;
public class CEAManagementDataHolder {
private EnforcementServiceManager enforcementServiceManager;
private TaskService taskService;
private CEAPolicyMonitoringTaskManager ceaPolicyMonitoringTaskManager;
private CEAManagementDataHolder() {}
public static CEAManagementDataHolder getInstance() {
return CEAManagementDataHolderRegistry.INSTANCE;
}
public EnforcementServiceManager getEnforcementServiceManager() {
return enforcementServiceManager;
}
public void setEnforcementServiceManager(EnforcementServiceManager enforcementServiceManager) {
this.enforcementServiceManager = enforcementServiceManager;
}
public TaskService getTaskService() {
return taskService;
}
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
public CEAPolicyMonitoringTaskManager getCeaPolicyMonitoringTaskManager() {
return ceaPolicyMonitoringTaskManager;
}
public void setCeaPolicyMonitoringTaskManager(CEAPolicyMonitoringTaskManager ceaPolicyMonitoringTaskManager) {
this.ceaPolicyMonitoringTaskManager = ceaPolicyMonitoringTaskManager;
}
private static class CEAManagementDataHolderRegistry {
public static final CEAManagementDataHolder INSTANCE = new CEAManagementDataHolder();
}
}

@ -0,0 +1,110 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.internal;
import io.entgra.device.mgt.core.cea.mgt.common.service.CEAManagementService;
import io.entgra.device.mgt.core.cea.mgt.common.service.EnforcementServiceManager;
import io.entgra.device.mgt.core.cea.mgt.core.config.CEAConfigManager;
import io.entgra.device.mgt.core.cea.mgt.core.dao.factory.CEAPolicyManagementDAOFactory;
import io.entgra.device.mgt.core.cea.mgt.core.impl.CEAManagementServiceImpl;
import io.entgra.device.mgt.core.cea.mgt.core.task.CEAPolicyMonitoringTaskManager;
import io.entgra.device.mgt.core.cea.mgt.core.task.CEAPolicyMonitoringTaskManagerImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.ntask.core.service.TaskService;
/**
* @scr.component name="io.entgra.device.mgt.core.cea.mgt.core.CEAManagementServiceComponent" immediate="true"
* @scr.reference name="org.wso2.carbon.ndatasource"
* interface="org.wso2.carbon.ndatasource.core.DataSourceService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDataSourceService"
* unbind="unsetDataSourceService"
* @scr.reference name="io.entgra.device.mgt.core.cea.mgt.enforcementServiceManager"
* interface="io.entgra.device.mgt.core.cea.mgt.common.service.EnforcementServiceManager"
* cardinality="1..1"
* policy="dynamic"
* bind="setEnforcementServiceManager"
* unbind="unsetEnforcementServiceManager"
* @scr.reference name="ntask.component"
* interface="org.wso2.carbon.ntask.core.service.TaskService"
* cardinality="1..1"
* policy="dynamic"
* bind="setTaskService"
* unbind="unsetTaskService"
*/
public class CEAManagementServiceComponent {
private static final Log log = LogFactory.getLog(CEAManagementServiceComponent.class);
protected void activate(ComponentContext componentContext) {
try {
CEAConfigManager ceaConfigManager = CEAConfigManager.getInstance();
CEAPolicyManagementDAOFactory.init(ceaConfigManager.getCeaPolicyManagementRepository().getDataSourceConfig());
CEAManagementService ceaManagementService = new CEAManagementServiceImpl();
componentContext.getBundleContext().registerService(CEAManagementService.class.getName(),
ceaManagementService, null);
CEAPolicyMonitoringTaskManager ceaPolicyMonitoringTaskManager = new CEAPolicyMonitoringTaskManagerImpl();
CEAManagementDataHolder.getInstance().setCeaPolicyMonitoringTaskManager(ceaPolicyMonitoringTaskManager);
} catch (Throwable t) {
String msg = "Error occurred while activating " + CEAManagementServiceComponent.class.getName();
log.error(msg, t);
}
}
protected void setDataSourceService(DataSourceService dataSourceService) {
// This is to avoid cea management component getting initialized before the underlying datasource registered
}
protected void unsetDataSourceService(DataSourceService dataSourceService) {
// Do nothing
}
protected void setEnforcementServiceManager(EnforcementServiceManager enforcementServiceManager) {
CEAManagementDataHolder.getInstance().setEnforcementServiceManager(enforcementServiceManager);
if (log.isDebugEnabled()) {
log.debug("Enforcement service manager is set successfully");
}
}
protected void unsetEnforcementServiceManager(EnforcementServiceManager enforcementServiceManager) {
CEAManagementDataHolder.getInstance().setEnforcementServiceManager(null);
if (log.isDebugEnabled()) {
log.debug("Enforcement service manager is unset successfully");
}
}
protected void setTaskService(TaskService taskService) {
CEAManagementDataHolder.getInstance().setTaskService(taskService);
if (log.isDebugEnabled()) {
log.debug("Task service is set successfully");
}
}
protected void unsetTaskService(TaskService taskService) {
CEAManagementDataHolder.getInstance().setTaskService(null);
if (log.isDebugEnabled()) {
log.debug("Task service is unset successfully");
}
}
}

@ -0,0 +1,99 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.mgt;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ui.CEAPolicyUIConfiguration;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAManagementException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyAlreadyExistsException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyNotFoundException;
import java.util.Date;
import java.util.List;
public interface CEAManager {
/**
* Retrieve conditional access policy UI configuration
*
* @return {@link CEAPolicyUIConfiguration}
* @throws CEAManagementException Throws when retrieving UI configurations
*/
CEAPolicyUIConfiguration getCEAPolicyUIConfiguration() throws CEAManagementException;
/**
* Trigger sync task with active sync server
*
* @throws CEAManagementException Throws when error occurred while triggering the sync operation
*/
void syncNow() throws CEAManagementException;
/**
* Create conditional access policy
*
* @param ceaPolicy {@link CEAPolicy}
* @return {@link CEAPolicy} Created conditional access policy
* @throws CEAManagementException Throws when error occurred while creating the policy
* @throws CEAPolicyAlreadyExistsException Throws when conflict occurs
*/
CEAPolicy createCEAPolicy(CEAPolicy ceaPolicy) throws CEAManagementException, CEAPolicyAlreadyExistsException;
/**
* Retrieve conditional access policy for the tenant
*
* @return {@link CEAPolicy}
* @throws CEAManagementException Throws when error occurred while retrieving the policy
*/
CEAPolicy retrieveCEAPolicy() throws CEAManagementException;
/**
* Retrieve all conditional access policies
*
* @return List of conditional access policies
* @throws CEAManagementException Throws when error occurred while retrieving policies
*/
List<CEAPolicy> retrieveAllCEAPolicies() throws CEAManagementException;
/**
* Update conditional access policy
*
* @param ceaPolicy {@link CEAPolicy}
* @return {@link CEAPolicy} Returns update conditional access policy
* @throws CEAManagementException Throws when error occurred while updating the policy
* @throws CEAPolicyNotFoundException Throws when policy doesn't exist
*/
CEAPolicy updateCEAPolicy(CEAPolicy ceaPolicy) throws CEAManagementException, CEAPolicyNotFoundException;
/**
* Delete the conditional access policy
*
* @throws CEAManagementException Throws when error occurred while deleting the policy
* @throws CEAPolicyNotFoundException Throws when a conditional access policy doesn't exist
*/
void deleteCEAPolicy() throws CEAManagementException, CEAPolicyNotFoundException;
/**
* Update sync status of the conditional access policy
*
* @param status Whether the sync success or not
* @param syncedTime Synced timestamp
* @throws CEAManagementException Throws when error occurred while updating the status
*/
void updateSyncStatus(boolean status, Date syncedTime) throws CEAManagementException;
}

@ -0,0 +1,199 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.mgt.impl;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ui.CEAPolicyUIConfiguration;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAConfigManagerException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAManagementException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyAlreadyExistsException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyNotFoundException;
import io.entgra.device.mgt.core.cea.mgt.core.bean.CEAConfiguration;
import io.entgra.device.mgt.core.cea.mgt.core.config.CEAConfigManager;
import io.entgra.device.mgt.core.cea.mgt.core.dao.CEAPolicyDAO;
import io.entgra.device.mgt.core.cea.mgt.core.dao.factory.CEAPolicyManagementDAOFactory;
import io.entgra.device.mgt.core.cea.mgt.core.exception.CEAPolicyManagementDAOException;
import io.entgra.device.mgt.core.cea.mgt.core.exception.CEAPolicyMonitoringTaskManagerException;
import io.entgra.device.mgt.core.cea.mgt.core.internal.CEAManagementDataHolder;
import io.entgra.device.mgt.core.cea.mgt.core.mgt.CEAManager;
import io.entgra.device.mgt.core.cea.mgt.core.task.CEAPolicyMonitoringTaskManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Date;
import java.util.List;
public class CEAManagerImpl implements CEAManager {
private static final Log log = LogFactory.getLog(CEAManagerImpl.class);
private final CEAPolicyDAO ceaPolicyDAO;
private CEAManagerImpl() {
ceaPolicyDAO = CEAPolicyManagementDAOFactory.getCEAPolicyDAO();
}
public static CEAManagerImpl getInstance() {
return CEAManagerHolder.INSTANCE;
}
@Override
public CEAPolicyUIConfiguration getCEAPolicyUIConfiguration() throws CEAManagementException {
CEAPolicyUIConfiguration ceaPolicyUIConfiguration;
try {
ceaPolicyUIConfiguration = CEAConfigManager.getInstance().getCeaPolicyUIConfiguration();
} catch (CEAConfigManagerException e) {
String msg = "Error occurred while retrieving CEA ui configs";
throw new CEAManagementException(msg, e);
}
return ceaPolicyUIConfiguration;
}
@Override
public void syncNow() throws CEAManagementException {
try {
CEAPolicyMonitoringTaskManager ceaPolicyMonitoringTaskManager = CEAManagementDataHolder.
getInstance().getCeaPolicyMonitoringTaskManager();
if (ceaPolicyMonitoringTaskManager == null) {
throw new IllegalStateException("CEA policy monitoring task manager not initialized properly");
}
CEAConfigManager ceaConfigManager = CEAConfigManager.getInstance();
CEAConfiguration ceaConfiguration = ceaConfigManager.getCeaConfiguration();
ceaPolicyMonitoringTaskManager.stopTask();
ceaPolicyMonitoringTaskManager.startTask(ceaConfiguration.getMonitoringConfiguration().getMonitoringFrequency());
} catch (CEAConfigManagerException e) {
String msg = "Error occurred while retrieving CEA configurations";
log.error(msg, e);
throw new CEAManagementException(msg, e);
} catch (CEAPolicyMonitoringTaskManagerException e) {
String msg = "Error occurred while triggering CEA policy monitoring task";
log.error(msg, e);
throw new CEAManagementException(msg, e);
}
}
@Override
public CEAPolicy createCEAPolicy(CEAPolicy ceaPolicy) throws CEAManagementException,
CEAPolicyAlreadyExistsException {
try {
CEAPolicyManagementDAOFactory.openConnection();
if (ceaPolicyDAO.retrieveCEAPolicy() != null) {
throw new CEAPolicyAlreadyExistsException("CEA policy already exists");
}
return ceaPolicyDAO.createCEAPolicy(ceaPolicy);
} catch (CEAPolicyManagementDAOException e) {
String msg = "Error occurred while creating CEA policy";
log.error(msg, e);
throw new CEAManagementException(msg, e);
} finally {
CEAPolicyManagementDAOFactory.closeConnection();
}
}
@Override
public CEAPolicy retrieveCEAPolicy() throws CEAManagementException {
try {
CEAPolicyManagementDAOFactory.openConnection();
return ceaPolicyDAO.retrieveCEAPolicy();
} catch (CEAPolicyManagementDAOException e) {
String msg = "Error occurred while retrieving CEA policy";
log.error(msg, e);
throw new CEAManagementException(msg, e);
} finally {
CEAPolicyManagementDAOFactory.closeConnection();
}
}
@Override
public List<CEAPolicy> retrieveAllCEAPolicies() throws CEAManagementException {
try {
CEAPolicyManagementDAOFactory.openConnection();
return ceaPolicyDAO.retrieveAllCEAPolicies();
} catch (CEAPolicyManagementDAOException e) {
String msg = "Error occurred while retrieving CEA policies";
log.error(msg, e);
throw new CEAManagementException(msg, e);
} finally {
CEAPolicyManagementDAOFactory.closeConnection();
}
}
@Override
public CEAPolicy updateCEAPolicy(CEAPolicy ceaPolicy) throws CEAManagementException, CEAPolicyNotFoundException {
try {
CEAPolicyManagementDAOFactory.openConnection();
CEAPolicy existingCeaPolicy = ceaPolicyDAO.retrieveCEAPolicy();
if (existingCeaPolicy == null) {
throw new CEAPolicyNotFoundException("CEA policy not found");
}
return ceaPolicyDAO.updateCEAPolicy(existingCeaPolicy, ceaPolicy);
} catch (CEAPolicyManagementDAOException e) {
String msg = "Error occurred while updating CEA policy";
log.error(msg, e);
throw new CEAManagementException(msg, e);
} finally {
CEAPolicyManagementDAOFactory.closeConnection();
}
}
@Override
public void deleteCEAPolicy() throws CEAManagementException, CEAPolicyNotFoundException {
try {
CEAPolicyManagementDAOFactory.openConnection();
CEAPolicyMonitoringTaskManager ceaPolicyMonitoringTaskManager = CEAManagementDataHolder.
getInstance().getCeaPolicyMonitoringTaskManager();
if (ceaPolicyMonitoringTaskManager == null) {
String msg = "CEA policy monitoring task manager not initialized properly, " +
"hence aborting CEA policy deleting procedure";
throw new IllegalStateException(msg);
}
CEAPolicy existingCeaPolicy = ceaPolicyDAO.retrieveCEAPolicy();
if (existingCeaPolicy == null) throw new CEAPolicyNotFoundException("CEA policy not found");
ceaPolicyDAO.deleteCEAPolicy();
ceaPolicyMonitoringTaskManager.stopTask();
} catch (CEAPolicyManagementDAOException e) {
String msg = "Error occurred while deleting CEA policy";
log.error(msg, e);
throw new CEAManagementException(msg, e);
} catch (CEAPolicyMonitoringTaskManagerException e) {
String msg = "Error occurred while stopping CEA policy monitoring task";
log.error(msg, e);
throw new CEAManagementException(msg, e);
} finally {
CEAPolicyManagementDAOFactory.closeConnection();
}
}
@Override
public void updateSyncStatus(boolean status, Date syncedTime) throws CEAManagementException {
try {
CEAPolicyManagementDAOFactory.openConnection();
ceaPolicyDAO.updateLastSyncedTime(status, syncedTime);
} catch (CEAPolicyManagementDAOException e) {
String msg = "Error occurred while updating sync status";
log.error(msg, e);
throw new CEAManagementException(msg, e);
} finally {
CEAPolicyManagementDAOFactory.closeConnection();
}
}
private static class CEAManagerHolder {
public static final CEAManagerImpl INSTANCE = new CEAManagerImpl();
}
}

@ -0,0 +1,112 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.task;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAConfigManagerException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAManagementException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.EnforcementServiceManagerException;
import io.entgra.device.mgt.core.cea.mgt.common.service.EnforcementServiceManager;
import io.entgra.device.mgt.core.cea.mgt.core.bean.ActiveSyncServerConfiguration;
import io.entgra.device.mgt.core.cea.mgt.core.bean.CEAConfiguration;
import io.entgra.device.mgt.core.cea.mgt.core.config.CEAConfigManager;
import io.entgra.device.mgt.core.cea.mgt.core.internal.CEAManagementDataHolder;
import io.entgra.device.mgt.core.cea.mgt.core.mgt.CEAManager;
import io.entgra.device.mgt.core.cea.mgt.core.mgt.impl.CEAManagerImpl;
import io.entgra.device.mgt.core.cea.mgt.core.util.Constants;
import io.entgra.device.mgt.core.cea.mgt.enforce.Impl.CEAPolicyOperationImpl;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.CEAPolicyOperationException;
import io.entgra.device.mgt.core.cea.mgt.enforce.service.CEAPolicyOperation;
import io.entgra.device.mgt.core.device.mgt.core.task.impl.DynamicPartitionedScheduleTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.util.Date;
import java.util.Objects;
public class CEAPolicyMonitoringTask extends DynamicPartitionedScheduleTask {
private static final Log log = LogFactory.getLog(CEAPolicyMonitoringTask.class);
private CEAManager ceaManager;
private CEAConfigManager ceaConfigManager;
private EnforcementServiceManager enforcementServiceManager;
@Override
protected void executeDynamicTask() {
int tenantId = Integer.parseInt(Objects.requireNonNull(getProperty(Constants.TENANT_ID_KEY)));
try {
CEAConfiguration ceaConfiguration = ceaConfigManager.getCeaConfiguration();
CEAPolicy ceaPolicy = ceaManager.retrieveCEAPolicy();
ActiveSyncServerConfiguration activeSyncServerConfiguration = ceaConfiguration.
getActiveSyncServerConfiguration(ceaPolicy.getActiveSyncServer());
if (MultitenantConstants.SUPER_TENANT_ID == tenantId) {
enforce(ceaPolicy, activeSyncServerConfiguration);
return;
}
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
enforce(ceaPolicy, activeSyncServerConfiguration);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
} catch (CEAManagementException e) {
log.error("Error occurred while executing dynamic partitioned task for the CEA policy monitoring", e);
} catch (CEAConfigManagerException e) {
log.error("Error occurred while retrieving CEA configuration", e);
}
}
private void enforce(CEAPolicy ceaPolicy, ActiveSyncServerConfiguration activeSyncServerConfiguration) {
boolean status = false;
Date syncedStartTime = new Date();
CEAPolicyOperation ceaPolicyOperation;
try {
ceaPolicyOperation = new CEAPolicyOperationImpl(enforcementServiceManager.
getEnforcementService(activeSyncServerConfiguration.getEnforcementService()), ceaPolicy);
ceaPolicyOperation.enforce();
status = true;
} catch (EnforcementServiceManagerException | CEAPolicyOperationException e) {
log.error("Error occurred while enforcing the CEA access policy for the tenant id" + ceaPolicy.getTenantId(), e);
} finally {
logbackEnforcementStatus(status, syncedStartTime);
}
}
private void logbackEnforcementStatus(boolean status, Date syncedStartTime) {
try {
ceaManager.updateSyncStatus(status, syncedStartTime);
} catch (CEAManagementException e) {
log.error("Error occurred while recording sync status", e);
}
}
@Override
protected void setup() {
ceaManager = CEAManagerImpl.getInstance();
ceaConfigManager = CEAConfigManager.getInstance();
enforcementServiceManager = CEAManagementDataHolder.getInstance().getEnforcementServiceManager();
}
}

@ -0,0 +1,28 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.task;
import io.entgra.device.mgt.core.cea.mgt.core.exception.CEAPolicyMonitoringTaskManagerException;
public interface CEAPolicyMonitoringTaskManager {
void startTask(long monitoringFrequency) throws CEAPolicyMonitoringTaskManagerException;
void stopTask() throws CEAPolicyMonitoringTaskManagerException;
}

@ -0,0 +1,105 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.task;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAConfigManagerException;
import io.entgra.device.mgt.core.cea.mgt.core.bean.CEAConfiguration;
import io.entgra.device.mgt.core.cea.mgt.core.config.CEAConfigManager;
import io.entgra.device.mgt.core.cea.mgt.core.exception.CEAPolicyMonitoringTaskManagerException;
import io.entgra.device.mgt.core.cea.mgt.core.internal.CEAManagementDataHolder;
import io.entgra.device.mgt.core.cea.mgt.core.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.ntask.common.TaskException;
import org.wso2.carbon.ntask.core.TaskInfo;
import org.wso2.carbon.ntask.core.TaskManager;
import org.wso2.carbon.ntask.core.service.TaskService;
import java.util.HashMap;
import java.util.Map;
public class CEAPolicyMonitoringTaskManagerImpl implements CEAPolicyMonitoringTaskManager {
private static final Log log = LogFactory.getLog(CEAPolicyMonitoringTaskManagerImpl.class);
@Override
public void startTask(long monitoringFrequency) throws CEAPolicyMonitoringTaskManagerException {
if (monitoringFrequency <= 0) {
throw new CEAPolicyMonitoringTaskManagerException("Invalid monitoring frequency");
}
TaskService taskService = CEAManagementDataHolder.getInstance().getTaskService();
if (taskService == null) {
throw new IllegalStateException("Task service is not initialized");
}
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
CEAConfiguration ceaConfiguration = CEAConfigManager.getInstance().getCeaConfiguration();
boolean isMonitoringEnable = ceaConfiguration.getMonitoringConfiguration().isMonitoringEnable();
if (!isMonitoringEnable) {
log.warn("CEA policy monitoring is disabled");
return;
}
taskService.registerTaskType(Constants.CEA_MONITORING_TASK_TYPE);
TaskManager taskManager = taskService.getTaskManager(Constants.CEA_MONITORING_TASK_TYPE);
TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo();
triggerInfo.setIntervalMillis(monitoringFrequency);
triggerInfo.setRepeatCount(-1);
Map<String, String> properties = new HashMap<>();
properties.put(Constants.TENANT_ID_KEY, String.valueOf(tenantId));
if (!taskManager.isTaskScheduled(Constants.CEA_MONITORING_TASK_NAME + tenantId)) {
TaskInfo taskInfo = new TaskInfo(Constants.CEA_MONITORING_TASK_NAME + tenantId,
ceaConfiguration.getMonitoringConfiguration().getMonitoringClazz(), properties, triggerInfo);
taskManager.registerTask(taskInfo);
taskManager.rescheduleTask(taskInfo.getName());
} else {
throw new CEAPolicyMonitoringTaskManagerException("CEA policy monitoring task is already active");
}
} catch (CEAConfigManagerException e) {
String msg = "Error occurred while retrieving CEA config";
log.error(msg, e);
throw new CEAPolicyMonitoringTaskManagerException(msg, e);
} catch (TaskException e) {
String msg = "Error occurred while scheduling task for CEA policy monitoring";
log.error(msg, e);
throw new CEAPolicyMonitoringTaskManagerException(msg, e);
}
}
@Override
public void stopTask() throws CEAPolicyMonitoringTaskManagerException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
TaskService taskService = CEAManagementDataHolder.getInstance().getTaskService();
if (taskService != null && taskService.isServerInit()) {
TaskManager taskManager = taskService.getTaskManager(Constants.CEA_MONITORING_TASK_TYPE);
taskManager.deleteTask(Constants.CEA_MONITORING_TASK_NAME + tenantId);
}
} catch (TaskException e) {
String msg = "Error occurred while stopping the " + Constants.CEA_MONITORING_TASK_NAME + tenantId;
log.error(msg, e);
throw new CEAPolicyMonitoringTaskManagerException(msg, e);
}
}
}

@ -0,0 +1,29 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.core.util;
public class Constants {
public static final String CDM_CONFIG_FILE_NAME = "cdm-config.xml";
public static final String CEA_POLICY_UI_FILE_NAME = "cea-ui-config.xml";
public static final String CEA_CONFIG_FILE_NAME = "cea-config.xml";
public static final String CEA_MONITORING_TASK_TYPE = "CEA_MONITORING_TASK";
public static final String CEA_MONITORING_TASK_NAME = "CEA_MONITORING_TASK";
public static final String TENANT_ID_KEY = "TENANT_ID";
}

@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>cea-mgt</artifactId>
<version>5.0.38-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>io.entgra.device.mgt.core.cea.mgt.enforce</artifactId>
<modelVersion>4.0.0</modelVersion>
<packaging>bundle</packaging>
<name>Entgra IoT - CEA Management Enforcement Service</name>
<description>Entgra IoT - Conditional Email Access Management Enforcement Service</description>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>CEA Management Enforcement Service Bundle</Bundle-Description>
<Import-Package>
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.wso2.carbon.utils,
org.wso2.carbon.context.*,
org.apache.commons.logging,
com.google.gson.*,
io.entgra.device.mgt.core.device.mgt.common.*,
io.entgra.device.mgt.core.cea.mgt.common.*,
io.entgra.device.mgt.core.device.mgt.core.service,
org.wso2.carbon.user.api,
org.wso2.carbon.user.core.service
</Import-Package>
<Export-Package>
io.entgra.device.mgt.core.cea.mgt.enforce.*
</Export-Package>
<DynamicImport-Package>*</DynamicImport-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.cea.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>msal4j</artifactId>
<version>1.14.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,58 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.Impl;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.service.CEAEnforcementService;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.CEAPolicyOperationException;
import io.entgra.device.mgt.core.cea.mgt.enforce.service.CEAPolicyOperation;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.annotation.Enforce;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Method;
public class CEAPolicyOperationImpl implements CEAPolicyOperation {
private static final Log log = LogFactory.getLog(CEAPolicyOperationImpl.class);
private final CEAEnforcementService ceaEnforcementService;
private final CEAPolicy ceaPolicy;
public CEAPolicyOperationImpl(CEAEnforcementService ceaEnforcementService, CEAPolicy ceaPolicy) {
this.ceaEnforcementService = ceaEnforcementService;
this.ceaPolicy = ceaPolicy;
}
@Override
public void enforce() throws CEAPolicyOperationException {
try {
Method[] methods = ceaEnforcementService.getClass().getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(Enforce.class)) {
method.setAccessible(true);
method.invoke(ceaEnforcementService, ceaPolicy);
}
}
} catch (Exception e) {
String msg = "Error occurred while invoking CEA enforcement service";
log.error(msg, e);
throw new CEAPolicyOperationException(msg, e);
}
}
}

@ -0,0 +1,61 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.Impl;
import io.entgra.device.mgt.core.cea.mgt.common.exception.EnforcementServiceManagerException;
import io.entgra.device.mgt.core.cea.mgt.common.service.CEAEnforcementService;
import io.entgra.device.mgt.core.cea.mgt.common.service.EnforcementServiceManager;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class EnforcementServiceManagerImpl implements EnforcementServiceManager {
private static final Log log = LogFactory.getLog(EnforcementServiceManagerImpl.class);
@Override
public CEAEnforcementService getEnforcementService(String enforcementServiceClassName) throws EnforcementServiceManagerException {
try {
Class<?> enforcementServiceClass = Class.forName(enforcementServiceClassName);
Method method = enforcementServiceClass.getMethod(Constants.METHOD_NAME_GET_INSTANCE);
return (CEAEnforcementService) method.invoke(null);
} catch (ClassNotFoundException e) {
String msg = enforcementServiceClassName + " not found";
log.error(msg, e);
throw new EnforcementServiceManagerException(msg, e);
} catch (NoSuchMethodException e) {
String msg = Constants.METHOD_NAME_GET_INSTANCE + " not found in " + enforcementServiceClassName;
log.error(msg, e);
throw new EnforcementServiceManagerException(msg, e);
} catch (InvocationTargetException e) {
String msg = "Error occurred while invoking " + Constants.METHOD_NAME_GET_INSTANCE + " in "
+ enforcementServiceClassName;
log.error(msg, e);
throw new EnforcementServiceManagerException(msg, e);
} catch (IllegalAccessException e) {
String msg = "Can't access the method " + Constants.METHOD_NAME_GET_INSTANCE + " in "
+ enforcementServiceClassName;
log.error(msg, e);
throw new EnforcementServiceManagerException(msg, e);
}
}
}

@ -0,0 +1,592 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.Impl;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncDevice;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServer;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.GracePeriod;
import io.entgra.device.mgt.core.cea.mgt.common.bean.MailboxProfile;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.EmailOutlookAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.GraceAllowedPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.WebOutlookAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAEnforcementException;
import io.entgra.device.mgt.core.cea.mgt.common.service.CEAEnforcementService;
import io.entgra.device.mgt.core.cea.mgt.common.util.Constants;
import io.entgra.device.mgt.core.cea.mgt.common.util.EASMgtUtil;
import io.entgra.device.mgt.core.cea.mgt.enforce.Impl.gateway.ExchangeOnlineGatewayServiceImpl;
import io.entgra.device.mgt.core.cea.mgt.enforce.bean.ExoPowershellCommand;
import io.entgra.device.mgt.core.cea.mgt.enforce.bean.PowershellCommand;
import io.entgra.device.mgt.core.cea.mgt.enforce.bean.PowershellRequest;
import io.entgra.device.mgt.core.cea.mgt.enforce.bean.PowershellResponse;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.GatewayServiceException;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.PowershellExecutionException;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.UnsupportedOsException;
import io.entgra.device.mgt.core.cea.mgt.enforce.service.gateway.GatewayService;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.DeviceMgtUtil;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.annotation.Enforce;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.Powershell;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.parser.Parser;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.user.api.UserStoreException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class ExchangeOnlineCEAEnforcementServiceImpl implements CEAEnforcementService {
private static final Log log = LogFactory.getLog(ExchangeOnlineCEAEnforcementServiceImpl.class);
private static volatile ExchangeOnlineCEAEnforcementServiceImpl INSTANCE;
private final GatewayService gatewayService;
private final Powershell powershell;
ExchangeOnlineCEAEnforcementServiceImpl() throws UnsupportedOsException {
gatewayService = new ExchangeOnlineGatewayServiceImpl();
powershell = Powershell.getPowershell();
}
public static ExchangeOnlineCEAEnforcementServiceImpl getInstance() throws UnsupportedOsException {
if (INSTANCE == null) {
synchronized (ExchangeOnlineCEAEnforcementServiceImpl.class) {
if (INSTANCE == null) {
INSTANCE = new ExchangeOnlineCEAEnforcementServiceImpl();
}
}
}
return INSTANCE;
}
@Enforce
public void enforceDefaultAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException {
try {
PowershellCommand setActiveSyncOrganizationSettings = getCommand(Parser.
COMMAND_SetActiveSyncOrganizationSettings.COMMAND, ceaPolicy.getActiveSyncServer());
setActiveSyncOrganizationSettings.addOption(Parser.COMMAND_SetActiveSyncOrganizationSettings.
PARAMETER_DefaultAccessLevel,
Parser.COMMAND_SetActiveSyncOrganizationSettings.POLICY_TO_VALUE.
get(ceaPolicy.getAccessPolicy().getDefaultAccessPolicy().toString()));
PowershellResponse powershellResponse = powershell.execute(getPowershellRequest(setActiveSyncOrganizationSettings));
if (powershellResponse.isSuccess()) {
log.info("Default access policy successfully enforced for " + ceaPolicy.getTenantId());
} else {
log.error("Default access policy enforcement procedure failed for " + ceaPolicy.getTenantId());
}
} catch (GatewayServiceException e) {
String msg = "Active sync gateway service failed while enforcing default CEA access policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
} catch (PowershellExecutionException e) {
String msg = "Error occurred while executing powershell command for enforcing " +
"CEA access policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
}
}
@Enforce
public void enforceEmailOutlookAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException {
Set<EmailOutlookAccessPolicy> emailOutlookAccessPolicies = ceaPolicy.getAccessPolicy().getEmailOutlookAccessPolicy();
if (emailOutlookAccessPolicies.contains(EmailOutlookAccessPolicy.NOT_CONFIGURED)) {
if (log.isDebugEnabled()) {
log.debug("CEA email outlook policy not configured, but the support is available in " +
ExchangeOnlineCEAEnforcementServiceImpl.class);
}
return;
}
ActiveSyncServer activeSyncServer = ceaPolicy.getActiveSyncServer();
try {
PowershellCommand setCASMailbox = getCommand(Parser.COMMAND_SetCASMailbox.COMMAND,
activeSyncServer);
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_Identity, "$_.Identity");
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_OutlookMobileEnabled, Parser.TRUE);
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_MacOutlookEnabled, Parser.TRUE);
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_OneWinNativeOutlookEnabled, Parser.TRUE);
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_EwsAllowMacOutlook, Parser.TRUE);
if (emailOutlookAccessPolicies.contains(EmailOutlookAccessPolicy.MOBILE_OUTLOOK_BLOCK)) {
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_OutlookMobileEnabled,
Parser.COMMAND_SetCASMailbox.POLICY_TO_VALUE.get(EmailOutlookAccessPolicy.MOBILE_OUTLOOK_BLOCK.toString()));
}
if (emailOutlookAccessPolicies.contains(EmailOutlookAccessPolicy.MAC_OUTLOOK_BLOCK)) {
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_MacOutlookEnabled,
Parser.COMMAND_SetCASMailbox.POLICY_TO_VALUE.get(EmailOutlookAccessPolicy.MAC_OUTLOOK_BLOCK.toString()));
}
if (emailOutlookAccessPolicies.contains(EmailOutlookAccessPolicy.WINDOWS_OUTLOOK_BLOCK)) {
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_OneWinNativeOutlookEnabled,
Parser.COMMAND_SetCASMailbox.POLICY_TO_VALUE.get(EmailOutlookAccessPolicy.WINDOWS_OUTLOOK_BLOCK.toString()));
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_EwsAllowMacOutlook,
Parser.COMMAND_SetCASMailbox.POLICY_TO_VALUE.get(EmailOutlookAccessPolicy.MAC_OLD_OUTLOOK_BLOCK.toString()));
}
PowershellResponse powershellResponse = powershell.execute(getPowershellRequest(
toAllMailboxesCommand(setCASMailbox, activeSyncServer)));
if (powershellResponse.isSuccess()) {
log.info("Email outlook access policy successfully enforced for " + ceaPolicy.getTenantId());
} else {
log.error("Email outlook access policy enforcement procedure failed for " + ceaPolicy.getTenantId());
}
} catch (GatewayServiceException e) {
String msg = "Active sync auth service failed while enforcing default " +
"CEA email outlook access policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
} catch (PowershellExecutionException e) {
String msg = "Error occurred while executing powershell command for enforcing " +
"CEA email outlook access policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
}
}
@Enforce
public void enforcePOPIMAPAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException {
if (ceaPolicy.getAccessPolicy().getPOPIMAPAccessPolicy().
equalsName(EmailOutlookAccessPolicy.NOT_CONFIGURED.name())) {
if (log.isDebugEnabled()) {
log.debug("CEA POP/IMAP policy not configured, but support is available in " +
ExchangeOnlineCEAEnforcementServiceImpl.class);
}
return;
}
ActiveSyncServer activeSyncServer = ceaPolicy.getActiveSyncServer();
try {
PowershellCommand setCASMailbox = getCommand(Parser.COMMAND_SetCASMailbox.COMMAND,
activeSyncServer);
String POPIMAPPolicy = ceaPolicy.getAccessPolicy().getPOPIMAPAccessPolicy().toString();
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_Identity, "$_.Identity");
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_ImapEnabled,
Parser.COMMAND_SetCASMailbox.POLICY_TO_VALUE.get(POPIMAPPolicy));
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_PopEnabled,
Parser.COMMAND_SetCASMailbox.POLICY_TO_VALUE.get(POPIMAPPolicy));
PowershellResponse powershellResponse = powershell.execute(getPowershellRequest(
toAllMailboxesCommand(setCASMailbox, activeSyncServer)));
if (powershellResponse.isSuccess()) {
log.info("POP/IMAP access policy successfully enforced for " + ceaPolicy.getTenantId());
} else {
log.error("POP/IMAP access policy enforcement procedure failed for " + ceaPolicy.getTenantId());
}
} catch (GatewayServiceException e) {
String msg = "Active sync auth service failed while enforcing default CEA POP/IMAP policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
} catch (PowershellExecutionException e) {
String msg = "Error occurred while executing powershell command for enforcing " +
"CEA POP/IMAP policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
}
}
@Enforce
public void enforceWebOutlookAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException {
if (ceaPolicy.getAccessPolicy().getWebOutlookAccessPolicy().
equalsName(WebOutlookAccessPolicy.NOT_CONFIGURED.name())) {
if (log.isDebugEnabled()) {
log.debug("CEA Outlook web access policy not configured, but support is available in " +
ExchangeOnlineCEAEnforcementServiceImpl.class);
}
return;
}
ActiveSyncServer activeSyncServer = ceaPolicy.getActiveSyncServer();
try {
PowershellCommand setCASMailbox = getCommand(Parser.COMMAND_SetCASMailbox.COMMAND,
activeSyncServer);
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_Identity, "$_.Identity");
setCASMailbox.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_OWAEnabled,
Parser.COMMAND_SetCASMailbox.POLICY_TO_VALUE.get(ceaPolicy.getAccessPolicy().
getWebOutlookAccessPolicy().toString()));
PowershellResponse powershellResponse = powershell.execute(getPowershellRequest(
toAllMailboxesCommand(setCASMailbox, activeSyncServer)));
if (powershellResponse.isSuccess()) {
log.info("Web outlook access policy successfully enforced for " + ceaPolicy.getTenantId());
} else {
log.error("Web outlook access policy enforcement procedure failed for " + ceaPolicy.getTenantId());
}
} catch (GatewayServiceException e) {
String msg = "Active sync auth service failed while enforcing CEA web outlook access policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
} catch (PowershellExecutionException e) {
String msg = "Error occurred while executing powershell command for enforcing " +
"CEA web outlook access policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
}
}
@Enforce
public void enforceConditionalAccessPolicy(CEAPolicy ceaPolicy) throws CEAEnforcementException {
GracePeriod gracePeriod = ceaPolicy.getGracePeriod();
ActiveSyncServer activeSyncServer = ceaPolicy.getActiveSyncServer();
boolean isSynced = ceaPolicy.isSynced();
Date created = ceaPolicy.getCreated();
Date lastSynced = ceaPolicy.getLastSynced();
/*
* Here we are filtering the devices(active sync devices) which are communicating
* with the exchange online server into valid and not valid categories.
* Valid category can contain devices which are currently managed by UEM or devices
* which are syncing with the exchange online server under a grace period.
* */
try {
/* Get the devices based on the last sync timestamp or cea policy created
* time to avoid unnecessary device bulks.
* */
List<ActiveSyncDevice> validActiveSyncDevices = isSynced ? DeviceMgtUtil.
getEnrolledActiveSyncDevicesSince(lastSynced) :
DeviceMgtUtil.getEnrolledActiveSyncDevicesPriorTo(new Date());
List<ActiveSyncDevice> notValidActiveSyncDevices = new ArrayList<>();
List<ActiveSyncDevice> connectedActiveSyncDevices = isSynced ?
getConnectedActiveSyncDevicesAfter(lastSynced, activeSyncServer) :
getAllConnectedActiveSyncDevices(activeSyncServer);
for (ActiveSyncDevice activeSyncDevice : connectedActiveSyncDevices) {
if (!EASMgtUtil.isManageByUEM(activeSyncDevice.getDeviceId())
&& !validActiveSyncDevices.contains(activeSyncDevice)) {
notValidActiveSyncDevices.add(activeSyncDevice);
} else {
validActiveSyncDevices.add(activeSyncDevice);
}
}
if (gracePeriod.getGraceAllowedPolicy().equalsName(GraceAllowedPolicy.NOT_ALLOWED.name())) {
// Block grace offered new devices if exists
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -Constants.MAX_GRACE_PERIOD_IN_DAYS);
List<ActiveSyncDevice> graceExceededNewlyConnectedActiveSyncDevices =
getConnectedActiveSyncDevicesAfter(calendar.getTime(), activeSyncServer);
List<ActiveSyncDevice> managedDevices = DeviceMgtUtil.getEnrolledActiveSyncDevicesSince(calendar.getTime());
for (ActiveSyncDevice activeSyncDevice : graceExceededNewlyConnectedActiveSyncDevices) {
if (!EASMgtUtil.isManageByUEM(activeSyncDevice.getDeviceId())
&& !managedDevices.contains(activeSyncDevice)) {
validActiveSyncDevices.remove(activeSyncDevice);
notValidActiveSyncDevices.add(activeSyncDevice);
} else {
// These devices are managed by UEM, so add to the valid category
notValidActiveSyncDevices.remove(activeSyncDevice);
validActiveSyncDevices.add(activeSyncDevice);
}
}
// Block grace offered existing devices if exists
List<ActiveSyncDevice> connectedActiveSyncDevicesBeforeTheCreationOfCEAPolicy =
getConnectedActiveSyncDevicesBefore(created, activeSyncServer);
for (ActiveSyncDevice activeSyncDevice: connectedActiveSyncDevicesBeforeTheCreationOfCEAPolicy) {
if (!EASMgtUtil.isManageByUEM(activeSyncDevice.getDeviceId())
&& !validActiveSyncDevices.contains(activeSyncDevice)) {
validActiveSyncDevices.remove(activeSyncDevice);
notValidActiveSyncDevices.add(activeSyncDevice);
} else {
// These devices are managed by UEM, so add to the valid category
notValidActiveSyncDevices.remove(activeSyncDevice);
validActiveSyncDevices.add(activeSyncDevice);
}
}
}
if (gracePeriod.getGraceAllowedPolicy().equalsName(GraceAllowedPolicy.NEW_AND_EXISTING.name()) ||
gracePeriod.getGraceAllowedPolicy().equalsName(GraceAllowedPolicy.NEW_ONLY.name())) {
List<ActiveSyncDevice> newlyConnectedActiveSyncDevices =
getConnectedActiveSyncDevicesAfter(isSynced ? lastSynced : created, activeSyncServer);
for (ActiveSyncDevice activeSyncDevice : newlyConnectedActiveSyncDevices) {
if (!EASMgtUtil.isManageByUEM(activeSyncDevice.getDeviceId())
&& !validActiveSyncDevices.contains(activeSyncDevice)) {
long timeDiff = Math.abs(new Date().getTime() - activeSyncDevice.getFirstSyncTime().getTime());
// Enforce the grace period if the device not exceeds the grace limit
if (TimeUnit.DAYS.convert(timeDiff, TimeUnit.MILLISECONDS) < gracePeriod.getGracePeriod()) {
notValidActiveSyncDevices.remove(activeSyncDevice);
validActiveSyncDevices.add(activeSyncDevice);
} else {
validActiveSyncDevices.remove(activeSyncDevice);
notValidActiveSyncDevices.add(activeSyncDevice);
}
} else {
// These devices are managed by UEM, so add to the valid category
notValidActiveSyncDevices.remove(activeSyncDevice);
validActiveSyncDevices.add(activeSyncDevice);
}
}
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -Constants.MAX_GRACE_PERIOD_IN_DAYS);
List<ActiveSyncDevice> graceExceededNewlyConnectedActiveSyncDevices =
getConnectedActiveSyncDevicesAfter(calendar.getTime(), activeSyncServer);
List<ActiveSyncDevice> managedDevices = DeviceMgtUtil.getEnrolledActiveSyncDevicesSince(calendar.getTime());
for (ActiveSyncDevice activeSyncDevice : graceExceededNewlyConnectedActiveSyncDevices) {
if (!EASMgtUtil.isManageByUEM(activeSyncDevice.getDeviceId())
&& !managedDevices.contains(activeSyncDevice)) {
long timeDiff = Math.abs(new Date().getTime() - activeSyncDevice.getFirstSyncTime().getTime());
// Enforce the grace period if the device isn't exceeds the current grace limit
if (TimeUnit.DAYS.convert(timeDiff, TimeUnit.MILLISECONDS) < gracePeriod.getGracePeriod()) {
notValidActiveSyncDevices.remove(activeSyncDevice);
validActiveSyncDevices.add(activeSyncDevice);
} else {
validActiveSyncDevices.remove(activeSyncDevice);
notValidActiveSyncDevices.add(activeSyncDevice);
}
} else {
notValidActiveSyncDevices.remove(activeSyncDevice);
validActiveSyncDevices.add(activeSyncDevice);
}
}
}
if (gracePeriod.getGraceAllowedPolicy().equalsName(GraceAllowedPolicy.NEW_AND_EXISTING.name()) ||
gracePeriod.getGraceAllowedPolicy().equalsName(GraceAllowedPolicy.EXISTING_ONLY.name())) {
long timeDiffBetweenCEAPolicyCreatedAndNow = Math.abs(new Date().getTime() - ceaPolicy.getCreated().getTime());
List<ActiveSyncDevice> connectedActiveSyncDevicesBeforeTheCreationOfCEAPolicy =
getConnectedActiveSyncDevicesBefore(created, activeSyncServer);
for (ActiveSyncDevice activeSyncDevice: connectedActiveSyncDevicesBeforeTheCreationOfCEAPolicy) {
if (!EASMgtUtil.isManageByUEM(activeSyncDevice.getDeviceId())
&& !validActiveSyncDevices.contains(activeSyncDevice)) {
// Enforce the grace period if the device not exceeds the grace limit
if(TimeUnit.DAYS.convert(timeDiffBetweenCEAPolicyCreatedAndNow, TimeUnit.MILLISECONDS)
< gracePeriod.getGracePeriod()) {
notValidActiveSyncDevices.remove(activeSyncDevice);
validActiveSyncDevices.add(activeSyncDevice);
} else {
validActiveSyncDevices.remove(activeSyncDevice);
notValidActiveSyncDevices.add(activeSyncDevice);
}
} else {
// These devices are managed by UEM, so add to the valid category
notValidActiveSyncDevices.remove(activeSyncDevice);
validActiveSyncDevices.add(activeSyncDevice);
}
}
}
List<MailboxProfile> mailboxProfiles = generateMailboxPolicies(validActiveSyncDevices,
notValidActiveSyncDevices);
for (MailboxProfile mailboxProfile : mailboxProfiles) {
PowershellCommand powershellCommand = getCommand(Parser.COMMAND_SetCASMailbox.COMMAND, activeSyncServer);
powershellCommand.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_Identity, mailboxProfile.getIdentity());
powershellCommand.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_ActiveSyncAllowedDeviceIDs,
mailboxProfile.getAllowedEASIdentifierString());
powershellCommand.addOption(Parser.COMMAND_SetCASMailbox.PARAMETER_ActiveSyncBlockedDeviceIDs,
mailboxProfile.getBlockedEASIdentifierString());
powershell.execute(getPowershellRequest(powershellCommand));
}
} catch (GatewayServiceException e) {
String msg = "Active sync auth service failed while enforcing CEA policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
} catch (PowershellExecutionException e) {
String msg = "Error occurred while executing powershell command for enforcing CEA policy";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
} catch (DeviceManagementException | UserStoreException e) {
String msg = "Error occurred while retrieving active sync devices";
log.error(msg, e);
throw new CEAEnforcementException(msg, e);
}
}
private PowershellCommand getCommand(String command, ActiveSyncServer activeSyncServer)
throws GatewayServiceException {
String[] urlParts = activeSyncServer.getGatewayUrl().split("/");
ExoPowershellCommand.ExoPowershellCommandBuilder commandBuilder =
new ExoPowershellCommand.ExoPowershellCommandBuilder(command);
commandBuilder.accessToken(gatewayService.acquireAccessToken(activeSyncServer))
.organization(urlParts[urlParts.length - 1]);
return commandBuilder.build();
}
private PowershellCommand toAllMailboxesCommand(PowershellCommand command,
ActiveSyncServer activeSyncServer) throws GatewayServiceException {
PowershellCommand getEXOMailbox = getCommand(Parser.COMMAND_GetEXOMailbox.COMMAND, activeSyncServer);
getEXOMailbox.addOption(Parser.COMMAND_GetEXOMailbox.PARAMETER_ResultSize, "unlimited");
PowershellCommand forEach = getCommand(Parser.COMMAND_ForEach.COMMAND, activeSyncServer);
forEach.addOption(Parser.COMMAND_ForEach.PARAMETER_Begin, "$upn = $_.UserPrincipalName;" + command.constructFullCommand());
forEach.addOption(Parser.COMMAND_ForEach.PARAMETER_End, "");
getEXOMailbox.pipe(forEach);
getEXOMailbox.setConvertToJson(false);
return getEXOMailbox;
}
private PowershellRequest getPowershellRequest(PowershellCommand command) {
PowershellRequest powershellRequest = new PowershellRequest();
powershellRequest.setCommand(command);
return powershellRequest;
}
private List<MailboxProfile> generateMailboxPolicies(List<ActiveSyncDevice> activeSyncAllowedDevices,
List<ActiveSyncDevice> activeSyncBlockedDevices) {
List<MailboxProfile> mailboxProfiles = new ArrayList<>();
MailboxProfile mailboxProfile;
for (ActiveSyncDevice activeSyncDevice : activeSyncAllowedDevices) {
mailboxProfile = new MailboxProfile();
mailboxProfile.setIdentity(activeSyncDevice.getUserPrincipalName());
if (mailboxProfiles.contains(mailboxProfile)) {
MailboxProfile existingMailboxProfile = mailboxProfiles.get(mailboxProfiles.indexOf(mailboxProfile));
existingMailboxProfile.addActiveSyncAllowedEASIdentifier(activeSyncDevice.getDeviceId());
} else {
mailboxProfile.addActiveSyncAllowedEASIdentifier(activeSyncDevice.getDeviceId());
mailboxProfiles.add(mailboxProfile);
}
}
for (ActiveSyncDevice activeSyncDevice : activeSyncBlockedDevices) {
mailboxProfile = new MailboxProfile();
mailboxProfile.setIdentity(activeSyncDevice.getUserPrincipalName());
if (mailboxProfiles.contains(mailboxProfile)) {
MailboxProfile existingMailboxProfile = mailboxProfiles.get(mailboxProfiles.indexOf(mailboxProfile));
existingMailboxProfile.addActiveSyncBlockEASIdentifier(activeSyncDevice.getDeviceId());
} else {
mailboxProfile.addActiveSyncBlockEASIdentifier(activeSyncDevice.getDeviceId());
mailboxProfiles.add(mailboxProfile);
}
}
return mailboxProfiles;
}
private List<ActiveSyncDevice> constructActiveSyncDeviceList(PowershellResponse powershellResponse)
throws CEAEnforcementException {
if (powershellResponse == null) {
throw new CEAEnforcementException("Powershell response can't be null");
}
if (!powershellResponse.isSuccess()) {
throw new CEAEnforcementException("Powershell request failed while getting active sync devices");
}
if (powershellResponse.getResponseBody() == null) {
return Collections.emptyList();
}
if (!powershellResponse.getResponseBody().isJsonArray()) {
throw new CEAEnforcementException("Unexpected result retrieve when getting active sync devices");
}
SimpleDateFormat powershellDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
List<ActiveSyncDevice> activeSyncDevices = new ArrayList<>();
JsonArray elements = powershellResponse.getResponseBody().getAsJsonArray();
JsonObject deviceJsonObject;
ActiveSyncDevice activeSyncDevice;
for (JsonElement element : elements) {
try {
deviceJsonObject = element.getAsJsonObject();
activeSyncDevice = new ActiveSyncDevice();
activeSyncDevice.setUserPrincipalName(deviceJsonObject.get("UserPrincipalName").getAsString());
activeSyncDevice.setDeviceId(deviceJsonObject.get("DeviceID").getAsString());
activeSyncDevice.setIdentity(deviceJsonObject.get("Identity").getAsString());
activeSyncDevice.setFirstSyncTime(powershellDateFormat.parse(deviceJsonObject.get("FirstSyncTime").getAsString()));
activeSyncDevices.add(activeSyncDevice);
} catch (ParseException e) {
throw new CEAEnforcementException("Error occurred while parsing active sync device json element");
}
}
return activeSyncDevices;
}
private List<ActiveSyncDevice> getConnectedActiveSyncDevicesAfter(Date after, ActiveSyncServer activeSyncServer)
throws GatewayServiceException, PowershellExecutionException, CEAEnforcementException {
SimpleDateFormat powershellDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
PowershellCommand getEXOMobileDeviceStatistics = getCommand(Parser.COMMAND_GetEXOMobileDeviceStatistics.COMMAND,
activeSyncServer);
getEXOMobileDeviceStatistics.addOption(Parser.COMMAND_GetEXOMobileDeviceStatistics.PARAMETER_ActiveSync, "");
getEXOMobileDeviceStatistics.addOption(
Parser.COMMAND_GetEXOMobileDeviceStatistics.PARAMETER_Mailbox, "$_.Identity");
PowershellCommand selectObject = getCommand(Parser.COMMAND_SelectObject.COMMAND, activeSyncServer);
selectObject.addOption("@{label='UserPrincipalName' ; expression={$upn}},FirstSyncTime, DeviceID, Identity", "");
PowershellCommand whereObject = getCommand(Parser.COMMAND_WhereObject.COMMAND, activeSyncServer);
whereObject.addOption(Parser.COMMAND_WhereObject.PARAMETER_Begin, "$_.FirstSyncTime -gt "
+ "'" + powershellDateFormat.format(after) + "'");
whereObject.addOption(Parser.COMMAND_WhereObject.PARAMETER_End, "");
PowershellCommand convertToJson = getCommand(Parser.COMMAND_ConvertToJson.COMMAND, activeSyncServer);
convertToJson.addOption(Parser.COMMAND_ConvertToJson.PARAMETER_AsArray, "");
getEXOMobileDeviceStatistics.pipe(selectObject).pipe(whereObject).pipe(convertToJson);
PowershellCommand toAllMailboxes = toAllMailboxesCommand(getEXOMobileDeviceStatistics, activeSyncServer);
PowershellRequest powershellRequest = getPowershellRequest(toAllMailboxes);
PowershellResponse powershellResponse = powershell.execute(powershellRequest);
return constructActiveSyncDeviceList(powershellResponse);
}
private List<ActiveSyncDevice> getConnectedActiveSyncDevicesBefore(Date before, ActiveSyncServer activeSyncServer)
throws GatewayServiceException, PowershellExecutionException, CEAEnforcementException {
SimpleDateFormat powershellDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
PowershellCommand getEXOMobileDeviceStatistics = getCommand(Parser.COMMAND_GetEXOMobileDeviceStatistics.COMMAND,
activeSyncServer);
getEXOMobileDeviceStatistics.addOption(Parser.COMMAND_GetEXOMobileDeviceStatistics.PARAMETER_ActiveSync, "");
getEXOMobileDeviceStatistics.addOption(
Parser.COMMAND_GetEXOMobileDeviceStatistics.PARAMETER_Mailbox, "$_.Identity");
PowershellCommand selectObject = getCommand(Parser.COMMAND_SelectObject.COMMAND, activeSyncServer);
selectObject.addOption("@{label='UserPrincipalName' ; expression={$upn}},FirstSyncTime, DeviceID, Identity", "");
PowershellCommand whereObject = getCommand(Parser.COMMAND_WhereObject.COMMAND, activeSyncServer);
whereObject.addOption(Parser.COMMAND_WhereObject.PARAMETER_Begin, "$_.FirstSyncTime -lt "
+ "'" + powershellDateFormat.format(before) + "'");
whereObject.addOption(Parser.COMMAND_WhereObject.PARAMETER_End, "");
PowershellCommand convertToJson = getCommand(Parser.COMMAND_ConvertToJson.COMMAND, activeSyncServer);
convertToJson.addOption(Parser.COMMAND_ConvertToJson.PARAMETER_AsArray, "");
getEXOMobileDeviceStatistics.pipe(selectObject).pipe(whereObject).pipe(convertToJson);
PowershellCommand toAllMailboxes = toAllMailboxesCommand(getEXOMobileDeviceStatistics, activeSyncServer);
PowershellRequest powershellRequest = getPowershellRequest(toAllMailboxes);
PowershellResponse powershellResponse = powershell.execute(powershellRequest);
return constructActiveSyncDeviceList(powershellResponse);
}
private List<ActiveSyncDevice> getAllConnectedActiveSyncDevices(ActiveSyncServer activeSyncServer)
throws GatewayServiceException, PowershellExecutionException, CEAEnforcementException {
PowershellCommand getEXOMobileDeviceStatistics = getCommand(Parser.COMMAND_GetEXOMobileDeviceStatistics.COMMAND,
activeSyncServer);
getEXOMobileDeviceStatistics.addOption(Parser.COMMAND_GetEXOMobileDeviceStatistics.PARAMETER_ActiveSync, "");
getEXOMobileDeviceStatistics.addOption(
Parser.COMMAND_GetEXOMobileDeviceStatistics.PARAMETER_Mailbox, "$_.Identity");
PowershellCommand convertToJson = getCommand(Parser.COMMAND_ConvertToJson.COMMAND, activeSyncServer);
convertToJson.addOption(Parser.COMMAND_ConvertToJson.PARAMETER_AsArray, "");
PowershellCommand selectObject = getCommand(Parser.COMMAND_SelectObject.COMMAND, activeSyncServer);
selectObject.addOption("@{label='UserPrincipalName' ; expression={$upn}},FirstSyncTime, DeviceID, Identity", "");
getEXOMobileDeviceStatistics.pipe(selectObject).pipe(convertToJson);
PowershellCommand toAllMailboxes = toAllMailboxesCommand(getEXOMobileDeviceStatistics, activeSyncServer);
PowershellRequest powershellRequest = getPowershellRequest(toAllMailboxes);
PowershellResponse powershellResponse = powershell.execute(powershellRequest);
return constructActiveSyncDeviceList(powershellResponse);
}
}

@ -0,0 +1,97 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.Impl.gateway;
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.IClientCredential;
import com.microsoft.aad.msal4j.IConfidentialClientApplication;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServer;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.GatewayServiceException;
import io.entgra.device.mgt.core.cea.mgt.enforce.service.gateway.GatewayService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
public class ExchangeOnlineGatewayServiceImpl implements GatewayService {
private static final Log log = LogFactory.getLog(ExchangeOnlineGatewayServiceImpl.class);
private static final Set<String> SCOPES = new HashSet<>(Collections.singletonList("https://outlook.office365.com/.default"));
private static final Map<String, IConfidentialClientApplication> confidentialClientApplications = new HashMap<>();
@Override
public String acquireAccessToken(ActiveSyncServer activeSyncServer) throws GatewayServiceException {
try {
IConfidentialClientApplication confidentialClientApplication = getOrCreateConfidentialClientApplication(
activeSyncServer.getClient(), activeSyncServer.getSecret(), activeSyncServer.getGatewayUrl());
ClientCredentialParameters clientCredentialParameters = ClientCredentialParameters.builder(SCOPES).build();
IAuthenticationResult result = confidentialClientApplication.acquireToken(clientCredentialParameters).get();
if (log.isDebugEnabled()) {
log.debug("Access token acquiring process is successful");
}
return result.accessToken();
} catch (MalformedURLException e) {
String msg = "Error occurred while constructing confidential client application";
log.error(msg, e);
throw new GatewayServiceException(msg, e);
} catch (InterruptedException e) {
String msg = "Error occurred while acquiring access token";
log.error(msg, e);
throw new GatewayServiceException(msg, e);
} catch (ExecutionException e) {
String msg = "Error occurred while executing token acquiring access token";
log.error(msg, e);
throw new GatewayServiceException(msg, e);
}
}
@Override
public boolean validate(ActiveSyncServer activeSyncServer) throws GatewayServiceException {
try {
IConfidentialClientApplication confidentialClientApplication = getOrCreateConfidentialClientApplication(
activeSyncServer.getClient(), activeSyncServer.getSecret(), activeSyncServer.getGatewayUrl());
return confidentialClientApplication.validateAuthority();
} catch (MalformedURLException e) {
String msg = "Error occurred while constructing confidential client application";
log.error(msg, e);
throw new GatewayServiceException(msg, e);
}
}
private IConfidentialClientApplication getOrCreateConfidentialClientApplication(String clientId, String secret, String authority)
throws MalformedURLException {
IConfidentialClientApplication confidentialClientApplication = confidentialClientApplications.get(clientId);
if (confidentialClientApplication == null) {
IClientCredential credential = ClientCredentialFactory.createFromSecret(secret);
confidentialClientApplication = ConfidentialClientApplication.
builder(clientId, credential).authority(authority).build();
confidentialClientApplications.put(clientId, confidentialClientApplication);
}
return confidentialClientApplication;
}
}

@ -0,0 +1,85 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.bean;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ExoPowershellCommand extends PowershellCommand {
private static final String COMMAND_IMPORT_MODULE_EXO = "Import-Module ExchangeOnlineManagement" + SYMBOL_END_LINE;
private static final String COMMAND_CONVERT_TO_JSON = "ConvertTo-Json";
private final String accessToken;
private final String organization;
protected ExoPowershellCommand(String command, String accessToken, String organization) {
super(command);
this.accessToken = accessToken;
this.organization = organization;
}
public String getCommandString() {
List<String> partsOfCommand = new ArrayList<>(Arrays.asList(
COMMAND_IMPORT_MODULE_EXO,
constructConnectionCommand(),
constructFullCommand(),
SYMBOL_PIPE));
if (isOutputNull) {
partsOfCommand.add(COMMAND_OUTPUT_NULL);
} else if (convertToJson) {
partsOfCommand.add(COMMAND_CONVERT_TO_JSON);
} else {
partsOfCommand.remove(partsOfCommand.size() - 1);
}
return String.join(SYMBOL_SPLITTER, partsOfCommand);
}
private String constructConnectionCommand() {
return "Connect-ExchangeOnline" +
" -Organization " + organization +
" -AccessToken " + accessToken + " -ShowBanner:$false" + SYMBOL_END_LINE;
}
public static class ExoPowershellCommandBuilder {
private final String command;
private String accessToken;
private String organization;
public ExoPowershellCommandBuilder(String command) {
this.command = command;
}
public ExoPowershellCommandBuilder accessToken(String accessToken) {
this.accessToken = accessToken;
return this;
}
public ExoPowershellCommandBuilder organization(String organization) {
this.organization = organization;
return this;
}
public ExoPowershellCommand build() {
return new ExoPowershellCommand(command, accessToken, organization);
}
}
}

@ -0,0 +1,82 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.bean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class PowershellCommand {
protected static final String COMMAND_OUTPUT_NULL = "Out-Null;";
protected static final String SYMBOL_PIPE = "|";
protected static final String SYMBOL_SPLITTER = "&";
protected static final String SYMBOL_END_LINE = ";";
protected final String command;
protected final Map<String, String> parameters = new HashMap<>();
protected boolean isOutputNull = false;
protected boolean convertToJson = true;
protected PowershellCommand pipedCommand;
public PowershellCommand(String command) {
this.command = command;
}
public boolean isOutputNull() {
return isOutputNull;
}
public void setOutputNull(boolean outputNull) {
isOutputNull = outputNull;
}
public boolean isConvertToJson() {
return convertToJson;
}
public void setConvertToJson(boolean convertToJson) {
this.convertToJson = convertToJson;
}
public void addOption(String option, String value) {
parameters.put(option, value);
}
protected String constructParameterString() {
List<String> optionList = new ArrayList<>();
for (String option : parameters.keySet()) {
optionList.add(option + " " + parameters.get(option));
}
return String.join(" ", optionList);
}
public String constructFullCommand() {
String fullCommand = command + " " + constructParameterString();
return pipedCommand == null ? fullCommand :
fullCommand + SYMBOL_SPLITTER + SYMBOL_PIPE + SYMBOL_SPLITTER + pipedCommand.constructFullCommand();
}
public PowershellCommand pipe(PowershellCommand command) {
pipedCommand = command;
return command;
}
public abstract String getCommandString();
}

@ -0,0 +1,32 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.bean;
public class PowershellRequest {
private PowershellCommand command;
public PowershellCommand getCommand() {
return command;
}
public void setCommand(PowershellCommand command) {
this.command = command;
}
}

@ -0,0 +1,68 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.bean;
import com.google.gson.JsonElement;
public class PowershellResponse {
private JsonElement responseBody;
private String error;
private int code;
private boolean isSuccess;
public PowershellResponse(JsonElement responseBody, String error, int code, boolean isSuccess) {
this.responseBody = responseBody;
this.error = error;
this.code = code;
this.isSuccess = isSuccess;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public JsonElement getResponseBody() {
return responseBody;
}
public void setResponseBody(JsonElement responseBody) {
this.responseBody = responseBody;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean success) {
isSuccess = success;
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.exception;
public class CEAPolicyOperationException extends Exception {
public CEAPolicyOperationException(String msg) {
super(msg);
}
public CEAPolicyOperationException(String msg, Throwable t) {
super(msg, t);
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.exception;
public class GatewayServiceException extends Exception {
public GatewayServiceException(String msg) {
super(msg);
}
public GatewayServiceException(String msg, Throwable t) {
super(msg, t);
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.exception;
public class PowershellExecutionException extends Exception {
public PowershellExecutionException(String msg) {
super(msg);
}
public PowershellExecutionException(String msg, Throwable t) {
super(msg, t);
}
}

@ -0,0 +1,26 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.exception;
public class UnsupportedOsException extends Exception {
public UnsupportedOsException(String msg) {
super(msg);
}
}

@ -0,0 +1,90 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.internal;
import io.entgra.device.mgt.core.cea.mgt.common.service.EnforcementServiceManager;
import io.entgra.device.mgt.core.cea.mgt.enforce.Impl.EnforcementServiceManagerImpl;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.user.core.service.RealmService;
/**
* @scr.component name="io.entgra.device.mgt.core.cea.mgt.enforcementServiceManager" immediate="true"
* @scr.reference name="org.wso2.carbon.device.manager"
* interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceManagementServiceProviderService"
* unbind="unsetDeviceManagementServiceProviderService"
* @scr.reference name="user.realmservice.default"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRealmService"
* unbind="unsetRealmService"
*/
public class EnforcementServiceComponent {
private static final Log log = LogFactory.getLog(EnforcementServiceComponent.class);
protected void activate(ComponentContext componentContext) {
try {
EnforcementServiceManager enforcementServiceManager = new EnforcementServiceManagerImpl();
componentContext.getBundleContext().registerService(EnforcementServiceManager.class.getName(),
enforcementServiceManager, null);
if (log.isDebugEnabled()) {
log.debug("Enforcement service manager initialized");
}
} catch (Throwable t) {
String msg = "Error occurred while activating " + EnforcementServiceComponent.class.getName();
log.error(msg, t);
}
}
protected void setDeviceManagementServiceProviderService(DeviceManagementProviderService deviceManagementProviderService) {
EnforcementServiceComponentDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService);
if (log.isDebugEnabled()) {
log.debug("Device management provider service is set successfully");
}
}
protected void unsetDeviceManagementServiceProviderService(DeviceManagementProviderService deviceManagementProviderService) {
EnforcementServiceComponentDataHolder.getInstance().setDeviceManagementProviderService(null);
if (log.isDebugEnabled()) {
log.debug("Device management provider service is unset successfully");
}
}
protected void setRealmService(RealmService realmService) {
EnforcementServiceComponentDataHolder.getInstance().setRealmService(realmService);
if (log.isDebugEnabled()) {
log.debug("Realm service is set successfully");
}
}
protected void unsetRealmService(RealmService realmService) {
EnforcementServiceComponentDataHolder.getInstance().setRealmService(null);
if (log.isDebugEnabled()) {
log.debug("Realm service is unset successfully");
}
}
}

@ -0,0 +1,55 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.internal;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.user.core.service.RealmService;
public class EnforcementServiceComponentDataHolder {
private DeviceManagementProviderService deviceManagementProviderService;
private RealmService realmService;
EnforcementServiceComponentDataHolder() {
}
public static EnforcementServiceComponentDataHolder getInstance() {
return EnforcementServiceComponentDataHolderRegistry.INSTANCE;
}
public DeviceManagementProviderService getDeviceManagementProviderService() {
return deviceManagementProviderService;
}
public void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) {
this.deviceManagementProviderService = deviceManagementProviderService;
}
public RealmService getRealmService() {
return realmService;
}
public void setRealmService(RealmService realmService) {
this.realmService = realmService;
}
private static class EnforcementServiceComponentDataHolderRegistry {
public static final EnforcementServiceComponentDataHolder INSTANCE = new EnforcementServiceComponentDataHolder();
}
}

@ -0,0 +1,31 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.service;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.CEAPolicyOperationException;
public interface CEAPolicyOperation {
/**
* Sync with the active sync server and enforce the conditional access policy
*
* @throws CEAPolicyOperationException Throws when error occurred while performing enforcement operations
*/
void enforce() throws CEAPolicyOperationException;
}

@ -0,0 +1,43 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.service.gateway;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServer;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.GatewayServiceException;
public interface GatewayService {
/**
* Retrieve access token to invoke active sync server endpoints
*
* @param activeSyncServer {@link ActiveSyncServer}
* @return Obtained access token
* @throws GatewayServiceException Throws when error occurred while obtaining an access token
*/
String acquireAccessToken(ActiveSyncServer activeSyncServer) throws GatewayServiceException;
/**
* Validate the access token
*
* @param activeSyncServer {@link ActiveSyncServer}
* @return True when the token is valid, otherwise false
* @throws GatewayServiceException Throws when error occurred while validating the token
*/
boolean validate(ActiveSyncServer activeSyncServer) throws GatewayServiceException;
}

@ -0,0 +1,27 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.util;
public class Constants {
public static final String EMAIL_CLAIM_URI = "http://wso2.org/claims/emailaddress";
public static final String DEVICE_TYPE_ANDROID = "android";
public static final String DEVICE_PROPERTY_EAS_ID = "EASDeviceIdentifier";
public static final String METHOD_NAME_GET_INSTANCE = "getInstance";
}

@ -0,0 +1,131 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.util;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncDevice;
import io.entgra.device.mgt.core.cea.mgt.enforce.internal.EnforcementServiceComponentDataHolder;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class DeviceMgtUtil {
private static final Log log = LogFactory.getLog(DeviceMgtUtil.class);
public static List<ActiveSyncDevice> getEnrolledActiveSyncDevicesSince(Date since)
throws DeviceManagementException, UserStoreException {
DeviceManagementProviderService deviceManagementProviderService = getDeviceManagementProviderService();
if (deviceManagementProviderService == null) {
String msg = "Device management provider service has not initialized";
log.error(msg);
throw new IllegalStateException(msg);
}
List<Device> devices = deviceManagementProviderService.getEnrolledDevicesSince(since);
if (devices == null) {
return new ArrayList<>();
}
return DeviceMgtUtil.constructActiveSyncDeviceList(devices);
}
public static List<ActiveSyncDevice> getEnrolledActiveSyncDevicesPriorTo(Date priorTo)
throws DeviceManagementException, UserStoreException {
DeviceManagementProviderService deviceManagementProviderService = getDeviceManagementProviderService();
if (deviceManagementProviderService == null) {
String msg = "Device management provider service has not initialized";
log.error(msg);
throw new IllegalStateException(msg);
}
List<Device> devices = deviceManagementProviderService.getEnrolledDevicesPriorTo(priorTo);
if (devices == null) {
return new ArrayList<>();
}
return DeviceMgtUtil.constructActiveSyncDeviceList(devices);
}
private static DeviceManagementProviderService getDeviceManagementProviderService() {
return EnforcementServiceComponentDataHolder.getInstance().getDeviceManagementProviderService();
}
private static UserStoreManager getUserStoreManager(int tenantId) throws UserStoreException {
RealmService realmService = EnforcementServiceComponentDataHolder.getInstance().getRealmService();
if (realmService == null) {
String msg = "Realm service has not initialized";
log.error(msg);
throw new IllegalStateException(msg);
}
return realmService.getTenantUserRealm(tenantId).getUserStoreManager();
}
private static String getIdentity(String owner, UserStoreManager userStoreManager)
throws UserStoreException {
return userStoreManager.getUserClaimValue(owner, Constants.EMAIL_CLAIM_URI, null);
}
private static List<ActiveSyncDevice> constructActiveSyncDeviceList(List<Device> devices)
throws UserStoreException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
List<ActiveSyncDevice> activeSyncDevices = new ArrayList<>();
UserStoreManager userStoreManager = getUserStoreManager(tenantId);
if (userStoreManager == null) {
String msg = "Retrieved null for user store manager";
log.error(msg);
throw new IllegalStateException(msg);
}
// filter out the android devices since android devices are resolved from the active sync server
devices = devices.stream().filter(device -> !Objects.equals(device.getType(), Constants.DEVICE_TYPE_ANDROID)).
collect(Collectors.toList());
for (Device device : devices) {
activeSyncDevices.add(mapToActiveSyncDevice(device, userStoreManager));
}
return activeSyncDevices;
}
public static ActiveSyncDevice mapToActiveSyncDevice(Device device, UserStoreManager userStoreManager)
throws UserStoreException {
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
ActiveSyncDevice activeSyncDevice = new ActiveSyncDevice();
activeSyncDevice.setUserPrincipalName(DeviceMgtUtil.getIdentity(enrolmentInfo.getOwner(), userStoreManager));
if (!Objects.equals(device.getType(), Constants.DEVICE_TYPE_ANDROID)) {
for (Device.Property property : device.getProperties()) {
if (property != null && Objects.equals(property.getName(), Constants.DEVICE_PROPERTY_EAS_ID)) {
activeSyncDevice.setDeviceId(property.getValue());
}
}
}
return activeSyncDevice;
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.util.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Enforce {
}

@ -0,0 +1,58 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.util.shell;
import io.entgra.device.mgt.core.cea.mgt.enforce.bean.PowershellRequest;
import io.entgra.device.mgt.core.cea.mgt.enforce.bean.PowershellResponse;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.PowershellExecutionException;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.UnsupportedOsException;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.os.LinuxPowershell;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.os.MacPowershell;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.os.WindowsPowershell;
public interface Powershell {
String OS = System.getProperty("os.name").toLowerCase();
boolean IS_UNIX = (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0);
boolean IS_WINDOWS = (OS.indexOf("win") >= 0);
boolean IS_MAC = (OS.indexOf("mac") >= 0);
static Powershell getPowershell() throws UnsupportedOsException {
if (IS_UNIX) {
return LinuxPowershell.getInstance();
}
if (IS_WINDOWS) {
return WindowsPowershell.getInstance();
}
if (IS_MAC) {
return MacPowershell.getInstance();
}
throw new UnsupportedOsException("OS is not supported!");
}
/**
* Execute the powershell request
*
* @param powershellRequest {@link PowershellRequest}
* @return {@link PowershellResponse}
* @throws PowershellExecutionException Throws when error occurred while execution
*/
PowershellResponse execute(PowershellRequest powershellRequest) throws PowershellExecutionException;
}

@ -0,0 +1,111 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.os;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import io.entgra.device.mgt.core.cea.mgt.enforce.bean.PowershellRequest;
import io.entgra.device.mgt.core.cea.mgt.enforce.bean.PowershellResponse;
import io.entgra.device.mgt.core.cea.mgt.enforce.exception.PowershellExecutionException;
import io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.Powershell;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
public class AbstractPowershell implements Powershell {
protected static final String SYMBOL_SPLITTER = "&";
private static final String PARAMETER_COMMAND = "-Command";
private static final String COMMAND_REDIRECT_WARNINGS = "$WarningPreference = 'SilentlyContinue';";
private final String BINARY;
AbstractPowershell(String BINARY) {
this.BINARY = BINARY;
}
@Override
public PowershellResponse execute(PowershellRequest powershellRequest) throws PowershellExecutionException {
String commandString = String.join(SYMBOL_SPLITTER, Arrays.asList(BINARY, PARAMETER_COMMAND, COMMAND_REDIRECT_WARNINGS,
powershellRequest.getCommand().getCommandString()));
ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(commandString.split(SYMBOL_SPLITTER)));
StringWriter standardOutputStringWriter = new StringWriter();
PrintWriter standardOutputPrintWriter = new PrintWriter(standardOutputStringWriter);
StringWriter errorStringWriter = new StringWriter();
PrintWriter errorPrintWriter = new PrintWriter(errorStringWriter);
try {
Process process = processBuilder.start();
List<Thread> streamConsumerThreads = Arrays.asList(
new Thread(new ThreadedStreamConsumer(process.getInputStream(), standardOutputPrintWriter)),
new Thread(new ThreadedStreamConsumer(process.getErrorStream(), errorPrintWriter))
);
for (Thread streamConsumerThread : streamConsumerThreads) {
streamConsumerThread.start();
}
int exitCode = process.waitFor();
for (Thread streamConsumerThread : streamConsumerThreads) {
streamConsumerThread.join();
}
return constructResponse(exitCode, getStringContent(standardOutputStringWriter),
getStringContent(errorStringWriter));
} catch (IOException e) {
String msg = "IOException occurred while executing powershell command : "
+ powershellRequest.getCommand();
throw new PowershellExecutionException(msg, e);
} catch (InterruptedException e) {
String msg = "Thread got interrupted while executing powershell command : "
+ powershellRequest.getCommand();
throw new PowershellExecutionException(msg, e);
}
}
private PowershellResponse constructResponse(int exitCode, String standardOutput, String errorOutput) {
JsonElement standardOutputJson = new Gson().fromJson(standardOutput, JsonElement.class);
return new PowershellResponse(standardOutputJson,
errorOutput, exitCode, exitCode == 0);
}
private String getStringContent(StringWriter stringWriter) {
return stringWriter.getBuffer().toString().trim();
}
private static class ThreadedStreamConsumer implements Runnable {
private final InputStream inputStream;
private final PrintWriter printWriter;
public ThreadedStreamConsumer(InputStream inputStream, PrintWriter printWriter) {
this.inputStream = inputStream;
this.printWriter = printWriter;
}
@Override
public void run() {
new BufferedReader(new InputStreamReader(inputStream)).
lines().forEach(printWriter::println);
}
}
}

@ -0,0 +1,36 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.os;
public class LinuxPowershell extends AbstractPowershell {
private static final String BINARY = "pwsh";
LinuxPowershell() {
super(BINARY);
}
public static LinuxPowershell getInstance() {
return LinuxPowershellHolderRegistry.INSTANCE;
}
private static class LinuxPowershellHolderRegistry {
public static LinuxPowershell INSTANCE = new LinuxPowershell();
}
}

@ -0,0 +1,36 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.os;
public class MacPowershell extends AbstractPowershell {
private static final String BINARY = "pwsh";
MacPowershell() {
super(BINARY);
}
public static MacPowershell getInstance() {
return MacPowershell.MacPowershellHolderRegistry.INSTANCE;
}
private static class MacPowershellHolderRegistry {
public static MacPowershell INSTANCE = new MacPowershell();
}
}

@ -0,0 +1,36 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.os;
public class WindowsPowershell extends AbstractPowershell {
private static final String BINARY = "powershell.exe";
WindowsPowershell() {
super(BINARY);
}
public static WindowsPowershell getInstance() {
return WindowsPowershell.WindowsPowershellHolderRegistry.INSTANCE;
}
private static class WindowsPowershellHolderRegistry {
public static WindowsPowershell INSTANCE = new WindowsPowershell();
}
}

@ -0,0 +1,113 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.cea.mgt.enforce.util.shell.parser;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.DefaultAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.EmailOutlookAccessPolicy;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Parser {
public static final String TRUE = "$true";
public static final String FALSE = "$false";
public static final String ALLOW = "ALLOW";
public static final String BLOCK = "BLOCK";
public static class COMMAND_SetActiveSyncOrganizationSettings {
public static final String COMMAND = "Set-ActiveSyncOrganizationSettings";
public static final String PARAMETER_DefaultAccessLevel = "-DefaultAccessLevel";
public static final Map<String, String> POLICY_TO_VALUE = Stream.of(new String[][]{
{DefaultAccessPolicy.ALLOW.toString(), "Allow"},
{DefaultAccessPolicy.BLOCK.toString(), "Block"},
{DefaultAccessPolicy.QUARANTINE.toString(), "Quarantine"}
}).collect(Collectors.collectingAndThen(
Collectors.toMap(entry -> entry[0], entry -> entry[1]),
Collections::<String, String>unmodifiableMap
));
}
public static class COMMAND_SetCASMailbox {
public static final String COMMAND = "Set-CASMailbox";
public static final String PARAMETER_Identity = "-Identity";
public static final String PARAMETER_ActiveSyncAllowedDeviceIDs = "-ActiveSyncAllowedDeviceIDs";
public static final String PARAMETER_ActiveSyncBlockedDeviceIDs = "-ActiveSyncBlockedDeviceIDs";
public static final String PARAMETER_EwsAllowMacOutlook = "-EwsAllowMacOutlook";
public static final String PARAMETER_MacOutlookEnabled = "-MacOutlookEnabled";
public static final String PARAMETER_OneWinNativeOutlookEnabled = "-OneWinNativeOutlookEnabled";
public static final String PARAMETER_OutlookMobileEnabled = "-OutlookMobileEnabled";
public static final String PARAMETER_OWAEnabled = "-OWAEnabled";
public static final String PARAMETER_ImapEnabled = "-ImapEnabled";
public static final String PARAMETER_PopEnabled = "-PopEnabled";
public static final Map<String, String> POLICY_TO_VALUE = Stream.of(new String[][]{
{EmailOutlookAccessPolicy.MOBILE_OUTLOOK_BLOCK.toString(), FALSE},
{EmailOutlookAccessPolicy.MAC_OUTLOOK_BLOCK.toString(), FALSE},
{EmailOutlookAccessPolicy.WINDOWS_OUTLOOK_BLOCK.toString(), FALSE},
{EmailOutlookAccessPolicy.MAC_OLD_OUTLOOK_BLOCK.toString(), FALSE},
{ALLOW, TRUE},
{BLOCK, FALSE}
}).collect(Collectors.collectingAndThen(
Collectors.toMap(entry -> entry[0], entry -> entry[1]),
Collections::<String, String>unmodifiableMap
));
}
public static class COMMAND_GetEXOMailbox {
public static final String COMMAND = "Get-EXOMailbox";
public static final String PARAMETER_ResultSize = "-ResultSize";
}
public static class COMMAND_ForEach {
public static final String COMMAND = "ForEach";
public static final String PARAMETER_Begin = "{";
public static final String PARAMETER_End = "}";
}
public static class COMMAND_WhereObject {
public static final String COMMAND = "Where-Object";
public static final String PARAMETER_Begin = "{";
public static final String PARAMETER_End = "}";
}
public static class COMMAND_GetEXOMobileDeviceStatistics {
public static final String COMMAND = "Get-EXOMobileDeviceStatistics";
public static final String PARAMETER_ActiveSync = "-ActiveSync";
public static final String PARAMETER_Mailbox = "-Mailbox";
}
public static class COMMAND_ConvertToJson {
public static final String COMMAND = "ConvertTo-Json";
public static final String PARAMETER_AsArray = "-AsArray";
}
public static class COMMAND_SelectObject {
public static final String COMMAND = "Select-Object";
}
public static class COMMAND_SetVariable {
public static final String COMMAND = "Set-Variable";
public static final String PARAMETER_Name = "-Name";
public static final String PARAMETER_Value = "-Value";
public static final String PARAMETER_PassThrough = "-PassThru";
}
}

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.parent</artifactId>
<version>5.0.38-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cea-mgt</artifactId>
<packaging>pom</packaging>
<name>Entgra IoT - CEA Management Component</name>
<description>Entgra IoT - Conditional Email Access Management Component</description>
<modules>
<module>io.entgra.device.mgt.core.cea.mgt.core</module>
<module>io.entgra.device.mgt.core.cea.mgt.common</module>
<module>io.entgra.device.mgt.core.cea.mgt.enforce</module>
</modules>
</project>

@ -460,5 +460,10 @@
<artifactId>io.entgra.device.mgt.core.apimgt.webapp.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.cea.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,58 @@
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Set;
@ApiModel(value = "AccessPolicyWrapper", description = "Access policy transferring DTO")
public class AccessPolicyWrapper {
@JsonProperty(value = "defaultAccessPolicy", required = true)
@ApiModelProperty(name = "defaultAccessPolicy", value = "Default access policy value", required = true)
private String defaultAccessPolicy;
@JsonProperty(value = "emailOutlookAccessPolicy", required = true)
@ApiModelProperty(name = "emailOutlookAccessPolicy", value = "Email outlook access policy value", required = true)
private Set<String> emailOutlookAccessPolicy;
@JsonProperty(value = "POPIMAPAccessPolicy", required = true)
@ApiModelProperty(name = "POPIMAPAccessPolicy", value = "POP/IMAP access policy value", required = true)
private String POPIMAPAccessPolicy;
@JsonProperty(value = "webOutlookAccessPolicy", required = true)
@ApiModelProperty(name = "webOutlookAccessPolicy", value = "Web outlook access policy value", required = true)
private String webOutlookAccessPolicy;
public String getDefaultAccessPolicy() {
return defaultAccessPolicy;
}
public void setDefaultAccessPolicy(String defaultAccessPolicy) {
this.defaultAccessPolicy = defaultAccessPolicy;
}
public Set<String> getEmailOutlookAccessPolicy() {
return emailOutlookAccessPolicy;
}
public void setEmailOutlookAccessPolicy(Set<String> emailOutlookAccessPolicy) {
this.emailOutlookAccessPolicy = emailOutlookAccessPolicy;
}
public String getPOPIMAPAccessPolicy() {
return POPIMAPAccessPolicy;
}
public void setPOPIMAPAccessPolicy(String POPIMAPAccessPolicy) {
this.POPIMAPAccessPolicy = POPIMAPAccessPolicy;
}
public String getWebOutlookAccessPolicy() {
return webOutlookAccessPolicy;
}
public void setWebOutlookAccessPolicy(String webOutlookAccessPolicy) {
this.webOutlookAccessPolicy = webOutlookAccessPolicy;
}
}

@ -0,0 +1,63 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "CEAPolicyWrapper", description = "CEA policy transferring DTO")
public class CEAPolicyWrapper {
@JsonProperty(value = "activeSyncServerEntries", required = true)
@ApiModelProperty(name = "activeSyncServerEntries", value = "Active sync server properties", required = true)
private ActiveSyncServer activeSyncServerEntries;
@JsonProperty(value = "conditionalAccessPolicyEntries", required = true)
@ApiModelProperty(name = "conditionalAccessPolicyEntries", value = "Definition of the access policy", required = true)
private AccessPolicyWrapper conditionalAccessPolicyEntries;
@JsonProperty(value = "gracePeriodEntries", required = true)
@ApiModelProperty(name = "gracePeriodEntries", value = "Definition of the grace period", required = true)
private GracePeriodWrapper gracePeriodEntries;
public ActiveSyncServer getActiveSyncServerEntries() {
return activeSyncServerEntries;
}
public void setActiveSyncServerEntries(ActiveSyncServer activeSyncServerEntries) {
this.activeSyncServerEntries = activeSyncServerEntries;
}
public AccessPolicyWrapper getConditionalAccessPolicyEntries() {
return conditionalAccessPolicyEntries;
}
public void setConditionalAccessPolicyEntries(AccessPolicyWrapper conditionalAccessPolicyEntries) {
this.conditionalAccessPolicyEntries = conditionalAccessPolicyEntries;
}
public GracePeriodWrapper getGracePeriodEntries() {
return gracePeriodEntries;
}
public void setGracePeriodEntries(GracePeriodWrapper gracePeriodEntries) {
this.gracePeriodEntries = gracePeriodEntries;
}
}

@ -0,0 +1,35 @@
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Set;
@ApiModel(value = "GracePeriodWrapper", description = "GracePeriod transferring DTO")
public class GracePeriodWrapper {
@JsonProperty(value = "gracePeriod", required = true)
@ApiModelProperty(name = "gracePeriod", value = "Grace period in days", required = true)
private int gracePeriod;
@JsonProperty(value = "graceAllowedPolicy", required = true)
@ApiModelProperty(name = "graceAllowedPolicy", value = "Grace allowed policy values", required = true)
private String graceAllowedPolicy;
public int getGracePeriod() {
return gracePeriod;
}
public void setGracePeriod(int gracePeriod) {
this.gracePeriod = gracePeriod;
}
public String getGraceAllowedPolicy() {
return graceAllowedPolicy;
}
public void setGraceAllowedPolicy(String graceAllowedPolicy) {
this.graceAllowedPolicy = graceAllowedPolicy;
}
}

@ -0,0 +1,336 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin;
import io.entgra.device.mgt.core.apimgt.annotations.Scope;
import io.entgra.device.mgt.core.apimgt.annotations.Scopes;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.CEAPolicyWrapper;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants;
import io.swagger.annotations.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Api(tags = {"conditional_email_access", "device_management"})
@Path("/admin/cea-policies")
@SwaggerDefinition(
info = @Info(
description = "Conditional Email Access Management",
version = "v1.0.0",
title = "CEAManagementAdminService API",
extensions = @Extension(properties = {
@ExtensionProperty(name = "name", value = "CEAManagementAdminService"),
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/admin/cea-policies"),
})
),
consumes = {MediaType.APPLICATION_JSON},
produces = {MediaType.APPLICATION_JSON},
schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS},
tags = {
@Tag(name = "device_management", description = "Device management"),
@Tag(name = "conditional_email_access", description = "Mailbox access management")
}
)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Scopes(
scopes = {
@Scope(
name = "CEA policy ui configuration view",
description = "CEA policy ui configuration view",
key = "dm:admin:cea:view",
roles = {"Internal/devicemgt-admin"},
permissions = {"/device-mgt/admin/cea/view"}
),
@Scope(
name = "Add CEA policy",
description = "Add CEA policy",
key = "dm:admin:cea:add",
roles = {"Internal/devicemgt-admin"},
permissions = {"/device-mgt/admin/cea/add"}
),
@Scope(
name = "Update CEA policy",
description = "Update CEA policy",
key = "dm:admin:cea:update",
roles = {"Internal/devicemgt-admin"},
permissions = {"/device-mgt/admin/cea/update"}
),
@Scope(
name = "Delete CEA policy",
description = "Delete CEA policy",
key = "dm:admin:cea:delete",
roles = {"Internal/devicemgt-admin"},
permissions = {"/device-mgt/admin/cea/delete"}
),
@Scope(
name = "Sync CEA policy",
description = "Sync CEA policy",
key = "dm:admin:cea:sync",
roles = {"Internal/devicemgt-admin"},
permissions = {"/device-mgt/admin/cea/sync"}
)
}
)
public interface CEAManagementAdminService {
@GET
@Path("/ui")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HttpMethod.GET,
value = "Retrieve CEA policy ui configurations",
notes = "Returns CEA policy ui configurations for supporting mail services",
tags = {"conditional_email_access", "device_management"},
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:cea:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(code = 200,
message = "OK. \n Successfully retrieve the cea ui configurations",
response = Integer.class),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of " +
"the requested resource."),
@ApiResponse(
code = 404,
message = "Configurations not found",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the group count.",
response = ErrorResponse.class)
}
)
Response getCEAPolicyUI();
@POST
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HttpMethod.POST,
value = "Add CEA policy",
notes = "Create conditional email access policy",
tags = {"conditional_email_access", "device_management"},
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:cea:add")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully created the CEA policy",
response = Response.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 409,
message = "Conflict. \n CEA policy already exists.",
response = Response.class),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while creating the resource.",
response = ErrorResponse.class)
}
)
Response createCEAPolicy(
@ApiParam(
name = "ceaPolicy",
value = "Conditional email access policy details",
required = true
)
CEAPolicyWrapper ceaPolicyWrapper);
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HttpMethod.GET,
value = "Retrieve CEA policy",
notes = "Retrieve conditional email access policy",
tags = {"conditional_email_access", "device_management"},
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:cea:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved the CEA policy",
response = Response.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 409,
message = "Conflict. \n CEA policy already exists.",
response = Response.class),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while creating the resource.",
response = ErrorResponse.class)
}
)
Response retrieveCEAPolicy();
@DELETE
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HttpMethod.DELETE,
value = "Delete CEA policy",
notes = "Delete conditional email access policy",
tags = {"conditional_email_access", "device_management"},
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:cea:delete")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully deleted the CEA policy",
response = Response.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while creating the resource.",
response = ErrorResponse.class)
}
)
Response deleteCEAPolicy();
@PUT
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HttpMethod.PUT,
value = "Update CEA policy",
notes = "Update conditional email access policy",
tags = {"conditional_email_access", "device_management"},
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:cea:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully updated the CEA policy",
response = Response.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while creating the resource.",
response = ErrorResponse.class)
}
)
Response updateCEAPolicy(@ApiParam(
name = "ceaPolicy",
value = "Conditional email access policy details",
required = true
) CEAPolicyWrapper ceaPolicyWrapper);
@GET
@Path("/syncNow")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HttpMethod.GET,
value = "Sync with active sync server",
notes = "Sync and enforce conditional access policy",
tags = {"conditional_email_access", "device_management"},
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:cea:sync")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully triggered CEA policy sync",
response = Response.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while creating the resource.",
response = ErrorResponse.class)
}
)
Response sync();
}

@ -0,0 +1,212 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin;
import io.entgra.device.mgt.core.cea.mgt.common.bean.AccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServer;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServerUIConfiguration;
import io.entgra.device.mgt.core.cea.mgt.common.bean.CEAPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.GracePeriod;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.DefaultAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.EmailOutlookAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.GraceAllowedPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.POPIMAPAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.WebOutlookAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ui.CEAPolicyUIConfiguration;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ui.ServerUIConfiguration;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAManagementException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyAlreadyExistsException;
import io.entgra.device.mgt.core.cea.mgt.common.exception.CEAPolicyNotFoundException;
import io.entgra.device.mgt.core.cea.mgt.common.service.CEAManagementService;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.AccessPolicyWrapper;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.CEAPolicyWrapper;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.GracePeriodWrapper;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.CEAManagementAdminService;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Path("/admin/cea-policies")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class CEAManagementAdminServiceImpl implements CEAManagementAdminService {
private static final Log log = LogFactory.getLog(CEAManagementAdminServiceImpl.class);
@GET
@Path("/ui")
@Override
public Response getCEAPolicyUI() {
CEAManagementService ceaManagementService = DeviceMgtAPIUtils.getCEAManagementService();
try {
CEAPolicyUIConfiguration ceaPolicyUIConfiguration = ceaManagementService.getCEAPolicyUIConfiguration();
if (ceaPolicyUIConfiguration == null) {
return Response.status(HttpStatus.SC_NOT_FOUND).entity("UI configurations not found").build();
}
return Response.status(HttpStatus.SC_OK).entity(ceaPolicyUIConfiguration).build();
} catch (CEAManagementException e) {
String msg = "Error occurred while retrieving CEA ui configs";
log.error(msg, e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@POST
@Override
public Response createCEAPolicy(CEAPolicyWrapper ceaPolicyWrapper) {
try {
RequestValidationUtil.validateCEAPolicy(ceaPolicyWrapper);
CEAManagementService ceaManagementService = DeviceMgtAPIUtils.getCEAManagementService();
CEAPolicy ceaPolicy = constructCEAPolicy(ceaPolicyWrapper);
ceaPolicy = ceaManagementService.createCEAPolicy(ceaPolicy);
return Response.status(HttpStatus.SC_CREATED).entity(ceaPolicy).build();
} catch (CEAPolicyAlreadyExistsException e) {
String msg = "CEA policy already exists for the tenant";
log.warn(msg);
return Response.status(HttpStatus.SC_CONFLICT).entity(msg).build();
} catch (CEAManagementException e) {
String msg = "Error occurred while creating CEA policy";
log.error(msg, e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
public Response retrieveCEAPolicy() {
try {
CEAManagementService ceaManagementService = DeviceMgtAPIUtils.getCEAManagementService();
CEAPolicy ceaPolicy = ceaManagementService.retrieveCEAPolicy();
if (ceaPolicy == null) {
return Response.status(HttpStatus.SC_NOT_FOUND).entity("CEA policy isn't exists in the tenant").build();
}
return Response.status(HttpStatus.SC_OK).entity(ceaPolicy).build();
} catch (CEAManagementException e) {
String msg = "Error occurred while retrieving CEA policy";
log.error(msg, e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
public Response deleteCEAPolicy() {
try {
CEAManagementService ceaManagementService = DeviceMgtAPIUtils.getCEAManagementService();
ceaManagementService.deleteCEAPolicy();
return Response.status(HttpStatus.SC_OK).build();
} catch (CEAPolicyNotFoundException e) {
String msg = "CEA policy isn't exists in the tenant";
log.warn(msg);
return Response.status(HttpStatus.SC_NOT_FOUND).entity(msg).build();
} catch (CEAManagementException e) {
String msg = "Error occurred while deleting CEA policy";
log.error(msg, e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
public Response updateCEAPolicy(CEAPolicyWrapper ceaPolicyWrapper) {
try {
RequestValidationUtil.validateCEAPolicy(ceaPolicyWrapper);
CEAManagementService ceaManagementService = DeviceMgtAPIUtils.getCEAManagementService();
CEAPolicy ceaPolicy = constructCEAPolicy(ceaPolicyWrapper);
ceaPolicy = ceaManagementService.updateCEAPolicy(ceaPolicy);
return Response.status(HttpStatus.SC_CREATED).entity(ceaPolicy).build();
} catch (CEAPolicyNotFoundException e) {
String msg = "CEA policy isn't exists in the tenant";
log.warn(msg);
return Response.status(HttpStatus.SC_NOT_FOUND).entity(msg).build();
} catch (CEAManagementException e) {
String msg = "Error occurred while updating CEA policy";
log.error(msg, e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/syncNow")
@Override
public Response sync() {
CEAManagementService ceaManagementService = DeviceMgtAPIUtils.getCEAManagementService();
try {
ceaManagementService.syncNow();
return Response.status(HttpStatus.SC_OK).build();
} catch (CEAManagementException e) {
String msg = "Error occurred while trigger syncing";
log.error(msg, e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
private CEAPolicy constructCEAPolicy(CEAPolicyWrapper ceaPolicyWrapper) {
AccessPolicyWrapper accessPolicyWrapper = ceaPolicyWrapper.getConditionalAccessPolicyEntries();
AccessPolicy accessPolicy = new AccessPolicy();
accessPolicy.setDefaultAccessPolicy(Enum.valueOf(DefaultAccessPolicy.class,
accessPolicyWrapper.getDefaultAccessPolicy()));
accessPolicy.setPOPIMAPAccessPolicy(Enum.valueOf(POPIMAPAccessPolicy.class,
accessPolicyWrapper.getPOPIMAPAccessPolicy()));
accessPolicy.setWebOutlookAccessPolicy(Enum.valueOf(WebOutlookAccessPolicy.class,
accessPolicyWrapper.getWebOutlookAccessPolicy()));
Set<EmailOutlookAccessPolicy> emailOutlookAccessPolicy = new HashSet<>();
for (String value : ceaPolicyWrapper.getConditionalAccessPolicyEntries().getEmailOutlookAccessPolicy()) {
emailOutlookAccessPolicy.add(Enum.valueOf(EmailOutlookAccessPolicy.class, value));
}
accessPolicy.setEmailOutlookAccessPolicy(emailOutlookAccessPolicy);
GracePeriodWrapper gracePeriodWrapper = ceaPolicyWrapper.getGracePeriodEntries();
GracePeriod gracePeriod = new GracePeriod();
gracePeriod.setGracePeriod(gracePeriodWrapper.getGracePeriod());
gracePeriod.setGraceAllowedPolicy(Enum.valueOf(GraceAllowedPolicy.class,
gracePeriodWrapper.getGraceAllowedPolicy()));
ActiveSyncServer activeSyncServer = ceaPolicyWrapper.getActiveSyncServerEntries();
CEAPolicy ceaPolicy = new CEAPolicy();
ceaPolicy.setAccessPolicy(accessPolicy);
ceaPolicy.setGracePeriod(gracePeriod);
ceaPolicy.setActiveSyncServer(activeSyncServer);
return ceaPolicy;
}
private List<ActiveSyncServerUIConfiguration> constructActiveSyncServerConfigurations
(List<ServerUIConfiguration> serverUIConfigurations) {
List<ActiveSyncServerUIConfiguration> activeSyncServerUIConfigurations = new ArrayList<>();
if (serverUIConfigurations == null) {
return activeSyncServerUIConfigurations;
}
for (ServerUIConfiguration serverUIConfiguration : serverUIConfigurations) {
ActiveSyncServerUIConfiguration activeSyncServerUIConfiguration = new ActiveSyncServerUIConfiguration();
activeSyncServerUIConfiguration.setName(serverUIConfiguration.getName());
activeSyncServerUIConfiguration.setKey(serverUIConfiguration.getKey());
activeSyncServerUIConfiguration.setDescription(serverUIConfiguration.getDescription());
activeSyncServerUIConfigurations.add(activeSyncServerUIConfiguration);
}
return activeSyncServerUIConfigurations;
}
}

@ -19,6 +19,15 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import io.entgra.device.mgt.core.cea.mgt.common.bean.ActiveSyncServer;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.AccessPolicyWrapper;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.CEAPolicyWrapper;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.GracePeriodWrapper;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.DefaultAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.EmailOutlookAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.GraceAllowedPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.POPIMAPAccessPolicy;
import io.entgra.device.mgt.core.cea.mgt.common.bean.enums.WebOutlookAccessPolicy;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -913,4 +922,84 @@ public class RequestValidationUtil {
"a higher value than endTimestamp").build());
}
}
public static void validateCEAPolicy(CEAPolicyWrapper ceaPolicyWrapper) {
if (ceaPolicyWrapper == null) {
String msg = "CEA policy should not be null";
log.error(msg);
throw new BadRequestException(msg);
}
validateActiveSyncServer(ceaPolicyWrapper.getActiveSyncServerEntries());
validateCEAAccessPolicy(ceaPolicyWrapper.getConditionalAccessPolicyEntries());
validateCEAGracePeriod(ceaPolicyWrapper.getGracePeriodEntries());
}
public static void validateActiveSyncServer(ActiveSyncServer activeSyncServer) {
if (activeSyncServer == null) {
String msg = "Active sync server should not be null";
log.error(msg);
throw new BadRequestException(msg);
}
if (activeSyncServer.getGatewayUrl() == null) {
String msg = "Active sync server url should not be null";
log.error(msg);
throw new BadRequestException(msg);
}
if (activeSyncServer.getKey() == null) {
String msg = "Active sync server type should not be null";
log.error(msg);
throw new BadRequestException(msg);
}
if (activeSyncServer.getClient() == null) {
String msg = "Active sync server username should not be null";
log.error(msg);
throw new BadRequestException(msg);
}
if (activeSyncServer.getSecret() == null) {
String msg = "Active sync server secret should not be null";
log.error(msg);
throw new BadRequestException(msg);
}
}
public static void validateCEAAccessPolicy(AccessPolicyWrapper accessPolicyWrapper) {
if (accessPolicyWrapper == null) {
String msg = "Access policy should not be null";
log.error(msg);
throw new BadRequestException(msg);
}
try {
Enum.valueOf(DefaultAccessPolicy.class, accessPolicyWrapper.getDefaultAccessPolicy());
Enum.valueOf(WebOutlookAccessPolicy.class, accessPolicyWrapper.getWebOutlookAccessPolicy());
Enum.valueOf(POPIMAPAccessPolicy.class, accessPolicyWrapper.getPOPIMAPAccessPolicy());
for(String value : accessPolicyWrapper.getEmailOutlookAccessPolicy()) {
Enum.valueOf(EmailOutlookAccessPolicy.class, value);
}
} catch (IllegalArgumentException | NullPointerException e) {
String msg = "Access policy contains illegal arguments";
log.error(msg);
throw new BadRequestException(msg);
}
}
public static void validateCEAGracePeriod(GracePeriodWrapper gracePeriodWrapper) {
if (gracePeriodWrapper == null) {
String msg = "Grace period should not be null";
log.error(msg);
throw new BadRequestException(msg);
}
if (gracePeriodWrapper.getGracePeriod() < 0 || gracePeriodWrapper.getGracePeriod() >
io.entgra.device.mgt.core.cea.mgt.common.util.Constants.MAX_GRACE_PERIOD_IN_DAYS) {
String msg = "Grace period should in range of 0-30 days";
log.error(msg);
throw new BadRequestException(msg);
}
try {
Enum.valueOf(GraceAllowedPolicy.class, gracePeriodWrapper.getGraceAllowedPolicy());
} catch (IllegalArgumentException | NullPointerException e) {
String msg = "Grace allowed policy contains illegal arguments";
log.error(msg);
throw new BadRequestException(msg);
}
}
}

@ -88,4 +88,8 @@ public class Constants {
public static final String TENANT = "/permission/admin/tenants";
}
public static final class CEAPolicyConstants {
CEAPolicyConstants() {};
public static final String CEAPolicyMetaKey = "_CEA_POLICY";
}
}

@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService;
import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager;
import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService;
import io.entgra.device.mgt.core.cea.mgt.common.service.CEAManagementService;
import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options;
import org.apache.axis2.java.security.SSLProtocolSocketFactory;
@ -157,11 +158,11 @@ public class DeviceMgtAPIUtils {
private static DeviceStatusManagementService deviceStatusManagementService;
private static OTPManagementService otpManagementService;
private static volatile SubscriptionManager subscriptionManager;
private static volatile ApplicationManager applicationManager;
private static volatile APIPublisherService apiPublisher;
private static volatile CEAManagementService ceaManagementService;
static {
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
@ -1230,4 +1231,19 @@ public class DeviceMgtAPIUtils {
return isPermitted;
}
public static CEAManagementService getCEAManagementService() {
if (ceaManagementService == null) {
synchronized (DeviceMgtAPIUtils.class) {
if (ceaManagementService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ceaManagementService = (CEAManagementService)
ctx.getOSGiService(CEAManagementService.class, null);
if (ceaManagementService == null) {
throw new IllegalStateException("Conditional Email Access Management Service is not initialize");
}
}
}
}
return ceaManagementService;
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save