You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@karaf.apache.org by ff...@apache.org on 2014/04/29 11:23:15 UTC
[4/4] git commit: [KARAF-2934]Role-based security for Shell/Console
commands - backport to 2.x branch #1st commit
[KARAF-2934]Role-based security for Shell/Console commands - backport to 2.x branch #1st commit
Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/4b8cc102
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/4b8cc102
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/4b8cc102
Branch: refs/heads/karaf-2.x
Commit: 4b8cc102226adce53f4d74f2c39843ab7f683dbd
Parents: 8a35113
Author: Freeman Fang <fr...@gmail.com>
Authored: Tue Apr 29 17:22:01 2014 +0800
Committer: Freeman Fang <fr...@gmail.com>
Committed: Tue Apr 29 17:22:01 2014 +0800
----------------------------------------------------------------------
assemblies/apache-karaf/pom.xml | 5 +
.../src/main/descriptors/unix-bin-release.xml | 12 +
.../src/main/descriptors/unix-bin-snapshot.xml | 11 +
.../main/descriptors/windows-bin-release.xml | 11 +
.../main/descriptors/windows-bin-snapshot.xml | 11 +
.../distribution/text/etc/system.properties | 13 +-
.../filtered-resources/etc/startup.properties | 1 +
.../standard/src/main/resources/features.xml | 1 +
.../apache/karaf/itests/KarafTestSupport.java | 44 +
management/server/pom.xml | 5 +
pom.xml | 6 +
service/guard/NOTICE | 71 +
service/guard/pom.xml | 115 ++
.../karaf/service/guard/impl/Activator.java | 67 +
.../service/guard/impl/GuardProxyCatalog.java | 598 +++++++
.../service/guard/impl/GuardingEventHook.java | 63 +
.../service/guard/impl/GuardingFindHook.java | 62 +
.../guard/tools/ACLConfigurationParser.java | 337 ++++
.../src/main/resources/OSGI-INF/bundle.info | 53 +
.../karaf/service/guard/impl/ActivatorTest.java | 128 ++
.../guard/impl/GuardProxyCatalogTest.java | 1652 ++++++++++++++++++
.../guard/impl/GuardingEventHookTest.java | 253 +++
.../guard/impl/GuardingFindHookTest.java | 241 +++
.../guard/tools/ACLConfigurationParserTest.java | 104 ++
service/pom.xml | 40 +
shell/console/pom.xml | 2 +
.../org/apache/karaf/shell/console/Main.java | 2 +-
.../karaf/shell/console/jline/Console.java | 111 +-
.../shell/console/jline/ConsoleFactory.java | 13 +-
.../impl/SecuredCommandConfigTransformer.java | 164 ++
.../impl/SecuredCommandProcessorImpl.java | 190 ++
.../OSGI-INF/blueprint/karaf-console.xml | 12 +-
.../shell/console/ExampleSubclassMain.java | 2 +-
.../karaf/shell/console/jline/ConsoleTest.java | 195 +++
.../SecuredCommandConfigTransformerTest.java | 278 +++
.../impl/SecuredCommandProcessorImplTest.java | 142 ++
.../karaf/shell/ssh/KarafJaasAuthenticator.java | 55 +-
.../karaf/shell/ssh/ShellFactoryImpl.java | 9 +-
.../resources/OSGI-INF/blueprint/shell-ssh.xml | 4 +-
.../karaf/webconsole/gogo/GogoPlugin.java | 3 +-
40 files changed, 5018 insertions(+), 68 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/assemblies/apache-karaf/pom.xml
----------------------------------------------------------------------
diff --git a/assemblies/apache-karaf/pom.xml b/assemblies/apache-karaf/pom.xml
index 966eab8..8053957 100644
--- a/assemblies/apache-karaf/pom.xml
+++ b/assemblies/apache-karaf/pom.xml
@@ -71,6 +71,11 @@
<artifactId>org.apache.karaf.deployer.wrap</artifactId>
</dependency>
<dependency>
+ <groupId>org.apache.karaf.service</groupId>
+ <artifactId>org.apache.karaf.service.guard</artifactId>
+ </dependency>
+
+ <dependency>
<groupId>org.apache.karaf.features</groupId>
<artifactId>org.apache.karaf.features.core</artifactId>
</dependency>
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/assemblies/apache-karaf/src/main/descriptors/unix-bin-release.xml
----------------------------------------------------------------------
diff --git a/assemblies/apache-karaf/src/main/descriptors/unix-bin-release.xml b/assemblies/apache-karaf/src/main/descriptors/unix-bin-release.xml
index f3d27e1..1c4657c 100644
--- a/assemblies/apache-karaf/src/main/descriptors/unix-bin-release.xml
+++ b/assemblies/apache-karaf/src/main/descriptors/unix-bin-release.xml
@@ -182,6 +182,18 @@
<unpack>false</unpack>
<useProjectArtifact>false</useProjectArtifact>
<outputFileNameMapping>
+ org/apache/karaf/service/${artifact.artifactId}/${artifact.baseVersion}/${artifact.artifactId}-${artifact.baseVersion}${dashClassifier?}.${artifact.extension}
+ </outputFileNameMapping>
+ <includes>
+ <include>org.apache.karaf.service:org.apache.karaf.service.guard</include>
+ </includes>
+ </dependencySet>
+
+ <dependencySet>
+ <outputDirectory>/system</outputDirectory>
+ <unpack>false</unpack>
+ <useProjectArtifact>false</useProjectArtifact>
+ <outputFileNameMapping>
org/apache/karaf/diagnostic/${artifact.artifactId}/${artifact.baseVersion}/${artifact.artifactId}-${artifact.baseVersion}${dashClassifier?}.${artifact.extension}
</outputFileNameMapping>
<includes>
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/assemblies/apache-karaf/src/main/descriptors/unix-bin-snapshot.xml
----------------------------------------------------------------------
diff --git a/assemblies/apache-karaf/src/main/descriptors/unix-bin-snapshot.xml b/assemblies/apache-karaf/src/main/descriptors/unix-bin-snapshot.xml
index 9b2849f..27b0142 100644
--- a/assemblies/apache-karaf/src/main/descriptors/unix-bin-snapshot.xml
+++ b/assemblies/apache-karaf/src/main/descriptors/unix-bin-snapshot.xml
@@ -182,6 +182,17 @@
<unpack>false</unpack>
<useProjectArtifact>false</useProjectArtifact>
<outputFileNameMapping>
+ org/apache/karaf/service/${artifact.artifactId}/${artifact.baseVersion}/${artifact.artifactId}-${artifact.baseVersion}${dashClassifier?}.${artifact.extension}
+ </outputFileNameMapping>
+ <includes>
+ <include>org.apache.karaf.service:org.apache.karaf.service.guard</include>
+ </includes>
+ </dependencySet>
+ <dependencySet>
+ <outputDirectory>/system</outputDirectory>
+ <unpack>false</unpack>
+ <useProjectArtifact>false</useProjectArtifact>
+ <outputFileNameMapping>
org/apache/karaf/diagnostic/${artifact.artifactId}/${artifact.baseVersion}/${artifact.artifactId}-${artifact.baseVersion}${dashClassifier?}.${artifact.extension}
</outputFileNameMapping>
<includes>
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/assemblies/apache-karaf/src/main/descriptors/windows-bin-release.xml
----------------------------------------------------------------------
diff --git a/assemblies/apache-karaf/src/main/descriptors/windows-bin-release.xml b/assemblies/apache-karaf/src/main/descriptors/windows-bin-release.xml
index 3227b30..ce68a81 100644
--- a/assemblies/apache-karaf/src/main/descriptors/windows-bin-release.xml
+++ b/assemblies/apache-karaf/src/main/descriptors/windows-bin-release.xml
@@ -190,6 +190,17 @@
<unpack>false</unpack>
<useProjectArtifact>false</useProjectArtifact>
<outputFileNameMapping>
+ org/apache/karaf/service/${artifact.artifactId}/${artifact.baseVersion}/${artifact.artifactId}-${artifact.baseVersion}${dashClassifier?}.${artifact.extension}
+ </outputFileNameMapping>
+ <includes>
+ <include>org.apache.karaf.service:org.apache.karaf.service.guard</include>
+ </includes>
+ </dependencySet>
+ <dependencySet>
+ <outputDirectory>/system</outputDirectory>
+ <unpack>false</unpack>
+ <useProjectArtifact>false</useProjectArtifact>
+ <outputFileNameMapping>
org/apache/karaf/diagnostic/${artifact.artifactId}/${artifact.baseVersion}/${artifact.artifactId}-${artifact.baseVersion}${dashClassifier?}.${artifact.extension}
</outputFileNameMapping>
<includes>
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/assemblies/apache-karaf/src/main/descriptors/windows-bin-snapshot.xml
----------------------------------------------------------------------
diff --git a/assemblies/apache-karaf/src/main/descriptors/windows-bin-snapshot.xml b/assemblies/apache-karaf/src/main/descriptors/windows-bin-snapshot.xml
index 984f3d1..9b4c0b8 100644
--- a/assemblies/apache-karaf/src/main/descriptors/windows-bin-snapshot.xml
+++ b/assemblies/apache-karaf/src/main/descriptors/windows-bin-snapshot.xml
@@ -190,6 +190,17 @@
<unpack>false</unpack>
<useProjectArtifact>false</useProjectArtifact>
<outputFileNameMapping>
+ org/apache/karaf/service/${artifact.artifactId}/${artifact.baseVersion}/${artifact.artifactId}-${artifact.baseVersion}${dashClassifier?}.${artifact.extension}
+ </outputFileNameMapping>
+ <includes>
+ <include>org.apache.karaf.service:org.apache.karaf.service.guard</include>
+ </includes>
+ </dependencySet>
+ <dependencySet>
+ <outputDirectory>/system</outputDirectory>
+ <unpack>false</unpack>
+ <useProjectArtifact>false</useProjectArtifact>
+ <outputFileNameMapping>
org/apache/karaf/diagnostic/${artifact.artifactId}/${artifact.baseVersion}/${artifact.artifactId}-${artifact.baseVersion}${dashClassifier?}.${artifact.extension}
</outputFileNameMapping>
<includes>
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/assemblies/apache-karaf/src/main/distribution/text/etc/system.properties
----------------------------------------------------------------------
diff --git a/assemblies/apache-karaf/src/main/distribution/text/etc/system.properties b/assemblies/apache-karaf/src/main/distribution/text/etc/system.properties
index 066c9ef..99ce56d 100644
--- a/assemblies/apache-karaf/src/main/distribution/text/etc/system.properties
+++ b/assemblies/apache-karaf/src/main/distribution/text/etc/system.properties
@@ -56,7 +56,7 @@ karaf.shell.init.script = ${karaf.etc}/shell.init.script
# karaf.shell.history.maxSize = 0
#
-# Default role name used for console authorization (JMX, SSH and WEB)
+# Roles to use when logging into a local Karaf console.
# The syntax is the following:
# [classname:]principal
# where classname is the class name of the principal object
@@ -64,10 +64,7 @@ karaf.shell.init.script = ${karaf.etc}/shell.init.script
# and principal is the name of the principal of that class
# (defaults to admin).
#
-# Note that this value can be overriden using the various ConfigAdmin
-# configurations for JMX, SSH or the WebConsole.
-#
-karaf.admin.role = admin
+karaf.local.roles=admin,manager,viewer
#
# Set this empty property to avoid errors when validating xml documents.
@@ -106,6 +103,12 @@ org.apache.aries.proxy.weaving.enabled = none
org.apache.aries.proxy.weaving.disabled = org.objectweb.asm.*,org.slf4j.*,org.apache.log4j.*,javax.*,org.apache.xerces.*
#
+# By default, only Karaf shell commands are secured, but additional services can be
+# secured by expanding this filter
+#
+karaf.secured.services=(&(osgi.command.scope=*)(osgi.command.function=*))
+
+#
# Security properties
#
#java.security.policy=${karaf.home}/etc/all.policy
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/assemblies/apache-karaf/src/main/filtered-resources/etc/startup.properties
----------------------------------------------------------------------
diff --git a/assemblies/apache-karaf/src/main/filtered-resources/etc/startup.properties b/assemblies/apache-karaf/src/main/filtered-resources/etc/startup.properties
index 2abc48a..138a26f 100644
--- a/assemblies/apache-karaf/src/main/filtered-resources/etc/startup.properties
+++ b/assemblies/apache-karaf/src/main/filtered-resources/etc/startup.properties
@@ -32,6 +32,7 @@ org/ops4j/pax/url/pax-url-mvn/${pax.url.version}/pax-url-mvn-${pax.url.version}.
org/ops4j/pax/url/pax-url-wrap/${pax.url.version}/pax-url-wrap-${pax.url.version}.jar=5
org/ops4j/pax/logging/pax-logging-api/${pax.logging.version}/pax-logging-api-${pax.logging.version}.jar=8
org/ops4j/pax/logging/pax-logging-service/${pax.logging.version}/pax-logging-service-${pax.logging.version}.jar=8
+org/apache/karaf/service/org.apache.karaf.service.guard/${project.version}/org.apache.karaf.service.guard-${project.version}.jar=10
org/apache/felix/org.apache.felix.configadmin/${felix.configadmin.version}/org.apache.felix.configadmin-${felix.configadmin.version}.jar=10
org/apache/felix/org.apache.felix.fileinstall/${felix.fileinstall.version}/org.apache.felix.fileinstall-${felix.fileinstall.version}.jar=11
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/assemblies/features/standard/src/main/resources/features.xml
----------------------------------------------------------------------
diff --git a/assemblies/features/standard/src/main/resources/features.xml b/assemblies/features/standard/src/main/resources/features.xml
index 593992b..10e55a6 100644
--- a/assemblies/features/standard/src/main/resources/features.xml
+++ b/assemblies/features/standard/src/main/resources/features.xml
@@ -25,6 +25,7 @@
<bundle start-level="5">mvn:org.ops4j.pax.url/pax-url-wrap/${pax.url.version}</bundle>
<bundle start-level="8">mvn:org.ops4j.pax.logging/pax-logging-api/${pax.logging.version}</bundle>
<bundle start-level="8">mvn:org.ops4j.pax.logging/pax-logging-service/${pax.logging.version}</bundle>
+ <bundle start-level="10">mvn:org.apache.karaf.service/org.apache.karaf.service.guard/${project.version}</bundle>
<bundle start-level="10">mvn:org.apache.felix/org.apache.felix.configadmin/${felix.configadmin.version}</bundle>
<bundle start-level="11">mvn:org.apache.felix/org.apache.felix.fileinstall/${felix.fileinstall.version}</bundle>
<bundle start-level="20">mvn:org.ow2.asm/asm-all/${asm.version}</bundle>
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/itests/src/test/java/org/apache/karaf/itests/KarafTestSupport.java
----------------------------------------------------------------------
diff --git a/itests/src/test/java/org/apache/karaf/itests/KarafTestSupport.java b/itests/src/test/java/org/apache/karaf/itests/KarafTestSupport.java
index 06a8810..19c7d1c 100644
--- a/itests/src/test/java/org/apache/karaf/itests/KarafTestSupport.java
+++ b/itests/src/test/java/org/apache/karaf/itests/KarafTestSupport.java
@@ -13,6 +13,7 @@
*/
package org.apache.karaf.itests;
+import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.maven;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
@@ -107,6 +108,7 @@ public class KarafTestSupport {
* @return
*/
protected String executeCommand(final String command, final Long timeout, final Boolean silent) {
+ waitForCommandService(command);
String response;
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final PrintStream printStream = new PrintStream(byteArrayOutputStream);
@@ -139,6 +141,48 @@ public class KarafTestSupport {
return response;
}
+ private void waitForCommandService(String command) {
+ // the commands are represented by services. Due to the asynchronous nature of services they may not be
+ // immediately available. This code waits the services to be available, in their secured form. It
+ // means that the code waits for the command service to appear with the roles defined.
+
+ if (command == null || command.length() == 0) {
+ return;
+ }
+
+ int spaceIdx = command.indexOf(' ');
+ if (spaceIdx > 0) {
+ command = command.substring(0, spaceIdx);
+ }
+ int colonIndx = command.indexOf(':');
+
+ try {
+ if (colonIndx > 0) {
+ String scope = command.substring(0, colonIndx);
+ String function = command.substring(colonIndx + 1);
+ waitForService("(&(osgi.command.scope=" + scope + ")(osgi.command.function=" + function + ")(org.apache.karaf.service.guard.roles=*))", SERVICE_TIMEOUT);
+ } else {
+ waitForService("(&(osgi.command.function=" + command + ")(org.apache.karaf.service.guard.roles=*))", SERVICE_TIMEOUT);
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void waitForService(String filter, long timeout) throws InvalidSyntaxException,
+ InterruptedException {
+
+ ServiceTracker st = new ServiceTracker(bundleContext,
+ bundleContext.createFilter(filter),
+ null);
+
+ try {
+ st.open();
+ st.waitForService(timeout);
+ } finally {
+ st.close();
+ }
+ }
protected <T> T getOsgiService(Class<T> type, long timeout) {
return getOsgiService(type, null, timeout);
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/management/server/pom.xml
----------------------------------------------------------------------
diff --git a/management/server/pom.xml b/management/server/pom.xml
index 7003102..b933a1b 100644
--- a/management/server/pom.xml
+++ b/management/server/pom.xml
@@ -64,6 +64,11 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.apache.karaf.service</groupId>
+ <artifactId>org.apache.karaf.service.guard</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
<groupId>org.easymock</groupId>
<artifactId>easymockclassextension</artifactId>
<version>${easymock.version}</version>
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 1430e72..14baf41 100644
--- a/pom.xml
+++ b/pom.xml
@@ -54,6 +54,7 @@
<module>demos</module>
<module>tooling</module>
<module>archetypes</module>
+ <module>service</module>
<module>diagnostic</module>
<module>itests</module>
</modules>
@@ -503,6 +504,11 @@
<version>${project.version}</version>
</dependency>
<dependency>
+ <groupId>org.apache.karaf.service</groupId>
+ <artifactId>org.apache.karaf.service.guard</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
<groupId>org.apache.karaf.webconsole</groupId>
<artifactId>org.apache.karaf.webconsole.console</artifactId>
<version>${project.version}</version>
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/service/guard/NOTICE
----------------------------------------------------------------------
diff --git a/service/guard/NOTICE b/service/guard/NOTICE
new file mode 100644
index 0000000..b70f1f9
--- /dev/null
+++ b/service/guard/NOTICE
@@ -0,0 +1,71 @@
+Apache Karaf
+Copyright 2010-2014 The Apache Software Foundation
+
+
+I. Included Software
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
+Licensed under the Apache License 2.0.
+
+This product uses software developed at
+The OSGi Alliance (http://www.osgi.org/).
+Copyright (c) OSGi Alliance (2000, 2010).
+Licensed under the Apache License 2.0.
+
+This product includes software developed at
+OW2 (http://www.ow2.org/).
+Licensed under the BSD License.
+
+This product includes software developed at
+OPS4J (http://www.ops4j.org/).
+Licensed under the Apache License 2.0.
+
+This product includes software developed at
+Eclipse Foundation (http://www.eclipse.org/).
+Licensed under the EPL.
+
+This product includes software written by
+Antony Lesuisse.
+Licensed under Public Domain.
+
+
+II. Used Software
+
+This product uses software developed at
+FUSE Source (http://www.fusesource.org/).
+Licensed under the Apache License 2.0.
+
+This product uses software developed at
+AOP Alliance (http://aopalliance.sourceforge.net/).
+Licensed under the Public Domain.
+
+This product uses software developed at
+Tanuki Software (http://www.tanukisoftware.com/).
+Licensed under the Apache License 2.0.
+
+This product uses software developed at
+Jasypt (http://jasypt.sourceforge.net/).
+Licensed under the Apache License 2.0.
+
+This product uses software developed at
+JLine (http://jline.sourceforge.net).
+Licensed under the BSD License.
+
+This product uses software developed at
+SLF4J (http://www.slf4j.org/).
+Licensed under the MIT License.
+
+This product uses software developed at
+SpringSource (http://www.springsource.org/).
+Licensed under the Apache License 2.0.
+
+This product includes software from http://www.json.org.
+Copyright (c) 2002 JSON.org
+
+
+III. License Summary
+- Apache License 2.0
+- BSD License
+- EPL License
+- MIT License
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/service/guard/pom.xml
----------------------------------------------------------------------
diff --git a/service/guard/pom.xml b/service/guard/pom.xml
new file mode 100644
index 0000000..3fdbb9e
--- /dev/null
+++ b/service/guard/pom.xml
@@ -0,0 +1,115 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<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">
+
+ <!--
+
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF 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.
+ -->
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.karaf.service</groupId>
+ <artifactId>service</artifactId>
+ <version>2.4.0-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>org.apache.karaf.service.guard</artifactId>
+ <packaging>bundle</packaging>
+ <name>Apache Karaf :: Service :: Guard</name>
+ <description>Adds role-based access control to OSGi services</description>
+
+ <properties>
+ <appendedResourcesDirectory>${basedir}/../../etc/appended-resources</appendedResourcesDirectory>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.aries.proxy</groupId>
+ <artifactId>org.apache.aries.proxy.api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.karaf.jaas</groupId>
+ <artifactId>org.apache.karaf.jaas.boot</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.compendium</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.aries.proxy</groupId>
+ <artifactId>org.apache.aries.proxy.impl</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ow2.asm</groupId>
+ <artifactId>asm-all</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-nop</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <includes>
+ <include>**/*</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.info</include>
+ </includes>
+ </resource>
+ </resources>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <configuration>
+ <instructions>
+ <Bundle-Activator>org.apache.karaf.service.guard.impl.Activator</Bundle-Activator>
+ <Export-Package>org.apache.karaf.service.guard.tools</Export-Package>
+ <Private-Package>org.apache.karaf.service.guard.impl</Private-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/service/guard/src/main/java/org/apache/karaf/service/guard/impl/Activator.java
----------------------------------------------------------------------
diff --git a/service/guard/src/main/java/org/apache/karaf/service/guard/impl/Activator.java b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/Activator.java
new file mode 100644
index 0000000..ea067db
--- /dev/null
+++ b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/Activator.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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 org.apache.karaf.service.guard.impl;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Filter;
+import org.osgi.framework.hooks.service.EventListenerHook;
+import org.osgi.framework.hooks.service.FindHook;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+// This bundle is quite low-level and benefits from starting early in the process. Therefore it does not depend
+// on Blueprint but rather uses direct OSGi framework APIs and Service Trackers ...
+public class Activator implements BundleActivator {
+
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+
+ GuardingEventHook guardingEventHook;
+ GuardingFindHook guardingFindHook;
+ GuardProxyCatalog guardProxyCatalog;
+
+ @Override
+ public void start(BundleContext bundleContext) throws Exception {
+ String f = System.getProperty(GuardProxyCatalog.KARAF_SECURED_SERVICES_SYSPROP);
+ Filter securedServicesFilter;
+ if (f == null) {
+ // no services need to be secured
+ logger.info("No role-based security for services as its system property is not set: {}", GuardProxyCatalog.KARAF_SECURED_SERVICES_SYSPROP);
+ return;
+ } else {
+ securedServicesFilter = bundleContext.createFilter(f);
+ logger.info("Adding role-based security to services with filter: {}", f);
+ }
+
+ guardProxyCatalog = new GuardProxyCatalog(bundleContext);
+
+ guardingEventHook = new GuardingEventHook(bundleContext, guardProxyCatalog, securedServicesFilter);
+ bundleContext.registerService(EventListenerHook.class, guardingEventHook, null);
+
+ guardingFindHook = new GuardingFindHook(bundleContext, guardProxyCatalog, securedServicesFilter);
+ bundleContext.registerService(FindHook.class, guardingFindHook, null);
+
+ }
+
+ @Override
+ public void stop(BundleContext bundleContext) throws Exception {
+ if (guardProxyCatalog != null) {
+ guardProxyCatalog.close();
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardProxyCatalog.java
----------------------------------------------------------------------
diff --git a/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardProxyCatalog.java b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardProxyCatalog.java
new file mode 100644
index 0000000..92e0ec6
--- /dev/null
+++ b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardProxyCatalog.java
@@ -0,0 +1,598 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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 org.apache.karaf.service.guard.impl;
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.regex.Pattern;
+
+import javax.security.auth.Subject;
+
+import org.apache.aries.proxy.InvocationListener;
+import org.apache.aries.proxy.ProxyManager;
+import org.apache.aries.proxy.UnableToProxyException;
+import org.apache.karaf.jaas.boot.principal.RolePrincipal;
+import org.apache.karaf.service.guard.tools.ACLConfigurationParser;
+import org.apache.karaf.service.guard.tools.ACLConfigurationParser.Specificity;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.framework.Filter;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceEvent;
+import org.osgi.framework.ServiceFactory;
+import org.osgi.framework.ServiceListener;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.cm.Configuration;
+import org.osgi.service.cm.ConfigurationAdmin;
+import org.osgi.util.tracker.ServiceTracker;
+import org.osgi.util.tracker.ServiceTrackerCustomizer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class GuardProxyCatalog implements ServiceListener {
+ public static final String KARAF_SECURED_SERVICES_SYSPROP = "karaf.secured.services";
+ public static final String SERVICE_GUARD_ROLES_PROPERTY = "org.apache.karaf.service.guard.roles";
+
+ static final String PROXY_CREATOR_THREAD_NAME = "Secure OSGi Service Proxy Creator";
+ static final String PROXY_SERVICE_KEY = "." + GuardProxyCatalog.class.getName(); // The only currently used value is Boolean.TRUE
+ static final String SERVICE_ACL_PREFIX = "org.apache.karaf.service.acl.";
+ static final String SERVICE_GUARD_KEY = "service.guard";
+ static final Logger LOG = LoggerFactory.getLogger(GuardProxyCatalog.class);
+
+ private static final Pattern JAVA_METHOD_NAME_PATTERN = Pattern.compile("[a-zA-Z_$][a-zA-Z0-9_$]*");
+ private static final String ROLE_WILDCARD = "*";
+
+ private final BundleContext myBundleContext;
+
+ final ServiceTracker<ConfigurationAdmin, ConfigurationAdmin> configAdminTracker;
+ final ServiceTracker<ProxyManager, ProxyManager> proxyManagerTracker;
+ final ConcurrentMap<Long, ServiceRegistrationHolder> proxyMap = new ConcurrentHashMap<Long, ServiceRegistrationHolder>();
+ final BlockingQueue<CreateProxyRunnable> createProxyQueue = new LinkedBlockingQueue<CreateProxyRunnable>();
+
+ // These two variables control the proxy creator thread, which is started as soon as a ProxyManager Service
+ // becomes available.
+ volatile boolean runProxyCreator = true;
+ volatile Thread proxyCreatorThread = null;
+
+ GuardProxyCatalog(BundleContext bc) throws Exception {
+ LOG.trace("Starting GuardProxyCatalog");
+ myBundleContext = bc;
+
+ // The service listener is used to update/unregister proxies if the backing service changes/goes away
+ bc.addServiceListener(this);
+
+ Filter caFilter = getNonProxyFilter(bc, ConfigurationAdmin.class);
+ LOG.trace("Creating Config Admin Tracker using filter {}", caFilter);
+ configAdminTracker = new ServiceTracker<ConfigurationAdmin, ConfigurationAdmin>(bc, caFilter, null);
+ configAdminTracker.open();
+
+ Filter pmFilter = getNonProxyFilter(bc, ProxyManager.class);
+ LOG.trace("Creating Proxy Manager Tracker using filter {}", pmFilter);
+ proxyManagerTracker = new ServiceTracker<ProxyManager, ProxyManager>(bc, pmFilter, new ServiceProxyCreatorCustomizer());
+ proxyManagerTracker.open();
+ }
+
+ static Filter getNonProxyFilter(BundleContext bc, Class<?> clazz) throws InvalidSyntaxException {
+ Filter caFilter = bc.createFilter(
+ "(&(" + Constants.OBJECTCLASS + "=" + clazz.getName() +
+ ")(!(" + PROXY_SERVICE_KEY + "=*)))");
+ return caFilter;
+ }
+
+ void close() {
+ LOG.trace("Stopping GuardProxyCatalog");
+ stopProxyCreator();
+ proxyManagerTracker.close();
+ configAdminTracker.close();
+
+ myBundleContext.removeServiceListener(this);
+
+ // Remove all proxy registrations
+ for (ServiceRegistrationHolder holder : proxyMap.values()) {
+ ServiceRegistration<?> reg = holder.registration;
+ if (reg != null) {
+ LOG.info("Unregistering proxy service of {} with properties {}",
+ reg.getReference().getProperty(Constants.OBJECTCLASS), copyProperties(reg.getReference()));
+ reg.unregister();
+ }
+ }
+ proxyMap.clear();
+ }
+
+ @Override
+ public void serviceChanged(ServiceEvent event) {
+ // This method is to ensure that proxied services follow the original service. I.e. if the original service
+ // goes away the proxies should go away too. If the original service is modified, the proxies should be
+ // modified accordingly
+
+ ServiceReference<?> sr = event.getServiceReference();
+ if (event.getType() == ServiceEvent.REGISTERED) {
+ // Nothing to do for new services
+ return;
+ }
+
+ if (isProxy(sr)) {
+ // Ignore proxies, we only react to real service changes
+ return;
+ }
+
+ Long orgServiceID = (Long) sr.getProperty(Constants.SERVICE_ID);
+ if (event.getType() == ServiceEvent.UNREGISTERING) {
+ handleOriginalServiceUnregistering(orgServiceID);
+ }
+
+ if ((event.getType() & (ServiceEvent.MODIFIED | ServiceEvent.MODIFIED_ENDMATCH)) > 0) {
+ handleOriginalServiceModifed(orgServiceID, sr);
+ }
+ }
+
+ private void handleOriginalServiceUnregistering(Long orgServiceID) {
+ // If the service queued up to be proxied, remove it.
+ for (Iterator<CreateProxyRunnable> i = createProxyQueue.iterator(); i.hasNext(); ) {
+ CreateProxyRunnable cpr = i.next();
+ if (orgServiceID.equals(cpr.getOriginalServiceID())) {
+ i.remove();
+ }
+ }
+
+ ServiceRegistrationHolder holder = proxyMap.remove(orgServiceID);
+ if (holder != null) {
+ if (holder.registration != null) {
+ holder.registration.unregister();
+ }
+ }
+ }
+
+ private void handleOriginalServiceModifed(Long orgServiceID, ServiceReference<?> orgServiceRef) {
+ // We don't need to do anything for services that are queued up to be proxied, as the
+ // properties are only taken at the point of proxyfication...
+
+ ServiceRegistrationHolder holder = proxyMap.get(orgServiceID);
+ if (holder != null) {
+ ServiceRegistration<?> reg = holder.registration;
+ if (reg != null) {
+ // Preserve the roles as they are expensive to compute
+ Object roles = reg.getReference().getProperty(SERVICE_GUARD_ROLES_PROPERTY);
+ Dictionary<String, Object> newProxyProps = proxyProperties(orgServiceRef);
+ if (roles != null) {
+ newProxyProps.put(SERVICE_GUARD_ROLES_PROPERTY, roles);
+ } else {
+ newProxyProps.remove(SERVICE_GUARD_ROLES_PROPERTY);
+ }
+ reg.setProperties(newProxyProps);
+ }
+ }
+ }
+
+ boolean isProxy(ServiceReference<?> sr) {
+ return sr.getProperty(PROXY_SERVICE_KEY) != null;
+ }
+
+ // Called by hooks to find out whether the service should be hidden.
+ // Also handles the proxy creation of services if applicable.
+ // Return true if the hook should hide the service for the bundle
+ boolean handleProxificationForHook(ServiceReference<?> sr) {
+ // Note that when running under an OSGi R6 framework the number of proxies created
+ // can be limited by looking at the new 'service.scope' property. If the value is
+ // 'singleton' then the same proxy can be shared across all clients.
+ // Pre OSGi R6 it is not possible to find out whether a service is backed by a
+ // Service Factory, so we assume that every service is.
+
+ if (isProxy(sr)) {
+ return false;
+ }
+
+ proxyIfNotAlreadyProxied(sr); // Note does most of the work async
+ return true;
+ }
+
+ void proxyIfNotAlreadyProxied(final ServiceReference<?> originalRef) {
+ final long orgServiceID = (Long) originalRef.getProperty(Constants.SERVICE_ID);
+
+ // make sure it's on the map before the proxy is registered, as that can trigger
+ // another call into this method, and we need to make sure that it doesn't proxy
+ // the service again.
+ final ServiceRegistrationHolder registrationHolder = new ServiceRegistrationHolder();
+ ServiceRegistrationHolder previousHolder = proxyMap.putIfAbsent(orgServiceID, registrationHolder);
+ if (previousHolder != null) {
+ // There is already a proxy for this service
+ return;
+ }
+
+ LOG.trace("Will create proxy of service {}({})", originalRef.getProperty(Constants.OBJECTCLASS), orgServiceID);
+
+ // Instead of immediately creating the proxy, we add the code that creates the proxy to the proxyQueue.
+ // This means that we can better react to the fact that the ProxyManager service might arrive
+ // later. As soon as the Proxy Manager is available, the queue is emptied and the proxies created.
+ CreateProxyRunnable cpr = new CreateProxyRunnable() {
+ @Override
+ public long getOriginalServiceID() {
+ return orgServiceID;
+ }
+
+ @Override
+ public void run(final ProxyManager pm) throws Exception {
+ String[] objectClassProperty = (String[]) originalRef.getProperty(Constants.OBJECTCLASS);
+ ServiceFactory<Object> sf = new ProxyServiceFactory(pm, originalRef);
+ registrationHolder.registration = originalRef.getBundle().getBundleContext().registerService(
+ objectClassProperty, sf, proxyPropertiesRoles());
+
+ Dictionary<String, Object> actualProxyProps = copyProperties(registrationHolder.registration.getReference());
+ LOG.debug("Created proxy of service {} under {} with properties {}",
+ orgServiceID, actualProxyProps.get(Constants.OBJECTCLASS), actualProxyProps);
+ }
+
+ private Dictionary<String, Object> proxyPropertiesRoles() throws Exception {
+ Dictionary<String, Object> p = proxyProperties(originalRef);
+
+ Set<String> roles = getServiceInvocationRoles(originalRef);
+ if (roles != null) {
+ roles.remove(ROLE_WILDCARD); // we don't expose that on the service property
+ p.put(SERVICE_GUARD_ROLES_PROPERTY, roles);
+ } else {
+ // In this case there are no roles defined for the service so anyone can invoke it
+ p.remove(SERVICE_GUARD_ROLES_PROPERTY);
+ }
+ return p;
+ }
+ };
+
+ try {
+ createProxyQueue.put(cpr);
+ } catch (InterruptedException e) {
+ LOG.warn("Problem scheduling a proxy creator for service {}({})",
+ originalRef.getProperty(Constants.OBJECTCLASS), orgServiceID, e);
+ e.printStackTrace();
+ }
+ }
+
+ private static Dictionary<String, Object> proxyProperties(ServiceReference<?> sr) {
+ Dictionary<String, Object> p = copyProperties(sr);
+ p.put(PROXY_SERVICE_KEY, Boolean.TRUE);
+ return p;
+ }
+
+ private static Dictionary<String, Object> copyProperties(ServiceReference<?> sr) {
+ Dictionary<String, Object> p = new Hashtable<String, Object>();
+
+ for (String key : sr.getPropertyKeys()) {
+ p.put(key, sr.getProperty(key));
+ }
+ return p;
+ }
+
+ // Returns what roles can possibly ever invoke this service. Note that not every invocation may be successful
+ // as there can be different roles for different methods and also roles based on arguments passed in.
+ Set<String> getServiceInvocationRoles(ServiceReference<?> serviceReference) throws Exception {
+ boolean definitionFound = false;
+ Set<String> allRoles = new HashSet<String>();
+
+ // This can probably be optimized. Maybe we can cache the config object relevant instead of
+ // walking through all of the ones that have 'service.guard'.
+ for (Configuration config : getServiceGuardConfigs()) {
+ Object guardFilter = config.getProperties().get(SERVICE_GUARD_KEY);
+ if (guardFilter instanceof String) {
+ Filter filter = myBundleContext.createFilter((String) guardFilter);
+ if (filter.match(serviceReference)) {
+ definitionFound = true;
+ for (Enumeration<String> e = config.getProperties().keys(); e.hasMoreElements(); ) {
+ String key = e.nextElement();
+ String bareKey = key;
+ int idx = bareKey.indexOf('(');
+ if (idx >= 0) {
+ bareKey = bareKey.substring(0, idx);
+ }
+ int idx1 = bareKey.indexOf('[');
+ if (idx1 >= 0) {
+ bareKey = bareKey.substring(0, idx1);
+ }
+ int idx2 = bareKey.indexOf('*');
+ if (idx2 >= 0) {
+ bareKey = bareKey.substring(0, idx2);
+ }
+ if (!isValidMethodName(bareKey)) {
+ continue;
+ }
+ Object value = config.getProperties().get(key);
+ if (value instanceof String) {
+ allRoles.addAll(ACLConfigurationParser.parseRoles((String) value));
+ }
+ }
+ }
+ }
+ }
+ return definitionFound ? allRoles : null;
+ }
+
+ // Ensures that it never returns null
+ private Configuration[] getServiceGuardConfigs() throws IOException, InvalidSyntaxException {
+ ConfigurationAdmin ca = null;
+ try {
+ ca = configAdminTracker.waitForService(5000);
+ } catch (InterruptedException e) {
+ }
+ if (ca == null) {
+ throw new IllegalStateException("Role based access for services requires the OSGi Configuration Admin Service to be present");
+ }
+
+ Configuration[] configs = ca.listConfigurations(
+ "(&(" + Constants.SERVICE_PID + "=" + SERVICE_ACL_PREFIX + "*)(" + SERVICE_GUARD_KEY + "=*))");
+ if (configs == null) {
+ return new Configuration [] {};
+ }
+ return configs;
+ }
+
+ private boolean isValidMethodName(String name) {
+ return JAVA_METHOD_NAME_PATTERN.matcher(name).matches();
+ }
+
+ void stopProxyCreator() {
+ runProxyCreator = false; // Will end the proxy creation thread
+ if (proxyCreatorThread != null) {
+ proxyCreatorThread.interrupt();
+ }
+ }
+
+ static boolean currentUserHasRole(String reqRole) {
+ if (ROLE_WILDCARD.equals(reqRole)) {
+ return true;
+ }
+
+ String clazz;
+ String role;
+ int idx = reqRole.indexOf(':');
+ if (idx > 0) {
+ clazz = reqRole.substring(0, idx);
+ role = reqRole.substring(idx + 1);
+ } else {
+ clazz = RolePrincipal.class.getName();
+ role = reqRole;
+ }
+
+ AccessControlContext acc = AccessController.getContext();
+ if (acc == null) {
+ return false;
+ }
+
+ Subject subject = Subject.getSubject(acc);
+ if (subject == null) {
+ return false;
+ }
+
+ for (Principal p : subject.getPrincipals()) {
+ if (clazz.equals(p.getClass().getName()) && role.equals(p.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ static class ServiceRegistrationHolder {
+ volatile ServiceRegistration<?> registration;
+ }
+
+ class ProxyServiceFactory implements ServiceFactory<Object> {
+ private final ProxyManager pm;
+ private final ServiceReference<?> originalRef;
+
+ ProxyServiceFactory(ProxyManager pm, ServiceReference<?> originalRef) {
+ this.pm = pm;
+ this.originalRef = originalRef;
+ }
+
+ @Override
+ public Object getService(Bundle bundle, ServiceRegistration<Object> registration) {
+ Set<Class<?>> allClasses = new HashSet<Class<?>>();
+
+ // This needs to be done on the Client BundleContext since the bundle might be backed by a Service Factory
+ // in which case it needs to be given a chance to produce the right service for this client.
+ Object svc = bundle.getBundleContext().getService(originalRef);
+ Class<?> curClass = svc.getClass();
+ while (!Object.class.equals(curClass)) {
+ allClasses.add(curClass);
+ allClasses.addAll(Arrays.asList(curClass.getInterfaces()));
+ curClass = curClass.getSuperclass(); // Collect super types too
+ }
+
+ for (Iterator<Class<?>> i = allClasses.iterator(); i.hasNext(); ) {
+ Class<?> cls = i.next();
+ if (((cls.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0) ||
+ ((cls.getModifiers() & Modifier.FINAL) > 0) ||
+ cls.isAnonymousClass() || cls.isLocalClass()) {
+ // Do not attempt to proxy private, package-default, final, anonymous or local classes
+ i.remove();
+ } else {
+ for (Method m : cls.getDeclaredMethods()) {
+ if ((m.getModifiers() & Modifier.FINAL) > 0) {
+ // If the class contains final methods, don't attempt to proxy it
+ i.remove();
+ break;
+ }
+ }
+ }
+ }
+
+ InvocationListener il = new ProxyInvocationListener(originalRef);
+ try {
+ return pm.createInterceptingProxy(originalRef.getBundle(), allClasses, svc, il);
+ } catch (UnableToProxyException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void ungetService(Bundle bundle, ServiceRegistration<Object> registration, Object service) {
+ bundle.getBundleContext().ungetService(originalRef);
+ }
+ }
+
+ class ProxyInvocationListener implements InvocationListener {
+ private final ServiceReference<?> serviceReference;
+
+ ProxyInvocationListener(ServiceReference<?> sr) {
+ this.serviceReference = sr;
+ }
+
+ @Override
+ public Object preInvoke(Object proxy, Method m, Object[] args) throws Throwable {
+ String[] sig = new String[m.getParameterTypes().length];
+ for (int i = 0; i < m.getParameterTypes().length; i++) {
+ sig[i] = m.getParameterTypes()[i].getName();
+ }
+
+ // The ordering of the keys is important because the first value when iterating has the highest specificity
+ TreeMap<Specificity, List<String>> roleMappings = new TreeMap<ACLConfigurationParser.Specificity, List<String>>();
+ boolean foundMatchingConfig = false;
+
+ // This can probably be optimized. Maybe we can cache the config object relevant instead of
+ // walking through all of the ones that have 'service.guard'.
+ for (Configuration config : getServiceGuardConfigs()) {
+ Object guardFilter = config.getProperties().get(SERVICE_GUARD_KEY);
+ if (guardFilter instanceof String) {
+ Filter filter = myBundleContext.createFilter((String) guardFilter);
+ if (filter.match(serviceReference)) {
+ foundMatchingConfig = true;
+ List<String> roles = new ArrayList<String>();
+ Specificity s = ACLConfigurationParser.
+ getRolesForInvocation(m.getName(), args, sig, config.getProperties(), roles);
+ if (s != Specificity.NO_MATCH) {
+ roleMappings.put(s, roles);
+ if (s == Specificity.ARGUMENT_MATCH) {
+ // No more specific mapping can be found
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if (!foundMatchingConfig) {
+ // No mappings for this service, anyone can invoke
+ return null;
+ }
+
+ if (roleMappings.size() == 0) {
+ LOG.info("Service {} has role mapping, but assigned no roles to method {}", serviceReference, m);
+ throw new SecurityException("Insufficient credentials.");
+ }
+
+ // The first entry on the map has the highest significance because the keys are sorted in the order of
+ // the Specificity enum.
+ List<String> allowedRoles = roleMappings.values().iterator().next();
+ for (String role : allowedRoles) {
+ if (currentUserHasRole(role)) {
+ LOG.trace("Allow user with role {} to invoke service {} method {}", role, serviceReference, m);
+ return null;
+ }
+ }
+
+ // The current user does not have the required roles to invoke the service.
+ LOG.info("Current user does not have required roles ({}) for service {} method {} and/or arguments",
+ allowedRoles, serviceReference, m);
+ throw new SecurityException("Insufficient credentials.");
+ }
+
+
+ @Override
+ public void postInvokeExceptionalReturn(Object token, Object proxy, Method m, Throwable exception) throws Throwable {
+ }
+
+ @Override
+ public void postInvoke(Object token, Object proxy, Method m, Object returnValue) throws Throwable {
+ }
+ }
+
+ // This customizer comes into action as the ProxyManager service arrives.
+ class ServiceProxyCreatorCustomizer implements ServiceTrackerCustomizer<ProxyManager, ProxyManager> {
+ @Override
+ public ProxyManager addingService(ServiceReference<ProxyManager> reference) {
+ runProxyCreator = true;
+ final ProxyManager svc = myBundleContext.getService(reference);
+ if (proxyCreatorThread == null && svc != null) {
+ proxyCreatorThread = newProxyProducingThread(svc);
+ }
+ return svc;
+ }
+
+ private Thread newProxyProducingThread(final ProxyManager proxyManager) {
+ Thread t = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ while (runProxyCreator) {
+ CreateProxyRunnable proxyCreator = null;
+ try {
+ proxyCreator = createProxyQueue.take(); // take waits until there is something on the queue
+ } catch (InterruptedException ie) {
+ // part of normal behaviour
+ }
+
+ if (proxyCreator != null) {
+ try {
+ proxyCreator.run(proxyManager);
+ } catch (Exception e) {
+ LOG.warn("Problem creating secured service proxy", e);
+ }
+ }
+ }
+ // finished running
+ proxyCreatorThread = null;
+ }
+ });
+ t.setName(PROXY_CREATOR_THREAD_NAME);
+ t.setDaemon(true);
+ t.start();
+
+ return t;
+ }
+
+ @Override
+ public void modifiedService(ServiceReference<ProxyManager> reference, ProxyManager service) {
+ // no need to react
+ }
+
+ @Override
+ public void removedService(ServiceReference<ProxyManager> reference, ProxyManager service) {
+ stopProxyCreator();
+ }
+ }
+
+ interface CreateProxyRunnable {
+ long getOriginalServiceID();
+ void run(ProxyManager pm) throws Exception;
+ }
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardingEventHook.java
----------------------------------------------------------------------
diff --git a/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardingEventHook.java b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardingEventHook.java
new file mode 100644
index 0000000..a37e863
--- /dev/null
+++ b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardingEventHook.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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 org.apache.karaf.service.guard.impl;
+
+import org.osgi.framework.*;
+import org.osgi.framework.hooks.service.EventListenerHook;
+import org.osgi.framework.hooks.service.ListenerHook;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+
+public class GuardingEventHook implements EventListenerHook {
+
+ private final BundleContext bundleContext;
+ private final GuardProxyCatalog guardProxyCatalog;
+ private final Filter servicesFilter;
+
+ GuardingEventHook(BundleContext bundleContext, GuardProxyCatalog guardProxyCatalog, Filter securedServicesFilter) throws InvalidSyntaxException {
+ this.bundleContext = bundleContext;
+ this.guardProxyCatalog = guardProxyCatalog;
+ this.servicesFilter = securedServicesFilter;
+ }
+
+ @Override
+ public void event(ServiceEvent event, Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners) {
+ if (servicesFilter == null) {
+ return;
+ }
+
+ ServiceReference<?> sr = event.getServiceReference();
+ if (!servicesFilter.match(sr)) {
+ return;
+ }
+
+ for (Iterator<BundleContext> i = listeners.keySet().iterator(); i.hasNext(); ) {
+ BundleContext bc = i.next();
+ if (bundleContext.equals(bc) || bc.getBundle().getBundleId() == 0L) {
+ // don't hide anything from this bundle or the system bundle
+ continue;
+ }
+
+ if (guardProxyCatalog.handleProxificationForHook(sr)) {
+ i.remove();
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardingFindHook.java
----------------------------------------------------------------------
diff --git a/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardingFindHook.java b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardingFindHook.java
new file mode 100644
index 0000000..bf1497c
--- /dev/null
+++ b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardingFindHook.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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 org.apache.karaf.service.guard.impl;
+
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Filter;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.hooks.service.FindHook;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+public class GuardingFindHook implements FindHook {
+
+ private final BundleContext bundleContext;
+ private final GuardProxyCatalog guardProxyCatalog;
+ private final Filter servicesFilter;
+
+ GuardingFindHook(BundleContext bundleContext, GuardProxyCatalog guardProxyCatalog, Filter securedServicesFilter) {
+ this.bundleContext = bundleContext;
+ this.guardProxyCatalog = guardProxyCatalog;
+ this.servicesFilter = securedServicesFilter;
+ }
+
+ public void find(BundleContext bundleContext, String name, String filter, boolean allServices, Collection<ServiceReference<?>> references) {
+ if (servicesFilter == null) {
+ return;
+ }
+
+ if (this.bundleContext.equals(bundleContext) || bundleContext.getBundle().getBundleId() == 0) {
+ // don't hide anything from this bundle or the system bundle
+ return;
+ }
+
+ for (Iterator<ServiceReference<?>> i = references.iterator(); i.hasNext(); ) {
+ ServiceReference<?> sr = i.next();
+
+ if (!servicesFilter.match(sr)) {
+ continue;
+ }
+
+ if (guardProxyCatalog.handleProxificationForHook(sr)) {
+ i.remove();
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/service/guard/src/main/java/org/apache/karaf/service/guard/tools/ACLConfigurationParser.java
----------------------------------------------------------------------
diff --git a/service/guard/src/main/java/org/apache/karaf/service/guard/tools/ACLConfigurationParser.java b/service/guard/src/main/java/org/apache/karaf/service/guard/tools/ACLConfigurationParser.java
new file mode 100644
index 0000000..5a5af3e
--- /dev/null
+++ b/service/guard/src/main/java/org/apache/karaf/service/guard/tools/ACLConfigurationParser.java
@@ -0,0 +1,337 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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 org.apache.karaf.service.guard.tools;
+
+import java.util.*;
+
+public class ACLConfigurationParser {
+
+ // note that the order of the enums is important. Needs to be from most specific to least specific.
+ public enum Specificity {
+ ARGUMENT_MATCH,
+ SIGNATURE_MATCH,
+ NAME_MATCH,
+ WILDCARD_MATCH,
+ NO_MATCH
+ };
+
+ /**
+ * Returns the roles that can invoke the given operation. This is determined by matching the
+ * operation details against configuration provided.<p/>
+ *
+ * The following configuration is supported. Keys are used to match an invocation against. The value can contain
+ * a comma-separated list of roles. Spaces are ignored for the role values. Note that comments are allowed in the
+ * value field after the hash {@code #} character:
+ * <pre>
+ * {@code
+ * myMethod = role1, role2
+ * methodName(int)[/17/] = role1 # regex match, assume it's surrounded by ^ and $
+ * methodName(int)[/[01]8/] = role2
+ * methodName(int)["19"] = role3 # exact value match
+ * methodName(int) = role4 # signature match
+ * methodName(java.lang.String, int) = role5 # signature match
+ * methodName = # no roles can invoke this command
+ * method* = role6 # name prefix/wildcard match. The asterisk must appear at the end.
+ * }
+ * </pre>
+ *
+ * The following algorithm is used to find matching roles:
+ * <ol>
+ * <li>Find all regex and exact value matches. For all parameters these matches are found by calling {@code toString()}
+ * on the parameters passed in. If there are multiple matches in this category all the matching roles are collected.
+ * If any is found return these roles.
+ * </li>
+ * <li>Find a signature match. If found return the associated roles.</li>
+ * <li>Find a method name match. If found return the associated roles.</li>
+ * <li>Find a method name prefix/wildcard match. If more than one prefix match, the roles associated with the longest
+ * prefix is used. So for example, if there are rules for {@code get*} and {@code *} only the roles associated with
+ * {@code get*} are returned.
+ * </li>
+ * <li>If none of the above criteria match, this method returns {@code null}.</li>
+ * </ol>
+ *
+ * @param methodName the method name to be invoked.
+ * @param params the parameters provided for the invocation. May be {@code null} for cases there the parameters are not yet
+ * known. In this case the roles that can <em>potentially</em> invoke the method are returned, although based on
+ * parameter values the actual invocation may still be denied.
+ * @param signature the signature of the method specified as an array of class name. For simple types, the simple type name
+ * is used (e.g. "int").
+ * @param config the configuration to check against.
+ * @param addToRoles the list of roles (which may be empty) if a matching configuration iteam has been found.
+ * @return the specificity
+ */
+ public static Specificity getRolesForInvocation(String methodName, Object[] params, String[] signature,
+ Dictionary<String, Object> config, List<String> addToRoles) {
+ Dictionary<String, Object> properties = trimKeys(config);
+
+ Specificity s = getRolesBasedOnSignature(methodName, params, signature, properties, addToRoles);
+ if (s != Specificity.NO_MATCH) {
+ return s;
+ }
+
+ s = getRolesBasedOnSignature(methodName, params, null, properties, addToRoles);
+ if (s != Specificity.NO_MATCH) {
+ return s;
+ }
+
+ List<String> roles = getMethodNameWildcardRoles(properties, methodName);
+ if (roles != null) {
+ addToRoles.addAll(roles);
+ return Specificity.WILDCARD_MATCH;
+ } else {
+ return Specificity.NO_MATCH;
+ }
+ }
+
+ private static Specificity getRolesBasedOnSignature(String methodName, Object[] params, String[] signature,
+ Dictionary<String, Object> properties, List<String> roles) {
+ if (params != null) {
+ boolean foundExactOrRegex = false;
+ Object exactArgMatchRoles = properties.get(getExactArgSignature(methodName, signature, params));
+ if (exactArgMatchRoles instanceof String) {
+ roles.addAll(parseRoles((String) exactArgMatchRoles));
+ foundExactOrRegex = true;
+ }
+
+ List<String> r = getRegexRoles(properties, methodName, signature, params);
+ if (r != null) {
+ foundExactOrRegex = true;
+ roles.addAll(r);
+ }
+
+ if (foundExactOrRegex) {
+ // since we have the actual parameters we can match them and if they do we won't look for any
+ // more generic rules...
+ return Specificity.ARGUMENT_MATCH;
+ }
+ } else {
+ // this is used in the case where parameters aren't known yet and the system wants to find out
+ // what roles in principle can invoke this method
+ List<String> r = getExactArgOrRegexRoles(properties, methodName, signature);
+ if (r != null) {
+ roles.addAll(r);
+ }
+ }
+
+ Object signatureRoles = properties.get(getSignature(methodName, signature));
+ if (signatureRoles instanceof String) {
+ roles.addAll(parseRoles((String) signatureRoles));
+ return signature == null ? Specificity.NAME_MATCH : Specificity.SIGNATURE_MATCH;
+ }
+
+ return Specificity.NO_MATCH;
+ }
+
+ private static Dictionary<String, Object> trimKeys(Dictionary<String, Object> properties) {
+ Dictionary<String, Object> d = new Hashtable<String, Object>();
+ for (Enumeration<String> e = properties.keys(); e.hasMoreElements(); ) {
+ String key = e.nextElement();
+ Object value = properties.get(key);
+ d.put(removeSpaces(key), value);
+ }
+ return d;
+ }
+
+ private static String removeSpaces(String key) {
+ StringBuilder sb = new StringBuilder();
+ char quoteChar = 0;
+ for (int i = 0; i < key.length(); i++) {
+ char c = key.charAt(i);
+
+ if (quoteChar == 0 && c == ' ')
+ continue;
+
+ if (quoteChar == 0 && (c == '\"' || c == '/') && sb.length() > 0 &&
+ (sb.charAt(sb.length() - 1) == '[' || sb.charAt(sb.length() - 1) == ',')) {
+ // we're in a quoted string
+ quoteChar = c;
+ } else if (quoteChar != 0 && c == quoteChar) {
+ // look ahead to see if the next non-space is the closing bracket or a comma, which ends the quoted string
+ for (int j = i + 1; j < key.length(); j++) {
+ if (key.charAt(j) == ' ')
+ continue;
+ if (key.charAt(j) == ']' || key.charAt(j) == ',')
+ quoteChar = 0;
+ break;
+ }
+ }
+ sb.append(c);
+ }
+ return sb.toString();
+ }
+
+ public static List<String> parseRoles(String roleStr) {
+ int hashIdx = roleStr.indexOf('#');
+ if (hashIdx >= 0) {
+ // you can put a comment at the end
+ roleStr = roleStr.substring(0, hashIdx);
+ }
+
+ List<String> roles = new ArrayList<String>();
+ for (String role : roleStr.split("[,]")) {
+ String trimmed = role.trim();
+ if (trimmed.length() > 0) {
+ roles.add(trimmed);
+ }
+ }
+
+ return roles;
+ }
+
+ private static Object getExactArgSignature(String methodName, String[] signature, Object[] params) {
+ StringBuilder sb = new StringBuilder(getSignature(methodName, signature));
+ sb.append('[');
+ boolean first = true;
+ for (Object param : params) {
+ if (first)
+ first = false;
+ else
+ sb.append(',');
+ sb.append('"');
+ if (param != null)
+ sb.append(param.toString().trim());
+ sb.append('"');
+ }
+ sb.append(']');
+ return sb.toString();
+ }
+
+ private static String getSignature(String methodName, String[] signature) {
+ StringBuilder sb = new StringBuilder(methodName);
+ if (signature == null)
+ return sb.toString();
+
+ sb.append('(');
+ boolean first = true;
+ for (String s : signature) {
+ if (first)
+ first = false;
+ else
+ sb.append(',');
+ sb.append(s);
+ }
+ sb.append(')');
+ return sb.toString();
+ }
+
+ private static List<String> getRegexRoles(Dictionary<String, Object> properties, String methodName, String[] signature, Object[] params) {
+ List<String> roles = new ArrayList<String>();
+ boolean matchFound = false;
+ String methodSig = getSignature(methodName, signature);
+ String prefix = methodSig + "[/";
+ for (Enumeration<String> e = properties.keys(); e.hasMoreElements(); ) {
+ String key = e.nextElement().trim();
+ if (key.startsWith(prefix) && key.endsWith("/]")) {
+ List<String> regexArgs = getRegexDecl(key.substring(methodSig.length()));
+ if (allParamsMatch(regexArgs, params)) {
+ matchFound = true;
+ Object roleStr = properties.get(key);
+ if (roleStr instanceof String) {
+ roles.addAll(parseRoles((String) roleStr));
+ }
+ }
+ }
+ }
+ return matchFound ? roles : null;
+ }
+
+ private static List<String> getExactArgOrRegexRoles(Dictionary<String, Object> properties, String methodName, String[] signature) {
+ List<String> roles = new ArrayList<String>();
+ boolean matchFound = false;
+ String methodSig = getSignature(methodName, signature);
+ String prefix = methodSig + "[";
+ for (Enumeration<String> e = properties.keys(); e.hasMoreElements(); ) {
+ String key = e.nextElement().trim();
+ if (key.startsWith(prefix) && key.endsWith("]")) {
+ matchFound = true;
+ Object roleStr = properties.get(key);
+ if (roleStr instanceof String) {
+ roles.addAll(parseRoles((String) roleStr));
+ }
+ }
+ }
+ return matchFound ? roles : null;
+ }
+
+ private static List<String> getMethodNameWildcardRoles(Dictionary<String, Object> properties, String methodName) {
+ SortedMap<String, String> wildcardRules = new TreeMap<String, String>(new Comparator<String>() {
+ public int compare(String s1, String s2) {
+ // returns longer entries before shorter ones...
+ return s2.length() - s1.length();
+ }
+ });
+ for (Enumeration<String> e = properties.keys(); e.hasMoreElements(); ) {
+ String key = e.nextElement();
+ if (key.endsWith("*")) {
+ String prefix = key.substring(0, key.length() - 1);
+ if (methodName.startsWith(prefix)) {
+ wildcardRules.put(prefix, properties.get(key).toString());
+ }
+ }
+ }
+
+ if (wildcardRules.size() != 0) {
+ return parseRoles(wildcardRules.values().iterator().next());
+ } else {
+ return null;
+ }
+ }
+
+ private static boolean allParamsMatch(List<String> regexArgs, Object[] params) {
+ if (regexArgs.size() != params.length)
+ return false;
+
+ for (int i = 0; i < regexArgs.size(); i++) {
+ if (params[i] == null)
+ return false;
+ if (!params[i].toString().trim().matches(regexArgs.get(i))) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static List<String> getRegexDecl(String key) {
+ List<String> l = new ArrayList<String>();
+
+ boolean inRegex = false;
+ StringBuilder curRegex = new StringBuilder();
+ for (int i = 0; i < key.length(); i++) {
+ if (!inRegex) {
+ if (key.length() > i + 1) {
+ String s = key.substring(i, i + 2);
+ if ("[/".equals(s) || ",/".equals(s)) {
+ inRegex = true;
+ i++;
+ continue;
+ }
+ }
+ } else {
+ String s = key.substring(i, i + 2);
+ if ("/]".equals(s) || "/,".equals(s)) {
+ l.add(curRegex.toString());
+ curRegex = new StringBuilder();
+ inRegex = false;
+ continue;
+ }
+ curRegex.append(key.charAt(i));
+ }
+ }
+ return l;
+ }
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/service/guard/src/main/resources/OSGI-INF/bundle.info
----------------------------------------------------------------------
diff --git a/service/guard/src/main/resources/OSGI-INF/bundle.info b/service/guard/src/main/resources/OSGI-INF/bundle.info
new file mode 100644
index 0000000..be2ec64
--- /dev/null
+++ b/service/guard/src/main/resources/OSGI-INF/bundle.info
@@ -0,0 +1,53 @@
+h1. Synopsis
+
+${project.name}
+
+${project.description}
+
+Maven URL:
+ [mvn:${project.groupId}/${project.artifactId}/${project.version}]
+
+h1. Description
+
+Add Role-based access to any OSGi Service
+
+Role-based access is added to existing OSGi services by hiding the
+original service from a clients through service registry hooks and
+presenting a proxy to the service that checks the required roles before
+an invocation is made.
+
+To enable the Role-based access for services, the service needs to match
+the filter in the karaf.secured.services system property (typically set
+in etc/system.properties), e.g:
+
+ karaf.secured.services = (|(objectClass=org.acme*)(foo=bar))
+
+Only services that match this filter have Role-based access applied,
+other services are left alone.
+
+Required roles are registered through the OSGi Configuration Admin
+Service. The service PID must start with org.apache.karaf.service.acl.
+For enabled services configurations with matching PIDs defining a
+service.guard property that matches are looked up.
+Then roles associated with the current method, its signature and/or the
+passed arguments are looked up. For example, take the following
+configuration:
+
+ service.guard = (objectClass=org.acme.MyServiceAPI)
+ myMethod = admin, manager
+
+A special role declaration of '*' means that role checking is disabled
+for this method.
+If a matching ACL is found, but no matching definition for the method
+being invoked can be found, no user can invoke the method.
+If no matching ACL is found, role checking is not enabled for the
+service.
+As with the role-based JMX access, method signatures and arguments
+(either literal or regex-based) can be matched.
+
+When roles are checked, these are obtained from the Subject associated
+with the current AccessControlContext. By default the Karaf
+RolePrincipal is checked for, but other role implementations can be
+supported through the following syntax:
+
+ my.custom.RoleImpl:someRole
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/karaf/blob/4b8cc102/service/guard/src/test/java/org/apache/karaf/service/guard/impl/ActivatorTest.java
----------------------------------------------------------------------
diff --git a/service/guard/src/test/java/org/apache/karaf/service/guard/impl/ActivatorTest.java b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/ActivatorTest.java
new file mode 100644
index 0000000..9670eb3
--- /dev/null
+++ b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/ActivatorTest.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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 org.apache.karaf.service.guard.impl;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import org.easymock.EasyMock;
+import org.easymock.IAnswer;
+import org.junit.Test;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Filter;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.hooks.service.EventListenerHook;
+import org.osgi.framework.hooks.service.FindHook;
+
+import java.util.Dictionary;
+import java.util.Properties;
+
+public class ActivatorTest {
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testStartActivator() throws Exception {
+ // keep the old properties. Note that the Properties 'copy constructor' new Properties(props)
+ // doesn't actually copy, hence the awkward setup here...
+ Properties oldProps = new Properties();
+ oldProps.putAll(System.getProperties());
+
+ try {
+ System.setProperty(GuardProxyCatalog.KARAF_SECURED_SERVICES_SYSPROP, "(foo=bar)");
+ Bundle b = EasyMock.createMock(Bundle.class);
+ EasyMock.expect(b.getBundleId()).andReturn(768L).anyTimes();
+ EasyMock.replay(b);
+
+ BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
+ EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes();
+ EasyMock.expect(bc.createFilter(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Filter>() {
+ @Override
+ public Filter answer() throws Throwable {
+ return FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]);
+ }
+ }).anyTimes();
+
+ EasyMock.expect(bc.registerService(
+ EasyMock.eq(EventListenerHook.class), EasyMock.isA(EventListenerHook.class), EasyMock.isNull(Dictionary.class)))
+ .andReturn(null);
+ EasyMock.expect(bc.registerService(
+ EasyMock.eq(FindHook.class), EasyMock.isA(FindHook.class), EasyMock.isNull(Dictionary.class)))
+ .andReturn(null);
+
+ EasyMock.replay(bc);
+
+ Activator a = new Activator();
+ a.start(bc);
+
+ assertNotNull(a.guardProxyCatalog);
+ assertNotNull(a.guardingEventHook);
+ assertNotNull(a.guardingFindHook);
+
+ EasyMock.verify(bc);
+ } finally {
+ System.setProperties(oldProps);
+ }
+ }
+
+ @Test
+ public void testStartActivatorNoServicesSecured() throws Exception {
+ // keep the old properties. Note that the Properties 'copy constructor' new Properties(props)
+ // doesn't actually copy, hence the awkward setup here...
+ Properties oldProps = new Properties();
+ oldProps.putAll(System.getProperties());
+
+ try {
+ Properties newProps = removeProperties(System.getProperties(), GuardProxyCatalog.KARAF_SECURED_SERVICES_SYSPROP);
+ System.setProperties(newProps);
+
+ BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
+ EasyMock.replay(bc);
+
+ Activator a = new Activator();
+ a.start(bc);
+
+ assertNull(a.guardProxyCatalog);
+ } finally {
+ System.setProperties(oldProps);
+ }
+ }
+
+ @Test
+ public void testStopActivator() throws Exception {
+ Activator a = new Activator();
+
+ a.guardProxyCatalog = EasyMock.createMock(GuardProxyCatalog.class);
+ a.guardProxyCatalog.close();
+ EasyMock.expectLastCall().once();
+ EasyMock.replay(a.guardProxyCatalog);
+
+ a.stop(EasyMock.createMock(BundleContext.class));
+
+ EasyMock.verify(a.guardProxyCatalog);
+ }
+
+ private Properties removeProperties(Properties props, String ... keys) {
+ Properties p = new Properties();
+ p.putAll(props);
+ for (String key : keys) {
+ p.remove(key);
+ }
+ return p;
+ }
+
+}