Author: bblfish
Date: Fri Apr  1 13:12:07 2011
New Revision: 1087694

URL: http://svn.apache.org/viewvc?rev=1087694&view=rev
Log:
Merge branch 'CLEREZZA-479'

Added:
    
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala
    
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala
Removed:
    
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/Utilities.scala
Modified:
    
incubator/clerezza/trunk/parent/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala
    
incubator/clerezza/trunk/parent/platform.security.auth.basic/src/main/java/org/apache/clerezza/platform/security/auth/basic/BasicAuthentication.java
    
incubator/clerezza/trunk/parent/platform.security.auth.cookie/src/main/java/org/apache/clerezza/platform/security/auth/cookie/CookieAuthentication.java
    incubator/clerezza/trunk/parent/platform.security.foafssl/core/pom.xml
    
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/resources/OSGI-INF/serviceComponents.xml
    
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala
    
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala
    
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala
    incubator/clerezza/trunk/parent/platform.security.foafssl/test/pom.xml
    
incubator/clerezza/trunk/parent/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/testservlets/TestMe.scala
    
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/UserUtil.java
    
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticatingFilter.java
    
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticationMethod.java
    
incubator/clerezza/trunk/parent/platform.users/core/src/main/resources/OSGI-INF/serviceComponents.xml
    
incubator/clerezza/trunk/parent/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala

Modified: 
incubator/clerezza/trunk/parent/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala
 Fri Apr  1 13:12:07 2011
@@ -68,6 +68,7 @@ class AbstractPermission(val accountName
                        case _ => false
            }
 
