Search in sources :

Example 11 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class AuthenticationResource method renewSession.

@Path("/renewal")
@PUT
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String renewSession(final String sessionToken) {
    final Token oldToken = Token.fromString(sessionToken);
    // ensure this is a valid token and a non-revoked session
    // if valid, extend the life of the session
    final Session session = sessionValidator.validateAndDecrypt(keySupplier.get(), oldToken);
    if (session != null) {
        // the session is valid, generate a new token
        // both the old and new tokens are valid, but the old one will expire
        // sooner as governed by the Fernet spec
        // revoking the session will revoke all associated Fernet tokens
        final Key key = keySupplier.get().iterator().next();
        final Token newToken = Token.generate(random, key, session.getId().toString());
        return newToken.serialise();
    }
    throw new NotAuthorizedException(Response.status(Status.UNAUTHORIZED).entity("invalid session token").build());
}
Also used : Token(com.macasaet.fernet.Token) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Key(com.macasaet.fernet.Key) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) PUT(javax.ws.rs.PUT)

Example 12 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class SecretInjectionIT method verifyFailedForgery.

/**
 * This demonstrates a client who attempts to forge a Fernet token but
 * cannot do so without knowing the secret key.
 */
@Test
public final void verifyFailedForgery() {
    // given
    final SecureRandom random = new SecureRandom();
    final Key invalidKey = Key.generateKey(random);
    final Token forgedToken = Token.generate(random, invalidKey, UUID.randomUUID().toString());
    final String tokenString = forgedToken.serialise();
    // when
    final NotAuthorizedException result = assertThrows(NotAuthorizedException.class, () -> target("secrets").request().header("X-Authorization", tokenString).get(String.class));
    // then
    assertThat(result, notAuthorisedMatcher);
}
Also used : SecureRandom(java.security.SecureRandom) Token(com.macasaet.fernet.Token) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Key(com.macasaet.fernet.Key) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 13 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class SecretInjectionIT method verifyInvalidTokenReturnsNotAuthorized.

@Test
public final void verifyInvalidTokenReturnsNotAuthorized() throws UnsupportedEncodingException {
    // given
    final SecureRandom random = new SecureRandom();
    final Key key = Key.generateKey(random);
    final byte[] plainText = "this is a valid token".getBytes("UTF-8");
    final Token validToken = Token.generate(random, key, plainText);
    final byte[] cipherText = key.encrypt(plainText, validToken.getInitializationVector());
    final Token invalidToken = new Token(validToken.getVersion(), validToken.getTimestamp(), validToken.getInitializationVector(), cipherText, key.sign(validToken.getVersion(), validToken.getTimestamp(), validToken.getInitializationVector(), cipherText)) {

        public byte getVersion() {
            return (byte) (validToken.getVersion() + 1);
        }

        public Instant getTimestamp() {
            return validToken.getTimestamp().plus(Duration.ofDays(365));
        }

        public IvParameterSpec getInitializationVector() {
            final byte[] validVector = super.getInitializationVector().getIV();
            final byte[] invalidVector = new byte[validVector.length + 1];
            System.arraycopy(validVector, 0, invalidVector, 0, validVector.length);
            invalidVector[validVector.length] = 0;
            return new IvParameterSpec(invalidVector);
        }
    };
    // when
    final NotAuthorizedException result = assertThrows(NotAuthorizedException.class, () -> target("secrets").request().header("Authorization", "Bearer " + invalidToken.serialise()).get(String.class));
    // then
    assertThat(result, notAuthorisedMatcher);
}
Also used : SecureRandom(java.security.SecureRandom) Token(com.macasaet.fernet.Token) IvParameterSpec(javax.crypto.spec.IvParameterSpec) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Key(com.macasaet.fernet.Key) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 14 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class RedisKeyManager method rotate.

/**
 * This makes the staged key the new primary key, makes the primary key a validation-only key, deletes the oldest
 * validation-only key, and generates a new staged key. Note that this class is unaware of the TTL your application
 * uses to validate {@link Token Tokens}. So be mindful not to over-rotate your keys.
 */
public void rotate() {
    final Key newStaged = Key.generateKey(getRandom());
    try (final Jedis jedis = getPool().getResource()) {
        try (final Transaction transaction = jedis.multi()) {
            transaction.lpush("fernet_keys", newStaged.serialise());
            transaction.ltrim("fernet_keys", 0, getMaxActiveKeys() - 1);
            transaction.exec();
        }
    }
}
Also used : Jedis(redis.clients.jedis.Jedis) Transaction(redis.clients.jedis.Transaction) Key(com.macasaet.fernet.Key)

Example 15 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class TokenHeaderUtilityTest method verifyGetAuthorizationTokenDeserialisesBearerToken.

@Test
public final void verifyGetAuthorizationTokenDeserialisesBearerToken() {
    // given
    final Key key = Key.generateKey(random);
    final Token token = Token.generate(random, key, "hello");
    final ContainerRequest request = mock(ContainerRequest.class);
    given(request.getHeaderString("Authorization")).willReturn("Bearer " + token.serialise());
    // when
    final Token result = utility.getAuthorizationToken(request);
    // then
    assertEquals(token.serialise(), result.serialise());
}
Also used : Token(com.macasaet.fernet.Token) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) Key(com.macasaet.fernet.Key) Test(org.junit.Test)

Aggregations

Key (com.macasaet.fernet.Key)23 Test (org.junit.Test)12 Token (com.macasaet.fernet.Token)10 SecureRandom (java.security.SecureRandom)5 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 ByteBuffer (java.nio.ByteBuffer)4 ContainerRequest (org.glassfish.jersey.server.ContainerRequest)4 Context (com.amazonaws.services.lambda.runtime.Context)3 DescribeSecretResult (com.amazonaws.services.secretsmanager.model.DescribeSecretResult)3 PutSecretValueRequest (com.amazonaws.services.secretsmanager.model.PutSecretValueRequest)3 InputStream (java.io.InputStream)3 OutputStream (java.io.OutputStream)3 JerseyTest (org.glassfish.jersey.test.JerseyTest)3 StringInputStream (com.amazonaws.util.StringInputStream)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 FileOutputStream (java.io.FileOutputStream)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2