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 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
|
package com.google.inject;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE_USE;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.TestLogHandler;
import com.google.inject.RestrictedBindingSource.RestrictionLevel;
import com.google.inject.spi.ElementSource;
import com.google.inject.spi.Elements;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.ModuleAnnotatedMethodScanner;
import com.google.inject.util.Modules;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.inject.Qualifier;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link RestrictedBindingSource}.
*
* @author vzm@google.com (Vladimir Makaric)
*/
@RunWith(JUnit4.class)
public class RestrictedBindingSourceTest {
// --------------------------------------------------------------------------
// Core Functionality Tests
// --------------------------------------------------------------------------
private static final String BINDING_PERMISSION_ERROR = "Unable to bind key";
private static final String USE_NETWORK_MODULE = "Please install NetworkModule.";
private static final String USE_ROUTING_MODULE = "Please install RoutingModule.";
private static final String NETWORK_ANNOTATION_IS_RESTRICTED =
"The @Network annotation can only be used to annotate Network library Keys.";
@RestrictedBindingSource.Permit
@Retention(RetentionPolicy.RUNTIME)
@interface NetworkLibrary {}
@Qualifier
@RestrictedBindingSource(
explanation = USE_NETWORK_MODULE,
permits = {NetworkLibrary.class})
@Retention(RetentionPolicy.RUNTIME)
@interface GatewayIpAdress {}
@Qualifier
@RestrictedBindingSource(
explanation = USE_NETWORK_MODULE,
permits = {NetworkLibrary.class})
@Retention(RetentionPolicy.RUNTIME)
@interface Hostname {}
@NetworkLibrary
private static class NetworkModule extends AbstractModule {
@Provides
@GatewayIpAdress
int provideIpAddress() {
return 21321566;
}
@Override
protected void configure() {
bind(String.class).annotatedWith(Hostname.class).toInstance("google.com");
}
}
@Test
public void networkLibraryCanProvideItsBindings() {
Guice.createInjector(new NetworkModule());
}
@RestrictedBindingSource(
explanation = USE_ROUTING_MODULE,
permits = {NetworkLibrary.class})
@ImplementedBy(RoutingTableImpl.class) // For testing untargetted bindings.
interface RoutingTable {
int getNextHopIpAddress(int destinationIpAddress);
}
@NetworkLibrary
private static class RoutingModule extends AbstractModule {
@Provides
RoutingTable provideRoutingTable(@GatewayIpAdress int gateway) {
return destinationIp -> gateway;
}
}
@Test
public void networkBindingCantBeProvidedByOtherModules() {
AbstractModule rogueModule =
new AbstractModule() {
// This will fail, the gateway IP can only be provided by the network library.
@Provides
@GatewayIpAdress
int provideGatewayIp() {
return 42;
}
@Override
protected void configure() {
install(new RoutingModule());
}
};
CreationException expected = assertThatInjectorCreationFails(rogueModule);
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_NETWORK_MODULE);
}
@Test
public void missingImplementationErrorForRestrictedBindingIncludesExplanation() {
CreationException expected = assertThatInjectorCreationFails(new RoutingModule());
assertThat(expected)
.hasMessageThat()
.contains(
"Hint: This key is restricted and cannot be bound directly. Restriction explanation:"
+ " Please install NetworkModule.");
}
@Test
public void canBindRestrictedTypeWithUnrestrictedQualifierAnnotation() {
Guice.createInjector(
new AbstractModule() {
@Provides
@Named("custom")
RoutingTable provideRoutingTable() {
return ip -> ip;
}
});
}
@Test
public void twoRogueNetworkBindingsYieldTwoErrorMessages() {
AbstractModule rogueModule =
new AbstractModule() {
@Provides
@GatewayIpAdress
int provideGatewayIp() {
return 42;
}
@Provides
RoutingTable provideRoutingTable() {
return destinationIp -> 0;
}
};
CreationException expected = assertThatInjectorCreationFails(rogueModule);
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_NETWORK_MODULE);
assertThat(expected).hasMessageThat().contains(USE_ROUTING_MODULE);
}
@RestrictedBindingSource.Permit
@Retention(RetentionPolicy.RUNTIME)
@interface NetworkTestLibrary {}
@Qualifier
@RestrictedBindingSource(
explanation = USE_NETWORK_MODULE,
permits = {NetworkLibrary.class, NetworkTestLibrary.class})
@Retention(RetentionPolicy.RUNTIME)
@interface MacAddress {}
@NetworkTestLibrary
private static class TestMacAddressModule extends AbstractModule {
@Provides
@MacAddress
String provideMacAddress() {
return "deadbeef";
}
}
@Test
public void bindingWithTwoPermitsAllowedIfOnePresent() {
Guice.createInjector(new TestMacAddressModule());
}
private static class RoutingTableImpl implements RoutingTable {
@Inject
RoutingTableImpl() {}
@Override
public int getNextHopIpAddress(int destinationIpAddress) {
return destinationIpAddress + 2;
}
}
@Test
public void untargettedBindingAllowedWithPermit() {
@NetworkLibrary
class PermittedNetworkModule extends AbstractModule {
@Override
protected void configure() {
bind(RoutingTable.class);
}
}
Guice.createInjector(new PermittedNetworkModule());
}
@Test
public void untargettedBindingDisallowedWithoutPermit() {
AbstractModule rogueModule =
new AbstractModule() {
@Override
protected void configure() {
bind(RoutingTable.class);
}
};
CreationException expected = assertThatInjectorCreationFails(rogueModule);
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_ROUTING_MODULE);
}
@RestrictedBindingSource.Permit
@Retention(RetentionPolicy.RUNTIME)
@Target(TYPE_USE)
@interface FooPermit {}
@Qualifier
@RestrictedBindingSource(
explanation = "Only modules with FooPermit can bind @Foo bindings.",
permits = {FooPermit.class})
@Retention(RetentionPolicy.RUNTIME)
@interface Foo {}
@Test
public void permitOnAnonymousClassWorks() {
Guice.createInjector(
new @FooPermit AbstractModule() {
@Provides
@Foo
String provideFooString() {
return "foo";
}
});
}
@Qualifier
@RestrictedBindingSource(
explanation = USE_NETWORK_MODULE,
permits = {NetworkLibrary.class},
restrictionLevel = RestrictionLevel.WARNING)
@Retention(RetentionPolicy.RUNTIME)
@interface HostIp {}
@Test
public void rogueBindingWithWarningRestrictionLevel() {
Logger logger = Logger.getLogger(RestrictedBindingSource.class.getName());
TestLogHandler testLogHandler = new TestLogHandler();
logger.addHandler(testLogHandler);
Guice.createInjector(
new AbstractModule() {
@Provides
@HostIp
int provideRogueHostIp() {
return 4;
}
});
List<LogRecord> logs = testLogHandler.getStoredLogRecords();
assertThat(logs).hasSize(1);
assertThat(logs.get(0).getLevel()).isEqualTo(Level.WARNING);
assertThat(logs.get(0).getMessage()).contains(USE_NETWORK_MODULE);
assertThat(logs.get(0).getMessage()).contains("provideRogueHostIp");
logger.removeHandler(testLogHandler);
}
// --------------------------------------------------------------------------
// Module Exemption Tests
// --------------------------------------------------------------------------
private static final String USE_DNS_MODULE = "Use the official DNS module";
@Qualifier
@RestrictedBindingSource(
explanation = USE_DNS_MODULE,
permits = {NetworkLibrary.class},
exemptModules =
"com.google.inject.RestrictedBindingSourceTest\\$FooRogueDnsModule"
+ "|com.google.inject.RestrictedBindingSourceTest\\$BarRogueDnsModule"
+ "|com.google.inject.RestrictedBindingSourceTest\\$TopLevelModulePrivatelyBindingDnsAddress")
@Retention(RetentionPolicy.RUNTIME)
@interface DnsAddress {}
static class FooRogueDnsModule extends AbstractModule {
@Provides
@DnsAddress
int rogueDns() {
return 4;
}
}
static class BarRogueDnsModule extends AbstractModule {
@Provides
@DnsAddress
int rogueDns() {
return 5;
}
}
// Non-exempt
static class BazRogueDnsModule extends AbstractModule {
@Provides
@DnsAddress
int rogueDns() {
return 5;
}
}
static class TopLevelModulePrivatelyBindingDnsAddress extends AbstractModule {
@Override
protected void configure() {
install(
new PrivateModule() {
@Override
protected void configure() {
// Non-exempt module.
install(new BazRogueDnsModule());
}
});
}
}
@Test
public void exemptModulesCanCreateRestrictedBinding() {
Guice.createInjector(new FooRogueDnsModule());
Guice.createInjector(new BarRogueDnsModule());
}
@Test
public void nonExemptModuleCantCreateRestrictedBinding() {
CreationException expected = assertThatInjectorCreationFails(new BazRogueDnsModule());
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_DNS_MODULE);
}
@Test
public void parentModuleExeptionAppliesToChildPrivateModule() {
Guice.createInjector(new TopLevelModulePrivatelyBindingDnsAddress());
}
@Test
public void exemptModuleCanBeOverridenIfRestrictedBindingIsNotOverriden() {
// This tests that we check for exemptions on the module stack of the original element source.
Guice.createInjector(
Modules.override(
new AbstractModule() {
@Override
protected void configure() {
install(new BarRogueDnsModule());
}
@Provides
String random() {
return "foo";
}
})
.with(
new AbstractModule() {
@Provides
String random() {
return "bar";
}
}));
}
// --------------------------------------------------------------------------
// Binder.withSource Tests
// --------------------------------------------------------------------------
@NetworkLibrary
private static class PermittedModule extends AbstractModule {
@Override
protected void configure() {
Method userUnpermittedModuleMethod;
try {
userUnpermittedModuleMethod = UnpermittedModule.class.getMethod("foo");
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
binder()
.withSource(userUnpermittedModuleMethod)
.bind(String.class)
.annotatedWith(Hostname.class)
.toInstance("google.com");
}
}
private static class UnpermittedModule extends AbstractModule {
public String foo() {
return "bar";
}
}
@Test
public void permittedModuleCanWithSourceAnUnpermittedModuleMethod() {
Guice.createInjector(new PermittedModule());
}
@Test
public void unpermittedModuleCantWithSourceAPermittedModule() {
AbstractModule rogueModule =
new AbstractModule() {
@Override
protected void configure() {
binder()
.withSource(PermittedModule.class)
.bindConstant()
.annotatedWith(GatewayIpAdress.class)
.to(0);
}
};
CreationException expected = assertThatInjectorCreationFails(rogueModule);
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_NETWORK_MODULE);
}
@Test
public void getElements_getModule_works() {
Guice.createInjector(Elements.getModule(Elements.getElements(new NetworkModule())));
}
// --------------------------------------------------------------------------
// ModuleAnnotatedMethodScanner tests
// --------------------------------------------------------------------------
@Target(METHOD)
@Retention(RetentionPolicy.RUNTIME)
private @interface NetworkProvides {}
@Qualifier
@RestrictedBindingSource(
explanation = NETWORK_ANNOTATION_IS_RESTRICTED,
permits = {NetworkLibrary.class})
@Retention(RetentionPolicy.RUNTIME)
@interface Network {}
// Adds the NetworkLibrary-owned Network annotation to keys produced by @NetworkProvides methods.
private static class NetworkProvidesScanner extends ModuleAnnotatedMethodScanner {
@Override
public String toString() {
return "NetworkProvidesScanner";
}
@Override
public Set<? extends Class<? extends Annotation>> annotationClasses() {
return ImmutableSet.of(NetworkProvides.class);
}
@Override
public <T> Key<T> prepareMethod(
Binder binder, Annotation annotation, Key<T> key, InjectionPoint injectionPoint) {
return key.withAnnotation(Network.class);
}
}
@Test
public void rogueBindingByMethodScannerDenied() {
AbstractModule rogueModule =
new AbstractModule() {
@NetworkProvides
String provideNetworkString() {
return "lorem ipsum";
}
};
CreationException expected =
assertThatInjectorCreationFails(rogueModule, scannerModule(new NetworkProvidesScanner()));
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(NETWORK_ANNOTATION_IS_RESTRICTED);
}
@Test
public void bindingsAddedByMethodScannerAllowedByNetworkLib() {
@NetworkLibrary
class NetworkModuleWithCustomProvides extends AbstractModule {
@NetworkProvides
String provideNetworkString() {
return "the real network string";
}
}
Guice.createInjector(
new NetworkModuleWithCustomProvides(), scannerModule(new NetworkProvidesScanner()));
}
@Test
public void scannerWithPermitCanCreateRestrictedBinding() {
@NetworkLibrary
class NetworkProvidesScannerWithPermit extends NetworkProvidesScanner {}
AbstractModule moduleWithNetworkProvidesMethod =
new AbstractModule() {
@NetworkProvides
String provideNetworkString() {
return "lorem ipsum";
}
};
Guice.createInjector(
moduleWithNetworkProvidesMethod, scannerModule(new NetworkProvidesScannerWithPermit()));
}
@Test
public void scannerWithPermitCanCreateRestrictedBindings() {
@NetworkLibrary
class NetworkProvidesScannerWithPermit extends NetworkProvidesScanner {
@Override
public <T> Key<T> prepareMethod(
Binder binder, Annotation annotation, Key<T> key, InjectionPoint injectionPoint) {
binder.install(
new AbstractModule() {
@Provides
@GatewayIpAdress
int provideGatewayIp() {
return 42;
}
});
return Key.get(key.getTypeLiteral(), Network.class);
}
}
AbstractModule moduleWithNetworkProvidesMethod =
new AbstractModule() {
@NetworkProvides
String provideNetworkString() {
return "lorem ipsum";
}
};
Injector injector =
Guice.createInjector(
moduleWithNetworkProvidesMethod, scannerModule(new NetworkProvidesScannerWithPermit()));
assertThat(injector.getInstance(Key.get(Integer.class, GatewayIpAdress.class))).isEqualTo(42);
}
@Test
public void moduleInstalledByScannerInheritsMethodModulePermit() {
class NetworkProvidesScannerWithoutPermit extends NetworkProvidesScanner {
@Override
public <T> Key<T> prepareMethod(
Binder binder, Annotation annotation, Key<T> key, InjectionPoint injectionPoint) {
binder.install(
new AbstractModule() {
@Provides
@GatewayIpAdress
int provideGatewayIp() {
return 42;
}
});
return key.withAnnotation(Network.class);
}
}
@NetworkLibrary
class ScannedModuleWithPermit extends AbstractModule {
@NetworkProvides
String provideNetworkString() {
return "lorem ipsum";
}
}
Injector injector =
Guice.createInjector(
new ScannedModuleWithPermit(),
scannerModule(new NetworkProvidesScannerWithoutPermit()));
assertThat(injector.getInstance(Key.get(Integer.class, GatewayIpAdress.class))).isEqualTo(42);
}
private static Module scannerModule(ModuleAnnotatedMethodScanner scanner) {
return new AbstractModule() {
@Override
protected void configure() {
binder().scanModulesForAnnotatedMethods(scanner);
}
};
}
// --------------------------------------------------------------------------
// Modules.override tests
// --------------------------------------------------------------------------
@Test
public void modulesOverrideCantOverrideRestrictedBinding() {
Module rogueModule =
Modules.override(new NetworkModule())
.with(
new AbstractModule() {
@Provides
@GatewayIpAdress
int provideRogueGatewayIp() {
return 12345;
}
});
CreationException expected = assertThatInjectorCreationFails(rogueModule);
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_NETWORK_MODULE);
}
@Test
public void modulesOverrideRestrictedBindingAllowedIfParentHasPermit() {
@NetworkLibrary
class NetworkModuleVersion2 extends AbstractModule {
@Override
protected void configure() {
install(
Modules.override(new NetworkModule())
.with(
new AbstractModule() {
@Provides
@GatewayIpAdress
int provideGatewayIpV2() {
return 2;
}
}));
}
}
assertThat(
Guice.createInjector(new NetworkModuleVersion2())
.getInstance(Key.get(Integer.class, GatewayIpAdress.class)))
.isEqualTo(2);
}
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@interface UnrestrictedQualifier {}
@Test
public void modulesOverrideCanOverrideUnrestrictedBinding() {
Module overrideModule =
Modules.override(
new NetworkModule(),
new AbstractModule() {
@Override
protected void configure() {
bindConstant().annotatedWith(UnrestrictedQualifier.class).to("foo");
}
})
.with(
new AbstractModule() {
@Provides
@UnrestrictedQualifier
String provideRogueGatewayIp() {
return "bar";
}
});
assertThat(
Guice.createInjector(overrideModule)
.getInstance(Key.get(String.class, UnrestrictedQualifier.class)))
.isEqualTo("bar");
}
@Test
public void nestedModulesOverrideCanOverrideUnrestrictedBindings() {
Module overrideModule =
Modules.override(
Modules.override(
new NetworkModule(),
new AbstractModule() {
@Override
protected void configure() {
bindConstant().annotatedWith(UnrestrictedQualifier.class).to("foo");
bindConstant().annotatedWith(UnrestrictedQualifier.class).to(42);
}
})
.with(
new AbstractModule() {
@Provides
@UnrestrictedQualifier
String overrideString() {
return "bar";
}
}))
.with(
new AbstractModule() {
@Provides
@UnrestrictedQualifier
int overrideLong() {
return 45;
}
});
Injector injector = Guice.createInjector(overrideModule);
assertThat(injector.getInstance(Key.get(String.class, UnrestrictedQualifier.class)))
.isEqualTo("bar");
assertThat(injector.getInstance(Key.get(Integer.class, UnrestrictedQualifier.class)))
.isEqualTo(45);
}
@Test
public void modulesOverridePrivateModule() {
Guice.createInjector(
Modules.override(
new PrivateModule() {
@Override
protected void configure() {
install(new NetworkModule());
expose(Key.get(String.class, Hostname.class));
}
@Provides
@Exposed
@Named("custom-gateway")
int customGateway(@GatewayIpAdress int gateway) {
return gateway + 4;
}
})
.with(
new AbstractModule() {
@Provides
@Named("custom-gateway")
int provideCustomGatewayOverride() {
return 12345;
}
}));
}
@Test
public void originalElementSourceNotTrustedIfSetExternally() {
ElementSource networkElementSource =
(ElementSource) Elements.getElements(new NetworkModule()).get(0).getSource();
AbstractModule rogueModule =
new AbstractModule() {
@Override
protected void configure() {
binder()
.withSource(networkElementSource)
.bindConstant()
.annotatedWith(GatewayIpAdress.class)
.to(12);
}
};
// Confirm that the original element source was spoofed.
@SuppressWarnings("unchecked")
Binding<Integer> rogueGatewayBinding =
(Binding<Integer>) Elements.getElements(rogueModule).get(0);
assertThat(((ElementSource) rogueGatewayBinding.getSource()).getOriginalElementSource())
.isEqualTo(networkElementSource);
// Will fail because the original element source isn't trusted, becase it wasn't set by Guice
// internals.
CreationException expected = assertThatInjectorCreationFails(rogueModule);
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_NETWORK_MODULE);
}
// --------------------------------------------------------------------------
// PrivateModule tests
// --------------------------------------------------------------------------
@NetworkLibrary
private static class NetworkModuleThatInstalls extends AbstractModule {
final Module module;
NetworkModuleThatInstalls(Module module) {
this.module = module;
}
@Override
protected void configure() {
install(module);
}
}
private static class PrivateModuleCreatesUnexposedNetworkBinding extends PrivateModule {
@Override
protected void configure() {
bindConstant().annotatedWith(GatewayIpAdress.class).to(0);
}
}
@Test
public void parentHasPermit_childPrivateModuleCanBind() {
Guice.createInjector(
new NetworkModuleThatInstalls(
// Allowed because the parent has the @NetworkLibrary permit.
new PrivateModuleCreatesUnexposedNetworkBinding()));
}
@Test
public void noPermitOnStack_privateModuleCantBind() {
AbstractModule rogueModule =
new AbstractModule() {
@Override
protected void configure() {
// Disallowed because there's no permit on the module stack.
install(new PrivateModuleCreatesUnexposedNetworkBinding());
}
};
CreationException expected = assertThatInjectorCreationFails(rogueModule);
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_NETWORK_MODULE);
}
private static class PrivateModuleExposesNetworkBinding extends PrivateModule {
@Override
protected void configure() {
install(
new AbstractModule() {
@Override
protected void configure() {
bindConstant().annotatedWith(GatewayIpAdress.class).to(0);
}
});
expose(Key.get(Integer.class, GatewayIpAdress.class));
}
}
@Test
public void parentHasPermit_childPrivateModuleCanExposeBinding() {
Guice.createInjector(
new NetworkModuleThatInstalls(
// Allowed because the parent has the @NetworkLibrary permit.
new PrivateModuleExposesNetworkBinding()));
}
@Test
public void noPermitOnStack_childPrivateModuleCantExposeBinding() {
AbstractModule rogueModule =
new AbstractModule() {
@Override
protected void configure() {
// Disallowed because there's no permit on the module stack.
install(new PrivateModuleExposesNetworkBinding());
}
};
CreationException expected = assertThatInjectorCreationFails(rogueModule);
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_NETWORK_MODULE);
}
// --------------------------------------------------------------------------
// Child Injector tests
// --------------------------------------------------------------------------
@Test
public void childInjectorCantBindRestrictedBindingWithoutPermit() {
Injector parent = Guice.createInjector(new NetworkModule());
AbstractModule rogueModule =
new AbstractModule() {
@Provides
RoutingTable provideRoutingTable() {
return destinationIp -> 0;
}
};
CreationException expected =
assertThrows(CreationException.class, () -> parent.createChildInjector(rogueModule));
assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR);
assertThat(expected).hasMessageThat().contains(USE_ROUTING_MODULE);
}
@Test
public void childInjectorCanBindRestrictedBindingWithPermit() {
Injector parent = Guice.createInjector(new NetworkModule());
parent.createChildInjector(new RoutingModule());
}
CreationException assertThatInjectorCreationFails(Module... modules) {
return assertThrows(CreationException.class, () -> Guice.createInjector(modules));
}
}
|