+  //todo: the hashes for same named account names of different types would be 
the same here
        override
        def hashCode: Int = {
                return  41 * (41 + (if (accountName != null) 
accountName.hashCode else 0))

Modified: 
incubator/clerezza/trunk/parent/platform.security.auth.basic/src/main/java/org/apache/clerezza/platform/security/auth/basic/BasicAuthentication.java
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.auth.basic/src/main/java/org/apache/clerezza/platform/security/auth/basic/BasicAuthentication.java?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security.auth.basic/src/main/java/org/apache/clerezza/platform/security/auth/basic/BasicAuthentication.java
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security.auth.basic/src/main/java/org/apache/clerezza/platform/security/auth/basic/BasicAuthentication.java
 Fri Apr  1 13:12:07 2011
@@ -23,6 +23,8 @@ import java.io.IOException;
 import java.nio.channels.Channels;
 import java.nio.channels.ReadableByteChannel;
 import java.security.AccessControlException;
+import java.util.Collections;
+
 import org.osgi.service.component.ComponentContext;
 import org.apache.clerezza.platform.security.auth.*;
 import org.apache.felix.scr.annotations.Component;
@@ -37,6 +39,8 @@ import org.wymiwyg.wrhapi.Response;
 import org.wymiwyg.wrhapi.ResponseStatus;
 import org.wymiwyg.wrhapi.util.MessageBody2Read;
 
+import javax.security.auth.Subject;
+
 /**
  *
  * @author mir
@@ -60,7 +64,7 @@ public class BasicAuthentication impleme
        }
 
        @Override
-       public String authenticate(Request request) throws LoginException, 
HandlerException {
+       public Subject authenticate(Request request) throws LoginException, 
HandlerException {
                String[] authorizationValues = 
request.getHeaderValues(HeaderName.AUTHORIZATION);
                if (authorizationValues != null && authorizationValues.length > 
0) {
                        String authorization = authorizationValues[0];
@@ -75,7 +79,10 @@ public class BasicAuthentication impleme
                        }
                        try {
                                if 
(authenticationService.authenticateUser(userName, password)) {
-                                       return userName;
+                                       return new Subject(true,
+                                               Collections.singleton(new 
PrincipalImpl(userName)),
+                                               Collections.EMPTY_SET,
+                                               Collections.EMPTY_SET);
                                } else {
                                        throw new 
LoginException(LoginException.PASSWORD_NOT_MATCHING);
                                }

Modified: 
incubator/clerezza/trunk/parent/platform.security.auth.cookie/src/main/java/org/apache/clerezza/platform/security/auth/cookie/CookieAuthentication.java
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.auth.cookie/src/main/java/org/apache/clerezza/platform/security/auth/cookie/CookieAuthentication.java?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security.auth.cookie/src/main/java/org/apache/clerezza/platform/security/auth/cookie/CookieAuthentication.java
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security.auth.cookie/src/main/java/org/apache/clerezza/platform/security/auth/cookie/CookieAuthentication.java
 Fri Apr  1 13:12:07 2011
@@ -21,10 +21,9 @@ package org.apache.clerezza.platform.sec
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
 import java.security.AccessControlException;
-import java.util.Arrays;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
+import java.security.Principal;
+import java.util.*;
+import javax.security.auth.Subject;
 import javax.ws.rs.core.Cookie;
 import org.osgi.service.component.ComponentContext;
 import org.apache.clerezza.platform.security.auth.*;
@@ -69,7 +68,7 @@ public class CookieAuthentication implem
        }
 
        @Override
-       public String authenticate(Request request) throws LoginException, 
HandlerException {
+       public Subject authenticate(Request request) throws LoginException, 
HandlerException {
                String[] cookieValues = 
request.getHeaderValues(HeaderName.COOKIE);
                if (cookieValues != null && cookieValues.length > 0) {
                        Map<String, Cookie> cookies = 
parseCookies(cookieValues[0]);            
@@ -89,7 +88,10 @@ public class CookieAuthentication implem
                        }
                        try {
                                if 
(authenticationService.authenticateUser(userName, password)){
-                                       return userName;
+                                       return new Subject(true,
+                                               Collections.singleton(new 
PrincipalImpl(userName)),
+                                               Collections.EMPTY_SET,
+                                               Collections.EMPTY_SET);
                                } else {
                                        throw new 
LoginException(LoginException.PASSWORD_NOT_MATCHING);
                                }

Modified: incubator/clerezza/trunk/parent/platform.security.foafssl/core/pom.xml
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.foafssl/core/pom.xml?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- incubator/clerezza/trunk/parent/platform.security.foafssl/core/pom.xml 
(original)
+++ incubator/clerezza/trunk/parent/platform.security.foafssl/core/pom.xml Fri 
Apr  1 13:12:07 2011
@@ -45,7 +45,7 @@
                </dependency>
         <dependency>
             <groupId>org.apache.clerezza</groupId>
-            <artifactId>rdf.web.proxy.core</artifactId>
+            <artifactId>platform.users.core</artifactId>
         </dependency>
                <dependency>
                        <groupId>javax.ws.rs</groupId>

Modified: 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/resources/OSGI-INF/serviceComponents.xml
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/resources/OSGI-INF/serviceComponents.xml?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/resources/OSGI-INF/serviceComponents.xml
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/resources/OSGI-INF/serviceComponents.xml
 Fri Apr  1 13:12:07 2011
@@ -11,16 +11,16 @@
                <service servicefactory="false">
                        <provide 
interface="org.apache.clerezza.platform.security.auth.WeightedAuthenticationMethod"/>
                </service>
+        <reference name="webIdService" 
interface="org.apache.clerezza.platform.users.WebIdGraphsService"
+        cardinality="1..1" policy="static" bind="bindWebIdService" 
unbind="unbindWebIdService"/>
+        <reference name="systemGraph" 
interface="org.apache.clerezza.rdf.core.access.LockableMGraph"
+        cardinality="1..1" policy="static" 
target="(name=http://tpf.localhost/system.graph)"
+        bind="bindSystemGraph" unbind="unbindSystemGraph"/>
        </scr:component>
        <scr:component enabled="true" 
name="org.apache.clerezza.foafssl.ssl.X509TrustManagerWrapperService">
                <implementation 
class="org.apache.clerezza.foafssl.ssl.X509TrustManagerWrapperService"/>
                <service servicefactory="false">
                        <provide 
interface="org.apache.clerezza.foafssl.ssl.X509TrustManagerWrapperService"/>
                </service>
-               <reference name="webProxy" 
interface="org.apache.clerezza.rdf.web.proxy.WebProxy"
-               cardinality="1..1" policy="static" bind="bindWebProxy" 
unbind="unbindWebProxy"/>
-               <reference name="systemGraph" 
interface="org.apache.clerezza.rdf.core.access.LockableMGraph" 
-               cardinality="1..1" policy="static" 
target="(name=http://tpf.localhost/system.graph)" 
-               bind="bindSystemGraph" unbind="unbindSystemGraph"/>
        </scr:component>
 </components>

Modified: 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala
 Fri Apr  1 13:12:07 2011
@@ -19,11 +19,36 @@
 
 package org.apache.clerezza.foafssl.auth
 
-import org.apache.clerezza.foafssl.Utilities
 import org.apache.clerezza.platform.security.auth._
 import org.apache.clerezza.rdf.core._
+import access.LockableMGraph
+import impl.{TripleImpl, PlainLiteralImpl, SimpleMGraph}
 import org.wymiwyg.wrhapi.Request
 import org.wymiwyg.wrhapi.Response
+import javax.security.auth.Subject
+import org.apache.clerezza.platform.Constants
+import org.apache.clerezza.rdf.ontologies.{FOAF, RDF, PLATFORM}
+import org.apache.clerezza.platform.users.WebIdGraphsService
+import org.slf4j.LoggerFactory
+import java.util.Collections
+
+
+object FoafSslAuthentication {
+  final private val logger = 
LoggerFactory.getLogger(classOf[FoafSslAuthentication])
+
+  final val ANONYMOUS: String = "anonymous"
+
+  def createSystemUserDescription(claim: WebIDClaim): MGraph = {
+    val result = new SimpleMGraph()
+    result.add(new TripleImpl(claim.webId, PLATFORM.userName,
+      new PlainLiteralImpl(claim.userName)))
+    result.add(new TripleImpl(claim.webId, RDF.`type`,
+      FOAF.Agent))
+    result
+  }
+
+
+}
 
 
 /**
@@ -32,28 +57,67 @@ import org.wymiwyg.wrhapi.Response
  */
 class FoafSslAuthentication extends WeightedAuthenticationMethod {
 
-       
-       def authenticate(request: Request): String = {
-               val certificates = request.getCertificates()
-               if ((certificates == null) || (certificates.length == 0)) {
-                       return null
-               } else {
-                       //TODO: not all the WebIDs below may have been verified 
(in cases of multiple SANs)
-                       //in fact we only currently verify the first, but as 
soon as we verify more then
-                       //a solution will need to be put in place for this.
-                       val webIdUriRefs = 
Utilities.getClaimedWebIds(certificates)
-                       if (webIdUriRefs.size > 0) {
-                               return 
Utilities.createUsernameForWebId(webIdUriRefs(0))
-                       } else {
-                               return null
-                       }
-               }
-       }
-
-       def writeLoginResponse(request: Request, response: Response,
-                       cause: Throwable) = {
-               false;
-       }
+  import FoafSslAuthentication._
+  import collection.JavaConversions._
+
+
+  override
+  def authenticate(request: Request): Subject = {
+    val certificates = request.getCertificates()
+    if ((certificates == null) || (certificates.length == 0)) {
+      return null
+    }
+    val x509c = new X509Claim(certificates(0))
+    x509c.verify(this)
+
+    val verified = for (claim <- x509c.webidclaims;
+         if (claim.verified == Verification.Verified) ) yield {
+      addAgentToSystem(claim)
+      claim.principal
+    }
+
+    return new Subject(true,
+      asJavaSet(verified.toSet),
+      Collections.singleton(x509c),
+      Collections.EMPTY_SET);
+
+
+  }
+
+  def addAgentToSystem(id: WebIDClaim) {
+    systemGraph.addAll(createSystemUserDescription(id))
+  }
+
+  //todo: perhaps this makes more sense now that the verification has moved up 
higher
+  def writeLoginResponse(request: Request, response: Response,
+                         cause: Throwable) = {
+    false;
+  }
+
+  def getWeight() = 400
+
+  protected[auth] var webIdSrvc: WebIdGraphsService = null;
+
+  protected def bindWebIdService(webcache: WebIdGraphsService) = {
+    this.webIdSrvc = webcache
+  }
+
+  protected def unbindWebIdService(webcache: WebIdGraphsService) = {
+    this.webIdSrvc = null
+  }
+
+  private var systemGraph: MGraph = null
+
+  protected def bindSystemGraph(g: LockableMGraph) {
+    systemGraph = g
+  }
+
+  protected def unbindSystemGraph(g: LockableMGraph) {
+    systemGraph = null
+  }
+
+
+  private val systemGraphUri = Constants.SYSTEM_GRAPH_URI;
+
 
-       def getWeight() = 400
 }

Added: 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala?rev=1087694&view=auto
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala
 (added)
+++ 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala
 Fri Apr  1 13:12:07 2011
@@ -0,0 +1,185 @@
+/*
+ * 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.clerezza.foafssl.auth
+
+import java.security.interfaces.RSAPublicKey
+import java.security.cert.CertificateException
+import java.io.ByteArrayOutputStream
+import org.apache.clerezza.rdf.core.serializedform.{SupportedFormat, 
Serializer}
+import org.apache.clerezza.rdf.utils.GraphNode
+import org.apache.clerezza.foafssl.ontologies.{RSA, CERT}
+import org.apache.clerezza.rdf.web.proxy.Cache
+import java.util.LinkedList
+import org.apache.clerezza.rdf.core._
+import org.apache.clerezza.rdf.scala.utils.Preamble._
+import java.security.PublicKey
+import org.apache.clerezza.platform.security.auth.PrincipalImpl
+
+
+/**
+ * An X509 Claim maintains information about the proofs associated with claims
+ * found in an X509 Certificate. It is the type of object that can be passed
+ * into the public credentials part of a Subject node
+ *
+ * todo: think of what this would look like for a chain of certificates
+ *
+ * @author hjs
+ * @created 30/03/2011
+ */
+class WebIDClaim(val webId: UriRef, val key: PublicKey) {
+
+  import X509Claim._
+
+  val errors = new LinkedList[Throwable]()
+
+  lazy val principal = new PrincipalImpl(userName)
+  var verified = Verification.Unverified
+
+ /*private lazy val selectQuery = {
+        val query = """PREFIX cert: <http://www.w3.org/ns/auth/cert#>
+        PREFIX rsa: <http://www.w3.org/ns/auth/rsa#>
+        SELECT ?m ?e ?mod ?exp
+        WHERE {
+        [] cert:identity ?webid ;
+        rsa:modulus ?m ;
+        rsa:public_exponent ?e .
+        OPTIONAL { ?m cert:hex ?mod . }
+        OPTIONAL { ?e cert:decimal ?exp . }
+        }"""
+        queryParser.parse(query).asInstanceOf[SelectQuery]
+        }*/
+
+  //todo: not at all a satisfactory username method. Find something better.
+  lazy val userName = for (c <- webId.getUnicodeString) yield
+      c match {
+        case ':' => '_';
+        case '#' => '_';
+        case '/' => '_';
+        case _ => c
+      }
+
+  /**
+   * verify this claim
+   * @param authSrvc: the authentication service contains information about 
where to get graphs
+   */
+  //todo: make this asynchronous
+  def verify(authSrvc: FoafSslAuthentication)  {
+    try {
+      var webIdInfo = authSrvc.webIdSrvc.getWebIDInfo(webId, Cache.CacheOnly)
+      if (
+        !verify(webIdInfo.publicUserGraph)
+      ) {
+        webIdInfo = authSrvc.webIdSrvc.getWebIDInfo(webId, Cache.ForceUpdate)
+        if (
+          !verify(webIdInfo.publicUserGraph)
+        ) {
+          verified = Verification.Failed
+          return
+        }
+      }
+    } catch {
+      case e => {
+        errors.add(e)
+        verified = Verification.Failed
+        return
+      }
+    }
+    verified = Verification.Verified
+  }
+
+  def verify(tc: TripleCollection): Boolean = {
+    key match {
+      case k: RSAPublicKey => verify(k, tc);
+      case _ => throw new CertificateException("Unsupported key format")
+    }
+  }
+
+  private def verify(publicKey: RSAPublicKey, tc: TripleCollection): Boolean = 
{
+    val publicKeysInGraph = getPublicKeysInGraph(tc)
+    val publicKeyTuple = (new BigInt(publicKey.getModulus), new 
BigInt(publicKey.getPublicExponent))
+    val result = publicKeysInGraph.contains(publicKeyTuple)
+    if (logger.isDebugEnabled) {
+      if (!result) {
+        val baos = new ByteArrayOutputStream
+        Serializer.getInstance.serialize(baos, tc, SupportedFormat.TURTLE);
+        logger.debug("no matching key in: \n{}", new String(baos.toByteArray));
+        logger.debug("the public key is not among the " +
+          publicKeysInGraph.size + " keys in the profile graph of size " +
+          tc.size)
+        logger.debug("PublicKey: " + publicKeyTuple)
+        publicKeysInGraph.foreach(k => logger.debug("PublikKey in graph: " + 
k))
+      }
+    }
+    result
+  }
+
+  private def getPublicKeysInGraph(tc: TripleCollection): Array[(BigInt, 
BigInt)] = {
+    import scala.collection.JavaConversions._
+    val publicKeys = for (t <- tc.filter(null, CERT.identity, webId)) yield {
+      t.getSubject
+    }
+    (for (p <- publicKeys) yield {
+      val node = new GraphNode(p, tc)
+      val modulusRes = node / RSA.modulus
+      val modulus = intValueOfResource(modulusRes) match {
+        case Some(x) => x
+        case _ => BigInt(0)
+      }
+      val exponentRes = node / RSA.public_exponent
+      val exponent = intValueOfResource(exponentRes) match {
+        case Some(x) => x
+        case _ => BigInt(0)
+      }
+      (modulus, exponent)
+    }).toArray
+  }
+
+
+
+  def canEqual(other: Any) = other.isInstanceOf[WebIDClaim]
+
+  override
+  def equals(other: Any): Boolean =
+    other match {
+      case that: WebIDClaim => (that eq this) || (that.canEqual(this) && webId 
== that.webId && key == that.key)
+      case _ => false
+    }
+
+  override
+  lazy val hashCode: Int = 41 * (
+      41 * (
+        41 + (if (webId != null) webId.hashCode else 0)
+        ) + (if (key != null) key.hashCode else 0)
+      )
+}
+
+object Verification extends Enumeration {
+
+       val Unverified = Value
+
+       val Verified = Value
+
+       val Failed = Value
+
+}
+
+
+
+

Added: 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala?rev=1087694&view=auto
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala
 (added)
+++ 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala
 Fri Apr  1 13:12:07 2011
@@ -0,0 +1,273 @@
+/*
+ * 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.clerezza.foafssl.auth
+
+import javax.security.auth.{RefreshFailedException, Refreshable}
+import java.security.cert.X509Certificate
+import org.slf4j.LoggerFactory
+import org.apache.clerezza.rdf.utils.GraphNode
+import org.apache.clerezza.foafssl.ontologies.{RSA, CERT}
+import java.util.Date
+import org.apache.clerezza.rdf.core._
+import java.math.BigInteger
+import org.apache.clerezza.platform.Constants
+import org.apache.clerezza.rdf.scala.utils.Preamble._
+
+/**
+ * An X509 Claim maintains information about the proofs associated with claims
+ * found in an X509 Certificate. It is the type of object that can be passed
+ * into the public credentials part of a Subject node
+ *
+ * todo: think of what this would look like for a chain of certificates
+ *
+ * @author hjs
+ * @created: 30/03/2011
+ */
+
+object X509Claim {
+  final val logger = LoggerFactory.getLogger(classOf[X509Claim])
+
+
+  private def intValueOfHexString(s: String): BigInt = {
+    val strval = cleanHex(s);
+    BigInt(strval, 16);
+  }
+
+
+  /**
+   * This takes any string and returns in order only those characters that are
+   * part of a hex string
+   *
+   * @param strval
+   *            any string
+   * @return a pure hex string
+   */
+
+  private def cleanHex(strval: String) = {
+    def legal(c: Char) = {
+      //in order of appearance probability
+      ((c >= '0') && (c <= '9')) ||
+        ((c >= 'A') && (c <= 'F')) ||
+        ((c >= 'a') && (c <= 'f'))
+    }
+    (for (c <- strval; if legal(c)) yield c)
+  }
+
+  /*private lazy val selectQuery = {
+   val query = """PREFIX cert: <http://www.w3.org/ns/auth/cert#>
+   PREFIX rsa: <http://www.w3.org/ns/auth/rsa#>
+   SELECT ?m ?e ?mod ?exp
+   WHERE {
+   [] cert:identity ?webid ;
+   rsa:modulus ?m ;
+   rsa:public_exponent ?e .
+   OPTIONAL { ?m cert:hex ?mod . }
+   OPTIONAL { ?e cert:decimal ?exp . }
+   }"""
+   queryParser.parse(query).asInstanceOf[SelectQuery]
+   }*/
+  /**
+   * gets the parts of key from rdf
+   * @return (mod, exp)
+   */
+  def getPublicKeysInGraph(webId: UriRef, tc: TripleCollection): 
Array[(BigInt, BigInt)] = {
+    import scala.collection.JavaConversions._
+    val publicKeys = for (t <- tc.filter(null, CERT.identity, webId)) yield {
+      t.getSubject
+    }
+    (for (p <- publicKeys) yield {
+      val node = new GraphNode(p, tc)
+      val modulusRes = node / RSA.modulus
+      val modulus = intValueOfResource(modulusRes) match {
+        case Some(x) => x
+        case _ => BigInt(0)
+      }
+      val exponentRes = node / RSA.public_exponent
+      val exponent = intValueOfResource(exponentRes) match {
+        case Some(x) => x
+        case _ => BigInt(0)
+      }
+      (modulus, exponent)
+    }).toArray
+  }
+
+  /**
+   * Extracts the URIs in the subject alternative name extension of an X.509
+   * certificate
+   *
+   * @param cert X.509 certificate from which to extract the URIs.
+   * @return Iterator of URIs as strings found in the subjectAltName extension.
+   */
+  def getClaimedWebIds(cert: X509Certificate): Iterator[String] = {
+    //           throws CertificateParsingException {
+    if (cert == null) {
+      return Iterator.empty;
+    }
+
+    val names = cert.getSubjectAlternativeNames()
+    if (names == null) {
+      return Iterator.empty;
+    }
+
+    return new Iterator[String]() {
+      val it = names.iterator
+      var nxt: String= getNext()
+
+      def hasNext(): Boolean =  nxt !=null;
+
+
+      def next(): String = {
+        val res = nxt
+        nxt = getNext
+        return res
+      }
+
+      def getNext(): String = {
+        while (it.hasNext) {
+          val altNme = it.next()
+          val altTpe = altNme.get(0);
+          val altObj = altNme.get(1);
+          if ((altTpe.asInstanceOf[Int] == 6) && altObj.isInstanceOf[String]) {
+            return altObj.asInstanceOf[String]
+          }
+        }
+        return null
+      }
+
+    }
+
+  }
+
+
+  /**
+   * @return the integer value if r is a typedLiteral of cert:hex or 
cert:decimal,
+   * otherwise the integer value of the  cert:hex or cert:decimal property of 
r or
+   * None if no such value available
+   */
+  def intValueOfResource(n: GraphNode): Option[BigInt] = {
+    n ! match {
+      case l: TypedLiteral => intValueOfTypedLiteral(l);
+      case r: Resource => intValueOfResourceByProperty(n)
+    }
+  }
+
+  def intValueOfResourceByProperty(n: GraphNode): Option[BigInt] = {
+    val hexValues = n / CERT.hex
+    if (hexValues.length > 0) {
+      return Some(intValueOfHexString(hexValues *))
+    }
+    val decimalValues = n / CERT.decimal
+    if (decimalValues.length > 0) {
+      return Some(BigInt(decimalValues *))
+    }
+    val intValues = n / CERT.int_
+    if (intValues.length > 0) {
+      return Some(BigInt(intValues *))
+    }
+    return None
+  }
+
+  def intValueOfLiteral(l: Literal): Option[BigInt] = {
+    l match {
+      case x: TypedLiteral => intValueOfTypedLiteral(x);
+      case x => Some(intValueOfHexString(x.getLexicalForm))
+    }
+  }
+
+  def intValueOfTypedLiteral(l: TypedLiteral): Option[BigInt] = {
+    try {
+      (l.getLexicalForm, l.getDataType) match {
+        case (lf, CERT.hex) => Some(intValueOfHexString(lf))
+        case (lf, CERT.decimal) => Some(BigInt(lf))
+        case (lf, CERT.int_) => Some(BigInt(lf))
+        case _ => Some(new 
BigInt(LiteralFactory.getInstance.createObject(classOf[BigInteger], l)))
+      }
+    } catch {
+      case e: NoConvertorException => None
+      case e => throw e
+    }
+  }
+
+
+  private
+  val systemGraphUri = Constants.SYSTEM_GRAPH_URI;
+
+}
+
+
+class X509Claim(val cert: X509Certificate) extends Refreshable {
+
+  import X509Claim._
+
+  /* a list of unverified principals */
+  lazy val webidclaims = getClaimedWebIds(cert).map {
+    str => {
+      val webid = new UriRef(str);
+      new WebIDClaim(webid, cert.getPublicKey)
+    }
+  }.toSet
+
+
+  //note could also implement Destroyable
+  //
+  
//http://download.oracle.com/javase/6/docs/technotes/guides/security/jaas/JAASRefGuide.html#Credentials
+  //
+  //if updating validity periods can also take into account the WebID 
reference, then it is possible
+  //that a refresh could have as consequence to do a fetch on the WebID profile
+  //note: one could also take the validity period to be dependent on the 
validity of the profile representation
+  //in which case updating the validity period would make more sense.
+
+  override
+  def refresh() {
+    throw new RefreshFailedException("refreshing validity period of x509 claim 
not defined and not implemented")
+  }
+
+  override
+  def isCurrent(): Boolean = {
+    val now = new Date();
+    if (now.after(cert.getNotAfter())) return false
+    if (now.before(cert.getNotBefore())) return false
+    return true;
+  }
+
+
+  /**verify all the webids in the X509 */
+  def verify(authService: FoafSslAuthentication) {
+    webidclaims foreach {
+      wid => wid.verify(authService)
+    }
+  }
+
+  def canEqual(other: Any) = other.isInstanceOf[X509Claim]
+
+  override
+  def equals(other: Any): Boolean =
+    other match {
+      case that: X509Claim => (that eq this) || (that.canEqual(this) && cert 
== that.cert)
+      case _ => false
+    }
+
+  override
+  lazy val hashCode: Int = 41 * (41 +
+    (if (cert != null) cert.hashCode else 0))
+
+
+}
+

Modified: 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala
 Fri Apr  1 13:12:07 2011
@@ -47,7 +47,8 @@ class Activator() {
       val http = 
bundleContext.getProperty("org.osgi.service.http.secure.enabled")
       if (http!=null && "true".equals(http)) {
         val sslContextFactory = new X509SSLContextFactory(
-                    getServerCertKeyStore(context), 
getKeyStorePassword(bundleContext),
+                    getServerCertKeyStore(context),
+                               getKeyStorePassword(bundleContext),
                     getServerCertKeyStore(context));//getCaKeyStore());
             sslContextFactory
                     .setTrustManagerWrapper(x509TrustManagerWrapperService);

Modified: 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala
 Fri Apr  1 13:12:07 2011
@@ -19,266 +19,52 @@
 
 package org.apache.clerezza.foafssl.ssl
 
-import java.io.ByteArrayOutputStream
-import java.math.BigInteger
-import java.security.PublicKey
 import java.security.cert.CertificateException
-import java.security.cert.CertificateExpiredException
-import java.security.cert.CertificateNotYetValidException
 import java.security.cert.X509Certificate
-import java.security.interfaces.RSAPublicKey
-import java.util.Date
 import javax.net.ssl.X509TrustManager;
-import org.apache.clerezza.foafssl.Utilities
-import org.apache.clerezza.foafssl.ontologies.CERT
-import org.apache.clerezza.foafssl.ontologies.RSA
-import org.apache.clerezza.platform.Constants
-import org.apache.clerezza.rdf.core.Literal
-import org.apache.clerezza.rdf.core.LiteralFactory
-import org.apache.clerezza.rdf.core.MGraph
-import org.apache.clerezza.rdf.core.NoConvertorException
-import org.apache.clerezza.rdf.core.Resource
-import org.apache.clerezza.rdf.core.TripleCollection
-import org.apache.clerezza.rdf.core.TypedLiteral
-import org.apache.clerezza.rdf.core.UriRef
-import org.apache.clerezza.rdf.core.access.LockableMGraph
-import org.apache.clerezza.rdf.core.access.TcManager
-import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl
-import org.apache.clerezza.rdf.core.impl.SimpleMGraph
-import org.apache.clerezza.rdf.core.impl.TripleImpl
-import org.apache.clerezza.rdf.core.serializedform.{Serializer, 
SupportedFormat}
-import org.apache.clerezza.rdf.utils._
-import org.apache.clerezza.rdf.scala.utils._
-import org.apache.clerezza.rdf.ontologies.FOAF
-import org.apache.clerezza.rdf.ontologies.PLATFORM
-import org.apache.clerezza.rdf.ontologies.RDF
-import org.apache.clerezza.rdf.scala.utils.Preamble._
 import org.jsslutils.sslcontext.X509TrustManagerWrapper
 import 
org.jsslutils.sslcontext.trustmanagers.TrustAllClientsWrappingTrustManager
 import org.slf4j.LoggerFactory
-import org.apache.clerezza.rdf.web.proxy.{WebProxy, Cache}
+import org.osgi.service.component.ComponentContext
+import org.apache.clerezza.foafssl.auth.X509Claim
 
-class X509TrustManagerWrapperService() extends X509TrustManagerWrapper {
 
+object X509TrustManagerWrapperService {
        private val logger = 
LoggerFactory.getLogger(classOf[X509TrustManagerWrapperService])
-       private var webproxy: WebProxy = null;
+}
 
-       protected def bindWebProxy(webcache: WebProxy) = {
-               this.webproxy = webcache
-       }
-       
-       protected def unbindWebProxy(webcache: WebProxy) = {
-               this.webproxy = null
-       }
-       
-       private var systemGraph: MGraph = null
-       
-       protected def bindSystemGraph(g: LockableMGraph) {
-               systemGraph = g
-       }
-       
-       protected def unbindSystemGraph(g: LockableMGraph) {
-               systemGraph = null
-       }
-       
-       override def wrapTrustManager(trustManager: X509TrustManager): 
X509TrustManager =  {
-               new TrustAllClientsWrappingTrustManager(
-                       trustManager) {
+
+class X509TrustManagerWrapperService() extends X509TrustManagerWrapper {
+
+       import X509TrustManagerWrapperService._
+
+       override def wrapTrustManager(trustManager: X509TrustManager): 
X509TrustManager = {
+
+               new TrustAllClientsWrappingTrustManager(trustManager) {
+
+                       //At this level we just check if there are webids
                        override def checkClientTrusted(chain: 
Array[X509Certificate], authType: String): Unit = {
                                try {
-                                       val webIdUriRefs = 
Utilities.getClaimedWebIds(chain)
-                                       if (webIdUriRefs.length == 0) {
+                                       val webIdUriRefs = 
X509Claim.getClaimedWebIds(chain(0))
+                                       if (webIdUriRefs.isEmpty) {
                                                
trustManager.checkClientTrusted(chain, authType)
-                                       } else {
-                                               val cert0 = chain(0)
-                                               val now = new Date();
-                                               if 
(now.after(cert0.getNotAfter()))
-                                                       throw new 
CertificateExpiredException(String.format("The certificate expires after %c . 
It is now %c . ", now, cert0.getNotAfter));
-                                               if 
(now.before(cert0.getNotBefore()))
-                                                       throw new 
CertificateNotYetValidException(String.format("The certificate is not valid 
before %c. It is now %c .", now, cert0.getNotBefore));
-                                               val publicKey = 
cert0.getPublicKey
-                                               for (uriRef <- webIdUriRefs) {
-                                                       verify(uriRef, 
publicKey)
-                                               }
                                        }
                                        return
+
                                } catch {
                                        //todo: this should be more clever, 
only displaying full stack trace if requested
                                        //todo: currently could be a denial of 
service attack - by filling up your hard drive
-                                       case ex: Throwable  => { 
-                                                       logger.info("can't 
check client",ex) 
-                                                       throw new 
CertificateException("cannot check client"+ex.getMessage);
-                                               }
-                               }
-                       }
-               }
-       }
-       
-       private val systemGraphUri = Constants.SYSTEM_GRAPH_URI;
-       
-       private def verify(webidClaim: UriRef, publicKey: PublicKey): Unit = {
-               var webIdInfo = webproxy.getResourceInfo(webidClaim, 
Cache.CacheOnly)
-               if (
-                       !verify(webidClaim, publicKey, webIdInfo.localCache)
-               ) {
-                       webIdInfo = webproxy.getResourceInfo(webidClaim, 
Cache.ForceUpdate)
-                       if (
-                               !verify(webidClaim, publicKey, 
webIdInfo.localCache)
-                       ) throw new CertificateException
-               }
-               systemGraph.addAll(createSystemUserDescription(webidClaim))
-       }
-       
-       def createSystemUserDescription(webId: UriRef): MGraph = {
-               val result = new SimpleMGraph()
-               result.add(new TripleImpl(webId, PLATFORM.userName,
-                                                                 new 
PlainLiteralImpl(Utilities.createUsernameForWebId(webId))))
-               result.add(new TripleImpl(webId, RDF.`type` , 
-                                                                 FOAF.Agent))
-               result
-       }
-       
-       /*private lazy val selectQuery = {
-        val query = """PREFIX cert: <http://www.w3.org/ns/auth/cert#>
-        PREFIX rsa: <http://www.w3.org/ns/auth/rsa#>
-        SELECT ?m ?e ?mod ?exp
-        WHERE {
-        [] cert:identity ?webid ;
-        rsa:modulus ?m ;
-        rsa:public_exponent ?e .
-        OPTIONAL { ?m cert:hex ?mod . }
-        OPTIONAL { ?e cert:decimal ?exp . }
-        }"""
-        queryParser.parse(query).asInstanceOf[SelectQuery]
-        }*/
-       /**
-        * gets the parts of key from rdf
-        * @return (mod, exp)
-        */
-       private def getPublicKeysInGraph(webId: UriRef, tc: TripleCollection): 
Array[(BigInt, BigInt)]= {
-               import scala.collection.JavaConversions._
-               val publicKeys = for (t <- tc.filter(null, CERT.identity, 
webId)) yield {
-                       t.getSubject
-               }
-               (for (p <- publicKeys) yield {
-                               val node = new GraphNode(p, tc)
-                               val modulusRes = node/RSA.modulus
-                               val modulus = intValueOfResource(modulusRes) 
match {
-                                       case Some(x) => x
-                                       case _ => BigInt(0)
-                               }
-                               val exponentRes = node/RSA.public_exponent
-                               val exponent = intValueOfResource(exponentRes) 
match {
-                                       case Some(x) => x
-                                       case _ => BigInt(0)
+                                       case ex: Throwable => {
+                                               logger.info("can't check 
client", ex)
+                                               throw new 
CertificateException("cannot check client" + ex.getMessage);
+                                       }
                                }
-                               (modulus, exponent)
-                       }).toArray
-       }
- 
-       
-       
-       /**
-        * todo: question should this perhaps be a 2 position method (pubkey, 
graphnode) ?
-        * @return true if the key could be verified
-        */
-       private def verify(webId: UriRef, publicKey: PublicKey, tc: 
TripleCollection): Boolean = {
-               publicKey match {
-                       case k: RSAPublicKey => verify(webId, k, tc);
-                       case _ => throw new CertificateException("Unsupported 
key format")
-               }
-       }
-        
-       private def verify(webId: UriRef, publicKey: RSAPublicKey, tc: 
TripleCollection): Boolean = {
-               val publicKeysInGraph = getPublicKeysInGraph(webId, tc)
-               val publicKeyTuple = (new BigInt(publicKey.getModulus), new 
BigInt(publicKey.getPublicExponent))
-               val result = publicKeysInGraph.contains(publicKeyTuple)
-               if (logger.isDebugEnabled) {
-                       if (!result) {
-                               val baos = new ByteArrayOutputStream
-                               Serializer.getInstance.serialize(baos, tc, 
SupportedFormat.TURTLE);
-                               logger.debug("no matching key in: \n{}", new 
String(baos.toByteArray));
-                               logger.debug("the public key is not among the "+
-                                                        
publicKeysInGraph.size+" keys in the profile graph of size "+
-                                                        tc.size)
-                               logger.debug("PublicKey: "+publicKeyTuple)
-                               publicKeysInGraph.foreach(k => 
logger.debug("PublikKey in graph: "+ k))
-                       }
-               }
-               result
-       }
-
-       /**
-        * @return the integer value if r is a typedLiteral of cert:hex or 
cert:decimal,
-        * otherwise the integer value of the  cert:hex or cert:decimal 
property of r or
-        * None if no such value available
-        */
-       private def intValueOfResource(n: GraphNode): Option[BigInt] = {
-               n! match {
-                       case l: TypedLiteral => intValueOfTypedLiteral(l);
-                       case r: Resource => intValueOfResourceByProperty(n)
-               }
-       }
-       
-       private def intValueOfResourceByProperty(n: GraphNode): Option[BigInt] 
= {
-               val hexValues = n/CERT.hex
-               if (hexValues.length > 0) {
-                       return Some(intValueOfHexString(hexValues*))
-               }
-               val decimalValues = n/CERT.decimal
-               if (decimalValues.length > 0) {
-                       return Some(BigInt(decimalValues*))
-               }
-               val intValues = n/CERT.int_
-               if (intValues.length > 0) {
-                       return Some(BigInt(intValues*))
-               }
-               return None
-       }
- 
-       private def intValueOfLiteral(l: Literal): Option[BigInt] = {
-               l match {
-                       case x: TypedLiteral => intValueOfTypedLiteral(x);
-                       case x => Some(intValueOfHexString(x.getLexicalForm))
-               }
-       }
-       private def intValueOfTypedLiteral(l: TypedLiteral): Option[BigInt] = {
-               try {
-                       (l.getLexicalForm, l.getDataType) match {
-                               case (lf, CERT.hex) => 
Some(intValueOfHexString(lf))
-                               case (lf, CERT.decimal) => Some(BigInt(lf))
-                               case (lf, CERT.int_) => Some(BigInt(lf))
-                               case _ => Some(new 
BigInt(LiteralFactory.getInstance.createObject(classOf[BigInteger], l)))
                        }
-               } catch {
-                       case e: NoConvertorException => None
-                       case e => throw e
                }
        }
-       
-       private def intValueOfHexString(s: String): BigInt = {
-               val strval = cleanHex(s);
-               BigInt(strval, 16);
-       }
 
+       protected def activate(context: ComponentContext) = { }
 
 
-       /**
-        * This takes any string and returns in order only those characters 
that are
-        * part of a hex string
-        * 
-        * @param strval
-        *            any string
-        * @return a pure hex string
-        */
-
-       private def cleanHex( strval: String)  = {
-               def legal(c: Char) = { //in order of likelyhood of appearance
-                       ((c >= '0') && (c <= '9')) ||
-                       ((c >= 'A') && (c <= 'F')) ||
-                       ((c >= 'a') && (c <= 'f'))
-               }
-               (for (c <- strval; if legal(c)) yield c)
-       }
 }
         
\ No newline at end of file

Modified: incubator/clerezza/trunk/parent/platform.security.foafssl/test/pom.xml
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.foafssl/test/pom.xml?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- incubator/clerezza/trunk/parent/platform.security.foafssl/test/pom.xml 
(original)
+++ incubator/clerezza/trunk/parent/platform.security.foafssl/test/pom.xml Fri 
Apr  1 13:12:07 2011
@@ -55,6 +55,10 @@
                        <groupId>org.apache.clerezza</groupId>
                        <artifactId>platform.security</artifactId>
                </dependency>
+        <dependency>
+            <groupId>org.apache.clerezza</groupId>
+            <artifactId>platform.security.foafssl.core</artifactId>
+        </dependency>
                <dependency>
                        <groupId>org.apache.clerezza</groupId>
                        <artifactId>platform.users.core</artifactId>

Modified: 
incubator/clerezza/trunk/parent/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/testservlets/TestMe.scala
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/testservlets/TestMe.scala?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/testservlets/TestMe.scala
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/testservlets/TestMe.scala
 Fri Apr  1 13:12:07 2011
@@ -21,12 +21,11 @@ package org.apache.clerezza.foafssl.test
 
 import org.apache.clerezza.platform.security.UserUtil
 import org.apache.clerezza.platform.usermanager.UserManager
-import org.apache.clerezza.rdf.utils.GraphNode
 import javax.ws.rs.{Produces, GET, Path}
-import org.apache.clerezza.web.fileserver.FileServer
 import org.osgi.service.component.ComponentContext
-import java.security.{PrivilegedAction, AccessController}
-import org.apache.clerezza.rdf.core.{UriRef, Resource, BNode}
+import org.apache.clerezza.foafssl.auth.{WebIDClaim, X509Claim}
+import java.security.Principal
+import scala.collection.JavaConversions._
 
 /**
  * implementation of (very early) version of test server for WebID so that the 
following tests
@@ -35,43 +34,58 @@ import org.apache.clerezza.rdf.core.{Uri
  * http://lists.w3.org/Archives/Public/public-xg-webid/2011Jan/0107.html
  */
 
-@Path("/test/webIdEndPoint")
-class TestMe extends FileServer {
+@Path("/test/WebId")
+class TestMe {
 
-       var userManager: UserManager = null;
+  var userManager: UserManager = null;
 
-       protected def bindUserManager(um: UserManager) = {
-               userManager = um
-       }
-
-       protected def unbindUserManager(um: UserManager) = {
-               userManager = null
-       }
-
-       protected def activate(componentContext: ComponentContext) = {
-               //              configure(componentContext.getBundleContext(), 
"profile-staticweb");
-       }
-
-       @GET
-       @Produces(Array("text/plain"))
-       def getTestMe(): String = {
-               try {
-                       var userName = UserUtil.getCurrentUserName();
-                       val webid = AccessController.doPrivileged(new 
PrivilegedAction[String]() {
-                               @Override
-                               def run(): String = {
-                                       val node: GraphNode = 
userManager.getUserGraphNode(userName)
-                                       node.getNode match {
-                                               case b : BNode => "+"
-                                          case uri: UriRef => 
uri.getUnicodeString
-                                       }
-                               }
-                       });
-                       return webid
-               } catch {
-                       case e: Exception => return "+ " + e.toString;
-               }
-       }
+  protected def bindUserManager(um: UserManager) = {
+    userManager = um
+  }
+
+  protected def unbindUserManager(um: UserManager) = {
+    userManager = null
+  }
+
+  protected def activate(componentContext: ComponentContext) = {
+    //         configure(componentContext.getBundleContext(), 
"profile-staticweb");
+  }
+
+  @GET
+  @Produces(Array("text/plain"))
+  def getTestMe(): String = {
+    val subject = UserUtil.getCurrentSubject();
+    val creds = subject.getPublicCredentials
+    if (creds.size == 0) return "No public keys found"
+    val cred = creds.iterator.next
+    def outString(x509: X509Claim): String = {
+      val res = for (p <- x509.verified) yield {
+        p match {
+          case id: WebIDClaim => "webid " + id.webId+" hasname "+ id.getName
+          case other: Principal => other.getName
+        }
+      }
+
+      return "X509 Certificate found. verified the following ids: " + res
+    }
+    return cred match {
+      case x509: X509Claim => outString(x509)
+      case other: AnyRef => "no X509 certificate found: found " + 
other.getClass()
+    }
+  }
+
+  @GET
+  @Path("x509")
+  @Produces(Array("text/plain"))
+  def getTestX509(): String = {
+    val subject = UserUtil.getCurrentSubject();
+    val creds = subject.getPublicCredentials
+    if (creds.size == 0) return "No public keys found"
+    return creds.iterator.next match {
+      case x509: X509Claim => "X509 Certificate found. " + x509.cert.toString
+      case other: Any => "no X509 certificate found: found " + other.getClass()
+    }
+  }
 
 
 }

Modified: 
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/UserUtil.java
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/UserUtil.java?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/UserUtil.java
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/UserUtil.java
 Fri Apr  1 13:12:07 2011
@@ -46,6 +46,16 @@ public class UserUtil {
        }
 
        /**
+        *
+        * @return the subject which is associated to the
+        * <code>AccessControlContext</code> of the current thread.
+        */
+       public static Subject getCurrentSubject() {
+               return getSubject(AccessController.getContext());
+       }
+
+
+       /**
         * Returns the name of the user associtated with the specified 
         * <code>AccessControlContext</code>.
         * 
@@ -54,7 +64,25 @@ public class UserUtil {
         * user name is associated with the provided 
<code>AccessControlContext</code>.
         */
        public static String getUserName(final AccessControlContext context) {
-               Subject subject;                
+               Subject subject = getSubject(context);
+               Iterator<Principal> iter = subject.getPrincipals().iterator();
+               String name = null;
+               if (iter.hasNext()) {
+                               name = iter.next().getName();
+               }
+               return name;
+       }
+
+       /**
+        * Returns the name of the user associtated with the specified
+        * <code>AccessControlContext</code>.
+        *
+        * @param context
+        * @return the username of the current user or null if no
+        * user name is associated with the provided 
<code>AccessControlContext</code>.
+        */
+       public static Subject getSubject(final AccessControlContext context) {
+               Subject subject;
                try {
                        subject = AccessController.doPrivileged(new 
PrivilegedExceptionAction<Subject>() {
 
@@ -70,17 +98,10 @@ public class UserUtil {
                        }
                        throw new RuntimeException(cause);
                }
-               if (subject == null) {
-                       return null;
-               }
-               Iterator<Principal> iter = subject.getPrincipals().iterator();
-               String name = null;
-               if (iter.hasNext()) {
-                               name = iter.next().getName();
-               }
-               return name;
+               return subject;
        }
 
+
        public static Subject createSubject(String userName) {
                return new Subject(true,
                        Collections.singleton(new PrincipalImpl(userName)), 
Collections.EMPTY_SET,

Modified: 
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticatingFilter.java
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticatingFilter.java?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticatingFilter.java
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticatingFilter.java
 Fri Apr  1 13:12:07 2011
@@ -63,13 +63,13 @@ public class AuthenticatingFilter implem
        public void handle(final Request request, final Response response,
                        final Handler wrapped) throws HandlerException {
 
-               String userName = null;
+               Subject subject = null;
                AuthenticationMethod authenticationMethod = null;
                try {
                        for (Iterator<WeightedAuthenticationMethod> it = 
methodList.iterator(); it.hasNext();) {
                                authenticationMethod = it.next();
-                               userName = 
authenticationMethod.authenticate(request);
-                               if (userName != null) {
+                               subject = 
authenticationMethod.authenticate(request);
+                               if (subject != null) {
                                        break;
                                }
                        }
@@ -80,11 +80,8 @@ public class AuthenticatingFilter implem
                        return;
                }
 
-               Subject subject;
-               if (userName == null) {
+               if (subject == null) {
                        subject = ANONYMOUS_SUBJECT;
-               } else {
-                       subject = UserUtil.createSubject(userName);
                }
                try {
                        Subject.doAsPrivileged(subject, new 
PrivilegedExceptionAction() {

Modified: 
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticationMethod.java
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticationMethod.java?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticationMethod.java
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.security/src/main/java/org/apache/clerezza/platform/security/auth/AuthenticationMethod.java
 Fri Apr  1 13:12:07 2011
@@ -22,6 +22,8 @@ import org.wymiwyg.wrhapi.HandlerExcepti
 import org.wymiwyg.wrhapi.Request;
 import org.wymiwyg.wrhapi.Response;
 
+import javax.security.auth.Subject;
+
 /**
  * Classes implementing this interface provide a method to authenticate a
  * a user with the information provided in a http request.
@@ -31,7 +33,7 @@ import org.wymiwyg.wrhapi.Response;
 public interface AuthenticationMethod {
 
        /**
-        * Returns the user name of the authenticated user with the informations
+        * Returns the user name of the authenticated user with the information
         * provided in the specified request. If the authentication failed, an
         * <code>LoginException</code> will be thrown. If no authentication
         * informations are available null is returned.
@@ -41,7 +43,7 @@ public interface AuthenticationMethod {
         * the login procedure failed.
         * @throws HandlerException
         */
-       public String authenticate(Request request)
+       public Subject authenticate(Request request)
                throws LoginException, HandlerException;
 
        /**

Modified: 
incubator/clerezza/trunk/parent/platform.users/core/src/main/resources/OSGI-INF/serviceComponents.xml
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.users/core/src/main/resources/OSGI-INF/serviceComponents.xml?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.users/core/src/main/resources/OSGI-INF/serviceComponents.xml
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.users/core/src/main/resources/OSGI-INF/serviceComponents.xml
 Fri Apr  1 13:12:07 2011
@@ -16,6 +16,8 @@
                cardinality="1..1" policy="static" bind="bindTcManager" 
unbind="unbindTcManager"/>
                <reference name="platformConfig" 
interface="org.apache.clerezza.platform.config.PlatformConfig"
                cardinality="1..1" policy="static" bind="bindPlatformConfig" 
unbind="unbindPlatformConfig"/>
+        <reference name="parser" 
interface="org.apache.clerezza.rdf.core.serializedform.Parser"
+        cardinality="1..1" policy="static" bind="bindParser" 
unbind="unbindParser"/>
                <!-- <reference name="tcManager" 
interface="org.apache.clerezza.platform.users.WebDescriptionProvider"
                cardinality="1..1" policy="static" 
bind="bindWebDescriptionProvider" unbind="unbindWebDescriptionProvider"/> -->
        </scr:component>

Modified: 
incubator/clerezza/trunk/parent/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala
URL: 
http://svn.apache.org/viewvc/incubator/clerezza/trunk/parent/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala?rev=1087694&r1=1087693&r2=1087694&view=diff
==============================================================================
--- 
incubator/clerezza/trunk/parent/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala
 (original)
+++ 
incubator/clerezza/trunk/parent/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala
 Fri Apr  1 13:12:07 2011
@@ -82,7 +82,7 @@ class WebIdGraphsService extends WebProx
                 */
                def publicUserGraph: MGraph = {
                        def systemTriples = {
-                               val systemGraph = 
tcManager.getMGraph(SystemConfig.SYSTEM_GRAPH_URI)
+                               val systemGraph = 
tcManager.getMGraph(Constants.SYSTEM_GRAPH_URI)
                                val triples = systemGraph.filter(webId, 
PLATFORM.userName, null)
                                val result = new SimpleMGraph
                                while (triples.hasNext) {
@@ -103,21 +103,13 @@ class WebIdGraphsService extends WebProx
                }
 
                /**
-                * for web-ids with a # same as representationGraphUriString
+                * the graph for putting local information in addition to the 
remote graph
                 */
                lazy val localGraphUri = {
-                       new UriRef(localGraphUriString)
+                       new UriRef(representationUri+".graph")
                }
 
-               //TODO: One should do some reasoning somewhere for URIs that 
have redirects, such a http://xmlns.com/foaf/knows
-               lazy val localGraphUriString = {
-                       val hashPos = uriString.indexOf('#')
-                       if (hashPos != -1) {
-                               uriString.substring(0, hashPos)
-                       } else {
-                               uriString
-                       }
-               }
+
 
 
                //for the WebID Graph this is the place where local information 
in addition to remote


Reply via email to