pulsar-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From GitBox <...@apache.org>
Subject [GitHub] merlimat commented on a change in pull request #2888: PIP-25: Token based authentication
Date Mon, 26 Nov 2018 22:24:04 GMT
merlimat commented on a change in pull request #2888: PIP-25: Token based authentication
URL: https://github.com/apache/pulsar/pull/2888#discussion_r236451460
 
 

 ##########
 File path: pulsar-broker-common/src/test/java/org/apache/pulsar/broker/authentication/AuthenticationProviderTokenTest.java
 ##########
 @@ -0,0 +1,287 @@
+/**
+ * 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.pulsar.broker.authentication;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.fail;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwt;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import io.jsonwebtoken.io.Decoders;
+import io.jsonwebtoken.security.Keys;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.security.KeyPair;
+import java.security.PrivateKey;
+import java.sql.Date;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
+import javax.crypto.SecretKey;
+import javax.naming.AuthenticationException;
+
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.authentication.utils.AuthTokenUtils;
+import org.testng.annotations.Test;
+
+public class AuthenticationProviderTokenTest {
+
+    @Test
+    public void testInvalidInitialize() throws Exception {
+        AuthenticationProviderToken provider = new AuthenticationProviderToken();
+
+        try {
+            provider.initialize(new ServiceConfiguration());
+            fail("should have failed");
+        } catch (IOException e) {
+            // Expected, secret key was not defined
+        }
+
+        provider.close();
+    }
+
+    @Test
+    public void testSerializeSecretKey() throws Exception {
+        SecretKey secretKey = AuthTokenUtils.createSecretKey(SignatureAlgorithm.HS256);
+
+        String token = Jwts.builder()
+                .setSubject("my-test-subject")
+                .signWith(secretKey)
+                .compact();
+
+        @SuppressWarnings("unchecked")
+        Jwt<?, Claims> jwt = Jwts.parser()
+                .setSigningKey(AuthTokenUtils.decodeSecretKey(secretKey.getEncoded()))
+                .parse(token);
+
+        System.out.println("Subject: " + jwt.getBody().getSubject());
+    }
+
+    @Test
+    public void testSerializeKeyPair() throws Exception {
+        KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
+
+        String privateKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPrivate());
+        String publicKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPublic());
+
+        String token = AuthTokenUtils.createToken(AuthTokenUtils.decodePrivateKey(Decoders.BASE64.decode(privateKey)),
+                "my-test-subject",
+                Optional.empty());
+
+        @SuppressWarnings("unchecked")
+        Jwt<?, Claims> jwt = Jwts.parser()
+                .setSigningKey(AuthTokenUtils.decodePublicKey(Decoders.BASE64.decode(publicKey)))
+                .parse(token);
+
+        System.out.println("Subject: " + jwt.getBody().getSubject());
+    }
+
+    @Test
+    public void testAuthSecretKey() throws Exception {
+        SecretKey secretKey = AuthTokenUtils.createSecretKey(SignatureAlgorithm.HS256);
+
+        AuthenticationProviderToken provider = new AuthenticationProviderToken();
+        assertEquals(provider.getAuthMethodName(), "token");
+
+        Properties properties = new Properties();
+        properties.setProperty(AuthenticationProviderToken.CONF_TOKEN_SECRET_KEY,
+                AuthTokenUtils.encodeKeyBase64(secretKey));
+
+        ServiceConfiguration conf = new ServiceConfiguration();
+        conf.setProperties(properties);
+        provider.initialize(conf);
+
+        try {
+            provider.authenticate(new AuthenticationDataSource() {
+            });
+            fail("Should have failed");
+        } catch (AuthenticationException e) {
+            // expected, no credential passed
+        }
+
+        String token = AuthTokenUtils.createToken(secretKey, "my-test-subject", Optional.empty());
+
+        // Pulsar protocol auth
+        String subject = provider.authenticate(new AuthenticationDataSource() {
+            @Override
+            public boolean hasDataFromCommand() {
+                return true;
+            }
+
+            @Override
+            public String getCommandData() {
+                return token;
+            }
+        });
+        assertEquals(subject, "my-test-subject");
+
+        // HTTP protocol auth
+        provider.authenticate(new AuthenticationDataSource() {
+            @Override
+            public boolean hasDataFromHttp() {
+                return true;
+            }
+
+            @Override
+            public String getHttpHeader(String name) {
+                if (name.equals("Authorization")) {
+                    return "Bearer " + token;
+                } else {
+                    throw new IllegalArgumentException("Wrong HTTP header");
+                }
+            }
+        });
+        assertEquals(subject, "my-test-subject");
+
+        // Expired token. This should be rejected by the authentication provider
+        String expiredToken = AuthTokenUtils.createToken(secretKey, "my-test-subject",
+                Optional.of(new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1))));
+
+        // Pulsar protocol auth
+        try {
+            provider.authenticate(new AuthenticationDataSource() {
+                @Override
+                public boolean hasDataFromCommand() {
+                    return true;
+                }
+
+                @Override
+                public String getCommandData() {
+                    return expiredToken;
+                }
+            });
+            fail("Should have failed");
+        } catch (AuthenticationException e) {
+            // expected, token was expired
+        }
+
+        provider.close();
+    }
+
+    @Test
 
 Review comment:
   I don't think it's possible to set env variables from within Java. We can only test this
in integration tests

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

Mime
View raw message