View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.syncope.core.logic;
20  
21  import com.fasterxml.jackson.databind.JsonNode;
22  import com.fasterxml.jackson.databind.json.JsonMapper;
23  import com.fasterxml.jackson.databind.node.ArrayNode;
24  import com.fasterxml.jackson.databind.node.ObjectNode;
25  import jakarta.ws.rs.core.UriBuilder;
26  import java.io.IOException;
27  import java.lang.reflect.Method;
28  import java.net.URI;
29  import java.util.HashMap;
30  import java.util.List;
31  import java.util.Map;
32  import org.apache.syncope.common.lib.scim.SCIMConf;
33  import org.apache.syncope.common.lib.to.EntityTO;
34  import org.apache.syncope.core.logic.scim.SCIMConfManager;
35  import org.apache.syncope.core.persistence.api.dao.NotFoundException;
36  import org.apache.syncope.ext.scimv2.api.data.AuthenticationScheme;
37  import org.apache.syncope.ext.scimv2.api.data.BulkConfigurationOption;
38  import org.apache.syncope.ext.scimv2.api.data.ConfigurationOption;
39  import org.apache.syncope.ext.scimv2.api.data.FilterConfigurationOption;
40  import org.apache.syncope.ext.scimv2.api.data.Meta;
41  import org.apache.syncope.ext.scimv2.api.data.ResourceType;
42  import org.apache.syncope.ext.scimv2.api.data.SchemaExtension;
43  import org.apache.syncope.ext.scimv2.api.data.ServiceProviderConfig;
44  import org.apache.syncope.ext.scimv2.api.type.Resource;
45  import org.springframework.security.access.prepost.PreAuthorize;
46  
47  public class SCIMLogic extends AbstractLogic<EntityTO> {
48  
49      protected static final String SCHEMAS_JSON = "schemas.json";
50  
51      protected static final Object MONITOR = new Object();
52  
53      protected static final JsonMapper MAPPER = JsonMapper.builder().findAndAddModules().build();
54  
55      protected static ServiceProviderConfig SERVICE_PROVIDER_CONFIG;
56  
57      protected static ResourceType USER;
58  
59      protected static ResourceType GROUP;
60  
61      protected String schemas;
62  
63      protected final Map<String, String> schemaMap = new HashMap<>();
64  
65      protected final SCIMConfManager confManager;
66  
67      public SCIMLogic(final SCIMConfManager confManager) {
68          this.confManager = confManager;
69      }
70  
71      protected void init() {
72          try {
73              JsonNode tree = MAPPER.readTree(SCIMLogic.class.getResourceAsStream('/' + SCHEMAS_JSON));
74              if (!tree.isArray()) {
75                  throw new IOException("JSON node is not a tree");
76              }
77  
78              ArrayNode schemaArray = (ArrayNode) tree;
79              SCIMConf conf = confManager.get();
80              if (conf.getExtensionUserConf() != null) {
81                  ObjectNode extensionObject = MAPPER.createObjectNode();
82                  extensionObject.put("id", Resource.ExtensionUser.schema());
83                  extensionObject.put("name", conf.getExtensionUserConf().getName());
84                  extensionObject.put("description", conf.getExtensionUserConf().getDescription());
85                  ArrayNode attributes = MAPPER.createArrayNode();
86                  conf.getExtensionUserConf().getAttributes().forEach(scimItem -> {
87                      ObjectNode attribute = MAPPER.createObjectNode();
88                      attribute.put("name", scimItem.getIntAttrName());
89                      attribute.put("type", "string");
90                      attribute.put("multiValued", scimItem.isMultiValued());
91                      attribute.put("required", scimItem.getMandatoryCondition());
92                      attribute.put("caseExact", scimItem.isCaseExact());
93                      attribute.put("mutability", scimItem.isMutability());
94                      attribute.put("returned", scimItem.getReturned().getReturned());
95                      attribute.put("uniqueness", scimItem.isUniqueness());
96                      attributes.add(attribute);
97                  });
98                  extensionObject.putIfAbsent("attributes", attributes);
99                  extensionObject.putIfAbsent("meta", MAPPER.readTree("{\"resourceType\": \"Schema\","
100                         + "\"location\": \"/v2/Schemas/urn:ietf:params:scim:schemas:extension:syncope:2.0:User\"}"));
101                 schemaArray.add(extensionObject);
102             }
103             if (conf.getExtensionGroupConf() != null) {
104                 ObjectNode extensionObject = MAPPER.createObjectNode();
105                 extensionObject.put("id", Resource.ExtensionGroup.schema());
106                 extensionObject.put("name", conf.getExtensionGroupConf().getName());
107                 extensionObject.put("description", conf.getExtensionGroupConf().getDescription());
108                 ArrayNode attributes = MAPPER.createArrayNode();
109                 conf.getExtensionGroupConf().getAttributes().forEach(scimItem -> {
110                     ObjectNode attribute = MAPPER.createObjectNode();
111                     attribute.put("name", scimItem.getIntAttrName());
112                     attribute.put("type", "string");
113                     attribute.put("multiValued", scimItem.isMultiValued());
114                     attribute.put("required", scimItem.getMandatoryCondition());
115                     attribute.put("caseExact", scimItem.isCaseExact());
116                     attribute.put("mutability", scimItem.isMutability());
117                     attribute.put("returned", scimItem.getReturned().getReturned());
118                     attribute.put("uniqueness", scimItem.isUniqueness());
119                     attributes.add(attribute);
120                 });
121                 extensionObject.putIfAbsent("attributes", attributes);
122                 extensionObject.putIfAbsent("meta", MAPPER.readTree("{\"resourceType\": \"Schema\","
123                         + "\"location\": \"/v2/Schemas/urn:ietf:params:scim:schemas:extension:syncope:2.0:Group\"}"));
124                 schemaArray.add(extensionObject);
125             }
126             if (!conf.getExtensionAnyObjectsConf().isEmpty()) {
127                 conf.getExtensionAnyObjectsConf().forEach(confItem -> {
128                     ObjectNode extensionObject = MAPPER.createObjectNode();
129                     extensionObject.put("id",
130                             "urn:ietf:params:scim:schemas:extension:syncope:2.0:" + confItem.getType());
131                     extensionObject.put("name", confItem.getName());
132                     extensionObject.put("description", confItem.getDescription());
133                     ArrayNode attributes = MAPPER.createArrayNode();
134                     confItem.getAttributes().forEach(scimItem -> {
135                         ObjectNode attribute = MAPPER.createObjectNode();
136                         attribute.put("name", scimItem.getIntAttrName());
137                         attribute.put("type", "string");
138                         attribute.put("multiValued", scimItem.isMultiValued());
139                         attribute.put("required", scimItem.getMandatoryCondition());
140                         attribute.put("caseExact", scimItem.isCaseExact());
141                         attribute.put("mutability", scimItem.isMutability());
142                         attribute.put("returned", scimItem.getReturned().getReturned());
143                         attribute.put("uniqueness", scimItem.isUniqueness());
144                         attributes.add(attribute);
145                     });
146                     extensionObject.putIfAbsent("attributes", attributes);
147                     try {
148                         extensionObject.putIfAbsent("meta", MAPPER.readTree("{\"resourceType\": \"Schema\","
149                                 + "\"location\": \"/v2/Schemas/urn:ietf:params:scim:schemas:extension:syncope:2.0:"
150                                 + confItem.getType() + "}\""));
151                     } catch (IOException e) {
152                         LOG.error("Could not parse the default schema definitions", e);
153                     }
154                     schemaArray.add(extensionObject);
155                 });
156             }
157             schemas = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(tree);
158 
159             schemaMap.clear();
160             for (JsonNode schema : schemaArray) {
161                 schemaMap.put(schema.get("id").asText(), MAPPER.writeValueAsString(schema));
162             }
163         } catch (IOException e) {
164             LOG.error("Could not parse the default schema definitions", e);
165         }
166     }
167 
168     @PreAuthorize("isAuthenticated()")
169     public ServiceProviderConfig serviceProviderConfig(final UriBuilder uriBuilder) {
170         init();
171 
172         synchronized (MONITOR) {
173             if (SERVICE_PROVIDER_CONFIG == null) {
174                 SCIMConf conf = confManager.get();
175 
176                 SERVICE_PROVIDER_CONFIG = new ServiceProviderConfig(
177                         new Meta(
178                                 Resource.ServiceProviderConfig.name(),
179                                 conf.getGeneralConf().getCreationDate(),
180                                 conf.getGeneralConf().getLastChangeDate(),
181                                 conf.getGeneralConf().getETagValue(),
182                                 uriBuilder.build().toASCIIString()),
183                         new ConfigurationOption(true),
184                         new BulkConfigurationOption(
185                                 false,
186                                 conf.getGeneralConf().getBulkMaxOperations(),
187                                 conf.getGeneralConf().getBulkMaxPayloadSize()),
188                         new FilterConfigurationOption(true, conf.getGeneralConf().getFilterMaxResults()),
189                         new ConfigurationOption(true),
190                         new ConfigurationOption(true),
191                         new ConfigurationOption(true));
192                 SERVICE_PROVIDER_CONFIG.getAuthenticationSchemes().add(new AuthenticationScheme(
193                         "JSON Web Token",
194                         "Apache Syncope JWT authentication",
195                         URI.create("http://www.rfc-editor.org/info/rfc6750"),
196                         URI.create("https://syncope.apache.org/docs/"
197                                 + "reference-guide.html#rest-authentication-and-authorization"),
198                         "oauthbearertoken",
199                         true));
200                 SERVICE_PROVIDER_CONFIG.getAuthenticationSchemes().add(new AuthenticationScheme(
201                         "HTTP Basic",
202                         "Apache Syncope HTTP Basic authentication",
203                         URI.create("http://www.rfc-editor.org/info/rfc2617"),
204                         URI.create("https://syncope.apache.org/docs/"
205                                 + "reference-guide.html#rest-authentication-and-authorization"),
206                         "httpbasic",
207                         false));
208             }
209         }
210         return SERVICE_PROVIDER_CONFIG;
211     }
212 
213     @PreAuthorize("isAuthenticated()")
214     public List<ResourceType> resourceTypes(final UriBuilder uriBuilder) {
215         synchronized (MONITOR) {
216             String uri = uriBuilder.build().toASCIIString();
217             if (USER == null) {
218                 USER = new ResourceType("User", "User", "/Users", "User Account", Resource.User.schema(),
219                         new Meta(Resource.ResourceType.name(), null, null, null, uri + "User"));
220                 USER.getSchemaExtensions().add(new SchemaExtension(Resource.EnterpriseUser.schema(), true));
221             }
222             if (GROUP == null) {
223                 GROUP = new ResourceType("Group", "Group", "/Groups", "Group", Resource.Group.schema(),
224                         new Meta(Resource.ResourceType.name(), null, null, null, uri + "Group"));
225             }
226         }
227 
228         return List.of(USER, GROUP);
229     }
230 
231     @PreAuthorize("isAuthenticated()")
232     public ResourceType resourceType(final UriBuilder uriBuilder, final String type) {
233         if (Resource.User.name().equals(type)) {
234             resourceTypes(uriBuilder);
235             return USER;
236         } else if (Resource.Group.name().equals(type)) {
237             resourceTypes(uriBuilder);
238             return GROUP;
239         } else {
240             throw new IllegalArgumentException("Unsupported resource type: " + type);
241         }
242     }
243 
244     @PreAuthorize("isAuthenticated()")
245     public String schemas() {
246         init();
247 
248         return schemas;
249     }
250 
251     @PreAuthorize("isAuthenticated()")
252     public String schema(final String schema) {
253         init();
254 
255         String found = schemaMap.get(schema);
256         if (found == null) {
257             throw new NotFoundException("Schema " + schema + " not found");
258         }
259 
260         return found;
261     }
262 
263     @Override
264     protected EntityTO resolveReference(final Method method, final Object... args)
265             throws UnresolvedReferenceException {
266 
267         throw new UnresolvedReferenceException();
268     }
269 }