forked from candlepin/candlepin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConsumerResourceCreationTest.java
495 lines (422 loc) · 19.1 KB
/
ConsumerResourceCreationTest.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
/**
* Copyright (c) 2009 - 2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.resource;
import static org.mockito.Mockito.*;
import org.candlepin.audit.EventFactory;
import org.candlepin.audit.EventSink;
import org.candlepin.auth.Access;
import org.candlepin.auth.NoAuthPrincipal;
import org.candlepin.auth.Principal;
import org.candlepin.auth.TrustedUserPrincipal;
import org.candlepin.auth.UserPrincipal;
import org.candlepin.auth.permissions.OwnerPermission;
import org.candlepin.auth.permissions.Permission;
import org.candlepin.auth.permissions.PermissionFactory.PermissionType;
import org.candlepin.common.config.Configuration;
import org.candlepin.common.config.MapConfiguration;
import org.candlepin.common.exceptions.BadRequestException;
import org.candlepin.common.exceptions.ForbiddenException;
import org.candlepin.config.ConfigProperties;
import org.candlepin.dto.ModelTranslator;
import org.candlepin.dto.StandardTranslator;
import org.candlepin.dto.api.v1.ConsumerDTO;
import org.candlepin.dto.api.v1.ConsumerTypeDTO;
import org.candlepin.model.CertificateSerial;
import org.candlepin.model.Consumer;
import org.candlepin.model.ConsumerContentOverrideCurator;
import org.candlepin.model.ConsumerCurator;
import org.candlepin.model.ConsumerType;
import org.candlepin.model.ConsumerType.ConsumerTypeEnum;
import org.candlepin.model.ConsumerTypeCurator;
import org.candlepin.model.DeletedConsumerCurator;
import org.candlepin.model.EnvironmentCurator;
import org.candlepin.model.IdentityCertificate;
import org.candlepin.model.Owner;
import org.candlepin.model.OwnerCurator;
import org.candlepin.model.PermissionBlueprint;
import org.candlepin.model.Role;
import org.candlepin.model.User;
import org.candlepin.model.activationkeys.ActivationKey;
import org.candlepin.model.activationkeys.ActivationKeyCurator;
import org.candlepin.policy.SystemPurposeComplianceRules;
import org.candlepin.policy.js.compliance.ComplianceRules;
import org.candlepin.policy.js.compliance.ComplianceStatus;
import org.candlepin.resource.util.ConsumerBindUtil;
import org.candlepin.resource.util.ConsumerEnricher;
import org.candlepin.resource.util.GuestMigration;
import org.candlepin.service.IdentityCertServiceAdapter;
import org.candlepin.service.OwnerServiceAdapter;
import org.candlepin.service.SubscriptionServiceAdapter;
import org.candlepin.service.UserServiceAdapter;
import org.candlepin.test.TestUtil;
import org.candlepin.util.FactValidator;
import org.candlepin.util.ServiceLevelValidator;
import com.google.inject.util.Providers;
import org.apache.commons.lang.StringUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.inject.Provider;
/**
*
*/
@RunWith(MockitoJUnitRunner.class)
/*
* FIXME: this seems to only test creating
* system consumers.
*/
public class ConsumerResourceCreationTest {
private static Logger log = LoggerFactory.getLogger(ConsumerResourceCreationTest.class);
private static final String USER = "testuser";
@Mock protected UserServiceAdapter userService;
@Mock protected IdentityCertServiceAdapter idCertService;
@Mock protected SubscriptionServiceAdapter subscriptionService;
@Mock protected OwnerServiceAdapter ownerService;
@Mock protected ConsumerCurator consumerCurator;
@Mock protected ConsumerTypeCurator consumerTypeCurator;
@Mock protected OwnerCurator ownerCurator;
@Mock protected EventSink sink;
@Mock protected EventFactory factory;
@Mock protected ActivationKeyCurator activationKeyCurator;
@Mock protected ComplianceRules complianceRules;
@Mock protected SystemPurposeComplianceRules systemPurposeComplianceRules;
@Mock protected DeletedConsumerCurator deletedConsumerCurator;
@Mock protected ConsumerContentOverrideCurator consumerContentOverrideCurator;
@Mock protected ServiceLevelValidator serviceLevelValidator;
@Mock protected ConsumerBindUtil consumerBindUtil;
@Mock protected ConsumerEnricher consumerEnricher;
@Mock protected EnvironmentCurator environmentCurator;
protected ModelTranslator modelTranslator;
private I18n i18n;
private Provider<I18n> i18nProvider = () -> i18n;
private ConsumerResource resource;
private ConsumerTypeDTO systemDto;
private ConsumerType system;
protected Configuration config;
protected Owner owner;
protected Role role;
private User user;
private GuestMigration testMigration;
private Provider<GuestMigration> migrationProvider;
@Before
public void init() throws Exception {
this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK);
this.modelTranslator = new StandardTranslator(this.consumerTypeCurator, this.environmentCurator,
this.ownerCurator);
testMigration = new GuestMigration(consumerCurator);
migrationProvider = Providers.of(testMigration);
this.config = initConfig();
this.resource = new ConsumerResource(
this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, this.ownerService,
null, this.idCertService, null, this.i18n, this.sink, null, null, this.userService, null,
null, this.ownerCurator, this.activationKeyCurator, null, this.complianceRules,
this.systemPurposeComplianceRules, this.deletedConsumerCurator, null, null, this.config, null,
null, null, this.consumerBindUtil, null, null, new FactValidator(this.config, this.i18nProvider),
null, consumerEnricher, migrationProvider, modelTranslator);
this.system = this.initConsumerType();
this.mockConsumerType(this.system);
this.systemDto = this.modelTranslator.translate(this.system, ConsumerTypeDTO.class);
owner = new Owner("test_owner");
owner.setId(TestUtil.randomString());
user = new User(USER, "");
PermissionBlueprint p = new PermissionBlueprint(PermissionType.OWNER, owner, Access.ALL);
role = new Role();
role.addPermission(p);
role.addUser(user);
when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return invocation.getArguments()[0];
}
});
when(consumerCurator.create(any(Consumer.class), any(Boolean.class))).thenAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return invocation.getArguments()[0];
}
});
when(userService.findByLogin(USER)).thenReturn(user);
IdentityCertificate cert = new IdentityCertificate();
cert.setKey("testKey");
cert.setCert("testCert");
cert.setId("testId");
cert.setSerial(new CertificateSerial(new Date()));
when(idCertService.generateIdentityCert(any(Consumer.class))).thenReturn(cert);
when(ownerCurator.getByKey(owner.getKey())).thenReturn(owner);
when(complianceRules.getStatus(
any(Consumer.class), any(Date.class), any(Boolean.class), any(Boolean.class)))
.thenReturn(new ComplianceStatus(new Date()));
}
public ConsumerType initConsumerType() {
return new ConsumerType(ConsumerType.ConsumerTypeEnum.SYSTEM);
}
protected ConsumerType mockConsumerType(ConsumerType ctype) {
if (ctype != null) {
// Ensure the type has an ID
if (ctype.getId() == null) {
ctype.setId("test-ctype-" + ctype.getLabel() + "-" + TestUtil.randomInt());
}
when(consumerTypeCurator.getByLabel(eq(ctype.getLabel()))).thenReturn(ctype);
when(consumerTypeCurator.getByLabel(eq(ctype.getLabel()), anyBoolean())).thenReturn(ctype);
when(consumerTypeCurator.get(eq(ctype.getId()))).thenReturn(ctype);
doAnswer(new Answer<ConsumerType>() {
@Override
public ConsumerType answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Consumer consumer = (Consumer) args[0];
ConsumerTypeCurator curator = (ConsumerTypeCurator) invocation.getMock();
ConsumerType ctype = null;
if (consumer == null || consumer.getTypeId() == null) {
throw new IllegalArgumentException("consumer is null or lacks a type ID");
}
ctype = curator.get(consumer.getTypeId());
if (ctype == null) {
throw new IllegalStateException("No such consumer type: " + consumer.getTypeId());
}
return ctype;
}
}).when(consumerTypeCurator).getConsumerType(any(Consumer.class));
}
return ctype;
}
private static class ConfigForTesting extends MapConfiguration {
@SuppressWarnings("serial")
public ConfigForTesting() {
super(new HashMap<String, String>() {
{
this.put(ConfigProperties.CONSUMER_SYSTEM_NAME_PATTERN,
"[\\#\\?\\'\\`\\!@{}()\\[\\]\\?&\\w-\\.]+");
this.put(ConfigProperties.CONSUMER_PERSON_NAME_PATTERN,
"[\\#\\?\\'\\`\\!@{}()\\[\\]\\?&\\w-\\.]+");
}
});
}
}
public Configuration initConfig() {
Configuration config = new ConfigForTesting();
config.setProperty(ConfigProperties.USE_SYSTEM_UUID_FOR_MATCHING, "true");
return config;
}
protected ConsumerDTO createConsumer(String consumerName) {
Collection<Permission> perms = new HashSet<>();
perms.add(new OwnerPermission(owner, Access.ALL));
Principal principal = new UserPrincipal(USER, perms, false);
List<String> empty = Collections.emptyList();
return createConsumer(consumerName, principal, empty);
}
private ConsumerDTO createConsumer(String consumerName, Principal principal,
List<String> activationKeys) {
ConsumerDTO consumer = TestUtil.createConsumerDTO(consumerName, null, null, systemDto);
return this.resource.create(consumer, principal, USER, owner.getKey(), null, true);
}
@Test
public void acceptedConsumerName() {
Assert.assertNotNull(createConsumer("test_user"));
}
@Test
public void camelCaseName() {
Assert.assertNotNull(createConsumer("ConsumerTest32953"));
}
@Test
public void startsWithUnderscore() {
Assert.assertNotNull(createConsumer("__init__"));
}
@Test
public void startsWithDash() {
Assert.assertNotNull(createConsumer("-dash"));
}
@Test
public void containsNumbers() {
Assert.assertNotNull(createConsumer("testmachine99"));
}
@Test
public void startsWithNumbers() {
Assert.assertNotNull(createConsumer("001test7"));
}
@Test
public void containsPeriods() {
Assert.assertNotNull(createConsumer("test-system.resource.net"));
}
@Test
public void containsUserServiceChars() {
Assert.assertNotNull(createConsumer("{bob}'s_b!g_#boi.`?uestlove!x"));
}
// These fail with the default consumer name pattern
@Test(expected = BadRequestException.class)
public void containsMultibyteKorean() {
createConsumer("서브스크립션 ");
}
@Test(expected = BadRequestException.class)
public void containsMultibyteOriya() {
createConsumer("ପରିବେଶ");
}
@Test(expected = BadRequestException.class)
public void startsWithPound() {
createConsumer("#pound");
}
@Test(expected = BadRequestException.class)
public void emptyConsumerName() {
createConsumer("");
}
@Test(expected = BadRequestException.class)
public void nullConsumerName() {
createConsumer(null);
}
@Test(expected = BadRequestException.class)
public void startsWithBadCharacter() {
createConsumer("#foo");
}
@Test(expected = BadRequestException.class)
public void containsBadCharacter() {
createConsumer("bar$%camp");
}
@Test(expected = ForbiddenException.class)
public void authRequired() {
Principal p = new NoAuthPrincipal();
List<String> empty = Collections.emptyList();
createConsumer("sys.example.com", p, empty);
}
private List<String> mockActivationKeys() {
ActivationKey key1 = new ActivationKey("key1", owner);
when(activationKeyCurator.getByKeyName(owner, "key1")).thenReturn(key1);
List<String> keys = new LinkedList<>();
keys.add(key1.getName());
return keys;
}
private String createKeysString(List<String> activationKeys) {
// Allow empty string through because we accept it for ",foo" etc.
if (!activationKeys.isEmpty()) {
return StringUtils.join(activationKeys, ',');
}
return null;
}
@Test
public void oauthRegistrationSupported() {
// Should be able to register successfully with as a trusted user principal:
Principal p = new TrustedUserPrincipal("anyuser");
ConsumerDTO consumer = TestUtil.createConsumerDTO("sys.example.com", null, null, systemDto);
resource.create(consumer, p, null, owner.getKey(), null, true);
}
@Test
public void registerWithKeys() {
// No auth should be required for registering with keys:
Principal p = new NoAuthPrincipal();
List<String> keys = mockActivationKeys();
ConsumerDTO consumer = TestUtil.createConsumerDTO("sys.example.com", null, null, systemDto);
resource.create(consumer, p, null, owner.getKey(), createKeysString(keys), true);
for (String keyName : keys) {
verify(activationKeyCurator).getByKeyName(owner, keyName);
}
}
@Test
public void registerFailsWithKeyWhenAutobindOnKeyAndDisabledOnOwner() {
ConsumerType ctype = new ConsumerType(ConsumerTypeEnum.SYSTEM);
ConsumerTypeDTO ctypeDTO = this.modelTranslator.translate(ctype, ConsumerTypeDTO.class);
this.mockConsumerType(ctype);
// Disable autobind for the owner.
owner.setAutobindDisabled(true);
// Create a key that has autobind disabled.
ActivationKey key = new ActivationKey("autobind-disabled-key", owner);
key.setAutoAttach(true);
when(activationKeyCurator.getByKeyName(owner, key.getName())).thenReturn(key);
// No auth should be required for registering with keys:
Principal p = new NoAuthPrincipal();
ConsumerDTO consumer = TestUtil.createConsumerDTO("sys.example.com", null, null, ctypeDTO);
resource.create(consumer, p, null, owner.getKey(), key.getName(), true);
}
@Test(expected = BadRequestException.class)
public void orgRequiredWithActivationKeys() {
Principal p = new NoAuthPrincipal();
List<String> keys = mockActivationKeys();
ConsumerDTO consumer = TestUtil.createConsumerDTO("sys.example.com", null, null, systemDto);
resource.create(consumer, p, null, null, createKeysString(keys), true);
}
@Test(expected = BadRequestException.class)
public void cannotMixUsernameWithActivationKeys() {
Principal p = new NoAuthPrincipal();
List<String> keys = mockActivationKeys();
ConsumerDTO consumer = TestUtil.createConsumerDTO("sys.example.com", null, null, systemDto);
resource.create(consumer, p, USER, owner.getKey(), createKeysString(keys), true);
}
@Test(expected = BadRequestException.class)
public void failIfOnlyActivationKeyDoesNotExistForOrg() {
Principal p = new NoAuthPrincipal();
List<String> keys = new ArrayList<>();
keys.add("NoSuchKey");
ConsumerDTO consumer = TestUtil.createConsumerDTO("sys.example.com", null, null, systemDto);
resource.create(consumer, p, null, owner.getKey(), createKeysString(keys), true);
}
@Test
public void passIfOnlyOneActivationKeyDoesNotExistForOrg() {
Principal p = new NoAuthPrincipal();
List<String> keys = mockActivationKeys();
keys.add("NoSuchKey");
ConsumerDTO consumer = TestUtil.createConsumerDTO("sys.example.com", null, null, systemDto);
resource.create(consumer, p, null, owner.getKey(), createKeysString(keys), true);
}
@Test
public void registerWithNoInstalledProducts() {
Principal p = new TrustedUserPrincipal("anyuser");
ConsumerDTO consumer = TestUtil.createConsumerDTO("consumerName", null, null, systemDto);
resource.create(consumer, p, USER, owner.getKey(), null, true);
}
@Test
public void registerWithNullReleaseVer() {
Principal p = new TrustedUserPrincipal("anyuser");
ConsumerDTO consumer = TestUtil.createConsumerDTO("consumername", null, null, systemDto);
consumer.setReleaseVersion(null);
resource.create(consumer, p, USER, owner.getKey(), null, true);
}
@Test
public void registerWithEmptyReleaseVer() {
Principal p = new TrustedUserPrincipal("anyuser");
ConsumerDTO consumer = TestUtil.createConsumerDTO("consumername", null, null, systemDto);
consumer.setReleaseVersion("");
resource.create(consumer, p, USER, owner.getKey(), null, true);
}
@Test
public void registerWithNoReleaseVer() {
Principal p = new TrustedUserPrincipal("anyuser");
ConsumerDTO consumer = TestUtil.createConsumerDTO("consumername", null, null, systemDto);
resource.create(consumer, p, USER, owner.getKey(), null, true);
}
@Test
public void setStatusOnCreate() {
Principal p = new TrustedUserPrincipal("anyuser");
ConsumerDTO consumer = TestUtil.createConsumerDTO("consumername", null, null, systemDto);
resource.create(consumer, p, USER, owner.getKey(), null, true);
// Should be called with the consumer, null date (now),
// no compliantUntil, and not update the consumer record
verify(complianceRules).getStatus(any(Consumer.class), eq((Date) null), eq(false), eq(false));
}
}