-
Notifications
You must be signed in to change notification settings - Fork 276
/
Copy pathAdminResourceImpl.java
504 lines (452 loc) · 20.4 KB
/
AdminResourceImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
package io.apicurio.registry.rest.v2;
import io.apicurio.common.apps.config.Dynamic;
import io.apicurio.common.apps.config.DynamicConfigPropertyDef;
import io.apicurio.common.apps.config.DynamicConfigPropertyDto;
import io.apicurio.common.apps.config.DynamicConfigPropertyIndex;
import io.apicurio.common.apps.config.Info;
import io.apicurio.common.apps.logging.Logged;
import io.apicurio.common.apps.logging.audit.Audited;
import io.apicurio.registry.auth.Authorized;
import io.apicurio.registry.auth.AuthorizedLevel;
import io.apicurio.registry.auth.AuthorizedStyle;
import io.apicurio.registry.auth.RoleBasedAccessApiOperation;
import io.apicurio.registry.metrics.health.liveness.ResponseErrorLivenessCheck;
import io.apicurio.registry.metrics.health.readiness.ResponseTimeoutReadinessCheck;
import io.apicurio.registry.rest.MissingRequiredParameterException;
import io.apicurio.registry.rest.v2.beans.ArtifactTypeInfo;
import io.apicurio.registry.rest.v2.beans.ConfigurationProperty;
import io.apicurio.registry.rest.v2.beans.DownloadRef;
import io.apicurio.registry.rest.v2.beans.RoleMapping;
import io.apicurio.registry.rest.v2.beans.Rule;
import io.apicurio.registry.rest.v2.beans.UpdateConfigurationProperty;
import io.apicurio.registry.rest.v2.beans.UpdateRole;
import io.apicurio.registry.rest.v2.shared.DataExporter;
import io.apicurio.registry.rules.DefaultRuleDeletionException;
import io.apicurio.registry.rules.RulesProperties;
import io.apicurio.registry.storage.RegistryStorage;
import io.apicurio.registry.storage.dto.DownloadContextDto;
import io.apicurio.registry.storage.dto.DownloadContextType;
import io.apicurio.registry.storage.dto.RoleMappingDto;
import io.apicurio.registry.storage.dto.RuleConfigurationDto;
import io.apicurio.registry.storage.error.ConfigPropertyNotFoundException;
import io.apicurio.registry.storage.error.InvalidPropertyValueException;
import io.apicurio.registry.storage.error.RuleNotFoundException;
import io.apicurio.registry.storage.impexp.EntityInputStream;
import io.apicurio.registry.types.Current;
import io.apicurio.registry.types.RoleType;
import io.apicurio.registry.types.RuleType;
import io.apicurio.registry.types.provider.ArtifactTypeUtilProviderFactory;
import io.apicurio.registry.utils.impexp.Entity;
import io.apicurio.registry.utils.impexp.EntityReader;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.interceptor.Interceptors;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipInputStream;
import static io.apicurio.common.apps.logging.audit.AuditingConstants.KEY_FOR_BROWSER;
import static io.apicurio.common.apps.logging.audit.AuditingConstants.KEY_NAME;
import static io.apicurio.common.apps.logging.audit.AuditingConstants.KEY_PRINCIPAL_ID;
import static io.apicurio.common.apps.logging.audit.AuditingConstants.KEY_ROLE_MAPPING;
import static io.apicurio.common.apps.logging.audit.AuditingConstants.KEY_RULE;
import static io.apicurio.common.apps.logging.audit.AuditingConstants.KEY_RULE_TYPE;
import static io.apicurio.common.apps.logging.audit.AuditingConstants.KEY_UPDATE_ROLE;
import static io.apicurio.registry.utils.DtoUtil.appAuthPropertyToRegistry;
import static io.apicurio.registry.utils.DtoUtil.registryAuthPropertyToApp;
@ApplicationScoped
@Interceptors({ ResponseErrorLivenessCheck.class, ResponseTimeoutReadinessCheck.class })
@Logged
public class AdminResourceImpl implements AdminResource {
@Inject
Logger log;
@Inject
@Current
RegistryStorage storage;
@Inject
RulesProperties rulesProperties;
@Inject
DynamicConfigPropertyIndex dynamicPropertyIndex;
@Inject
ArtifactTypeUtilProviderFactory factory;
@Inject
Config config;
@Inject
DataExporter exporter;
@Context
HttpServletRequest request;
@Dynamic(label = "Download link expiry", description = "The number of seconds that a generated link to a .zip download file is active before expiring.")
@ConfigProperty(name = "apicurio.download.href.ttl.seconds", defaultValue = "30")
@Info(category = "download", description = "Download link expiry", availableSince = "2.1.2.Final")
Supplier<Long> downloadHrefTtl;
private static final void requireParameter(String parameterName, Object parameterValue) {
if (parameterValue == null) {
throw new MissingRequiredParameterException(parameterName);
}
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#listArtifactTypes()
*/
@Override
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Read)
public List<ArtifactTypeInfo> listArtifactTypes() {
return factory.getAllArtifactTypes().stream().map(t -> {
ArtifactTypeInfo ati = new ArtifactTypeInfo();
ati.setName(t);
return ati;
}).collect(Collectors.toList());
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#listGlobalRules()
*/
@Override
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Read)
public List<RuleType> listGlobalRules() {
List<RuleType> rules = storage.getGlobalRules();
Set<RuleType> defaultRules = rulesProperties.getDefaultGlobalRules();
return Stream.concat(rules.stream(), defaultRules.stream()).collect(Collectors.toSet()).stream()
.sorted().collect(Collectors.toList());
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#createGlobalRule(io.apicurio.registry.rest.v2.beans.Rule)
*/
@Override
@Audited(extractParameters = { "0", KEY_RULE })
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
public void createGlobalRule(Rule data) {
RuleType type = data.getType();
requireParameter("type", type);
if (data.getConfig() == null || data.getConfig().isEmpty()) {
throw new MissingRequiredParameterException("Config");
}
RuleConfigurationDto configDto = new RuleConfigurationDto();
configDto.setConfiguration(data.getConfig());
storage.createGlobalRule(data.getType(), configDto);
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#deleteAllGlobalRules()
*/
@Override
@Audited
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
public void deleteAllGlobalRules() {
storage.deleteGlobalRules();
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#getGlobalRuleConfig(io.apicurio.registry.types.RuleType)
*/
@Override
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Read)
public Rule getGlobalRuleConfig(RuleType rule) {
RuleConfigurationDto dto;
try {
dto = storage.getGlobalRule(rule);
} catch (RuleNotFoundException ruleNotFoundException) {
// Check if the rule exists in the default global rules
dto = rulesProperties.getDefaultGlobalRuleConfiguration(rule);
if (dto == null) {
throw ruleNotFoundException;
}
}
Rule ruleBean = new Rule();
ruleBean.setType(rule);
ruleBean.setConfig(dto.getConfiguration());
return ruleBean;
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#updateGlobalRuleConfig(io.apicurio.registry.types.RuleType,
* io.apicurio.registry.rest.v2.beans.Rule)
*/
@Override
@Audited(extractParameters = { "0", KEY_RULE_TYPE, "1", KEY_RULE })
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
public Rule updateGlobalRuleConfig(RuleType rule, Rule data) {
RuleConfigurationDto configDto = new RuleConfigurationDto();
configDto.setConfiguration(data.getConfig());
try {
storage.updateGlobalRule(rule, configDto);
} catch (RuleNotFoundException ruleNotFoundException) {
// This global rule doesn't exist in artifactStore - if the rule exists in the default
// global rules, override the default by creating a new global rule
if (rulesProperties.isDefaultGlobalRuleConfigured(rule)) {
storage.createGlobalRule(rule, configDto);
} else {
throw ruleNotFoundException;
}
}
Rule ruleBean = new Rule();
ruleBean.setType(rule);
ruleBean.setConfig(data.getConfig());
return ruleBean;
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#deleteGlobalRule(io.apicurio.registry.types.RuleType)
*/
@Override
@Audited(extractParameters = { "0", KEY_RULE_TYPE })
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
public void deleteGlobalRule(RuleType rule) {
try {
storage.deleteGlobalRule(rule);
} catch (RuleNotFoundException ruleNotFoundException) {
// This global rule doesn't exist in artifactStore - if the rule exists in
// the default global rules, return a DefaultRuleDeletionException.
// Otherwise, return the RuleNotFoundException
if (rulesProperties.isDefaultGlobalRuleConfigured(rule)) {
throw new DefaultRuleDeletionException(rule);
} else {
throw ruleNotFoundException;
}
}
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#importData(Boolean, Boolean, java.io.InputStream)
*/
@Override
@Audited
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
public void importData(Boolean xRegistryPreserveGlobalId, Boolean xRegistryPreserveContentId,
InputStream data) {
final ZipInputStream zip = new ZipInputStream(data, StandardCharsets.UTF_8);
final EntityReader reader = new EntityReader(zip);
EntityInputStream stream = new EntityInputStream() {
@Override
public Entity nextEntity() throws IOException {
try {
return reader.readEntity();
} catch (Exception e) {
log.error("Error reading data from import ZIP file.", e);
return null;
}
}
@Override
public void close() throws IOException {
zip.close();
}
};
this.storage.importData(stream, isNullOrTrue(xRegistryPreserveGlobalId),
isNullOrTrue(xRegistryPreserveContentId));
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#exportData(java.lang.Boolean)
*/
@Override
@Audited(extractParameters = { "0", KEY_FOR_BROWSER })
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
public Response exportData(Boolean forBrowser) {
String acceptHeader = request.getHeader("Accept");
if (Boolean.TRUE.equals(forBrowser) || MediaType.APPLICATION_JSON.equals(acceptHeader)) {
long expires = System.currentTimeMillis() + (downloadHrefTtl.get() * 1000);
DownloadContextDto downloadCtx = DownloadContextDto.builder().type(DownloadContextType.EXPORT)
.expires(expires).build();
String downloadId = storage.createDownload(downloadCtx);
String downloadHref = createDownloadHref(downloadId);
DownloadRef downloadRef = new DownloadRef();
downloadRef.setDownloadId(downloadId);
downloadRef.setHref(downloadHref);
return Response.ok(downloadRef).type(MediaType.APPLICATION_JSON_TYPE).build();
} else {
return exporter.exportData();
}
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#createRoleMapping(io.apicurio.registry.rest.v2.beans.RoleMapping)
*/
@Override
@Audited(extractParameters = { "0", KEY_ROLE_MAPPING })
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
@RoleBasedAccessApiOperation
public void createRoleMapping(RoleMapping data) {
storage.createRoleMapping(data.getPrincipalId(), data.getRole().name(), data.getPrincipalName());
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#listRoleMappings()
*/
@Override
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
@RoleBasedAccessApiOperation
public List<RoleMapping> listRoleMappings() {
List<RoleMappingDto> mappings = storage.getRoleMappings();
return mappings.stream().map(dto -> {
return dtoToRoleMapping(dto);
}).collect(Collectors.toList());
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#getRoleMapping(java.lang.String)
*/
@Override
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
@RoleBasedAccessApiOperation
public RoleMapping getRoleMapping(String principalId) {
RoleMappingDto dto = storage.getRoleMapping(principalId);
return dtoToRoleMapping(dto);
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#updateRoleMapping (java.lang.String,
* io.apicurio.registry.rest.v2.beans.Role)
*/
@Override
@Audited(extractParameters = { "0", KEY_PRINCIPAL_ID, "1", KEY_UPDATE_ROLE })
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
@RoleBasedAccessApiOperation
public void updateRoleMapping(String principalId, UpdateRole data) {
requireParameter("principalId", principalId);
requireParameter("role", data.getRole());
storage.updateRoleMapping(principalId, data.getRole().name());
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#deleteRoleMapping(java.lang.String)
*/
@Override
@Audited(extractParameters = { "0", KEY_PRINCIPAL_ID })
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
@RoleBasedAccessApiOperation
public void deleteRoleMapping(String principalId) {
storage.deleteRoleMapping(principalId);
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#listConfigProperties()
*/
@Override
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
public List<ConfigurationProperty> listConfigProperties() {
// Query the DB for the set of configured properties.
List<DynamicConfigPropertyDto> props = storage.getConfigProperties();
// Index the stored properties for easy lookup
Map<String, DynamicConfigPropertyDto> propsI = new HashMap<>();
props.forEach(dto -> propsI.put(dto.getName(), dto));
// Return value is the set of all dynamic config properties, with either configured or default values
// (depending
// on whether the value is actually configured and stored in the DB or not).
return dynamicPropertyIndex.getAcceptedPropertyNames().stream()
.sorted((pname1, pname2) -> pname1.compareTo(pname2))
.map(pname -> propsI.containsKey(pname)
? dtoToConfigurationProperty(dynamicPropertyIndex.getProperty(pname), propsI.get(pname))
: defToConfigurationProperty(dynamicPropertyIndex.getProperty(pname)))
.collect(Collectors.toList());
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#getConfigProperty(java.lang.String)
*/
@Override
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
public ConfigurationProperty getConfigProperty(String propertyName) {
// Ensure that the property is a valid dynamic config property.
DynamicConfigPropertyDef def = resolveConfigProperty(propertyName);
DynamicConfigPropertyDto dto = storage.getRawConfigProperty(propertyName);
if (dto == null) {
return defToConfigurationProperty(def);
} else {
return dtoToConfigurationProperty(def, dto);
}
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#updateConfigProperty(java.lang.String,
* io.apicurio.registry.rest.v2.beans.UpdateConfigurationProperty)
*/
@Override
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
public void updateConfigProperty(String propertyName, UpdateConfigurationProperty data) {
DynamicConfigPropertyDef propertyDef = resolveConfigProperty(propertyName);
validateConfigPropertyValue(propertyDef, data.getValue());
DynamicConfigPropertyDto dto = new DynamicConfigPropertyDto();
dto.setName(propertyName);
dto.setValue(data.getValue());
storage.setConfigProperty(dto);
}
/**
* @see io.apicurio.registry.rest.v2.AdminResource#resetConfigProperty(java.lang.String)
*/
@Override
@Authorized(style = AuthorizedStyle.None, level = AuthorizedLevel.Admin)
@Audited(extractParameters = { "0", KEY_NAME })
public void resetConfigProperty(String propertyName) {
// Check if the config property exists.
resolveConfigProperty(propertyName);
// Delete it in the storage.
storage.deleteConfigProperty(propertyName);
}
private static RoleMapping dtoToRoleMapping(RoleMappingDto dto) {
RoleMapping mapping = new RoleMapping();
mapping.setPrincipalId(dto.getPrincipalId());
mapping.setRole(RoleType.valueOf(dto.getRole()));
mapping.setPrincipalName(dto.getPrincipalName());
return mapping;
}
private static boolean isNullOrTrue(Boolean value) {
return value == null || value;
}
private String createDownloadHref(String downloadId) {
return "/apis/registry/v2/downloads/" + downloadId;
}
private static ConfigurationProperty dtoToConfigurationProperty(DynamicConfigPropertyDef def,
DynamicConfigPropertyDto dto) {
ConfigurationProperty rval = new ConfigurationProperty();
rval.setName(def.getName());
rval.setValue(dto.getValue());
rval.setType(def.getType().getName());
rval.setLabel(def.getLabel());
rval.setDescription(def.getDescription());
return rval;
}
private ConfigurationProperty defToConfigurationProperty(DynamicConfigPropertyDef def) {
String propertyValue = config.getOptionalValue(def.getName(), String.class)
.orElse(def.getDefaultValue());
ConfigurationProperty rval = new ConfigurationProperty();
rval.setName(appAuthPropertyToRegistry(def.getName()));
rval.setValue(propertyValue);
rval.setType(def.getType().getName());
rval.setLabel(def.getLabel());
rval.setDescription(def.getDescription());
return rval;
}
/**
* Lookup the dynamic configuration property being set. Ensure that it exists (throws a
* {@link NotFoundException} if it does not.
*
* @param propertyName the name of the dynamic property
* @return the dynamic config property definition
*/
private DynamicConfigPropertyDef resolveConfigProperty(String propertyName) {
DynamicConfigPropertyDef property = dynamicPropertyIndex.getProperty(propertyName);
if (property == null) {
propertyName = registryAuthPropertyToApp(propertyName);
}
// If registry property cannot be found, try with app property
property = dynamicPropertyIndex.getProperty(propertyName);
if (property == null) {
throw new ConfigPropertyNotFoundException(propertyName);
}
if (!dynamicPropertyIndex.isAccepted(propertyName)) {
throw new ConfigPropertyNotFoundException(propertyName);
}
return property;
}
/**
* Ensure that the value being set on the given property is value for the property type. For example, this
* should fail
*
* @param propertyDef the dynamic config property definition
* @param value the config property value
*/
private void validateConfigPropertyValue(DynamicConfigPropertyDef propertyDef, String value) {
if (!propertyDef.isValidValue(value)) {
throw new InvalidPropertyValueException(
"Invalid dynamic configuration property value for: " + propertyDef.getName());
}
}
}