This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27723-grpc-jwt-expiry in repository https://gitbox.apache.org/repos/asf/camel.git
commit 81aec4e5a5502bb295ca95c322dd2e029233f4d6 Author: Claus Ibsen <[email protected]> AuthorDate: Fri Nov 27 19:41:15 2026 +0100 CAMEL-27723: camel-grpc - JWT tokens have no expiry The producer created one JSON Web Token at startup, without the iat and exp claims, and the consumer did not require them, so a token stayed valid until jwtSecret changed. The producer now sends tokens with iat and exp, valid for the new jwtTokenLifetime option (1 hour by default), and creates a new token when less than a tenth of the lifetime, at most one minute, is left. 0 keeps the tokens without expiry. The consumer accepts a clock difference of one minute for exp and iat, and the new jwtMaxTokenAge option rejects tokens older than this age (by iat). Tokens without exp are still accepted by default. The docs say PLAINTEXT (not NONE) and strongly recommend TLS with JWT. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../org/apache/camel/catalog/components/grpc.json | 18 +- .../apache/camel/catalog/docs/grpc-component.adoc | 16 +- .../component/grpc/GrpcEndpointConfigurer.java | 12 ++ .../component/grpc/GrpcEndpointUriFactory.java | 4 +- .../org/apache/camel/component/grpc/grpc.json | 18 +- .../camel-grpc/src/main/docs/grpc-component.adoc | 16 +- .../camel/component/grpc/GrpcConfiguration.java | 32 ++++ .../apache/camel/component/grpc/GrpcConsumer.java | 4 +- .../apache/camel/component/grpc/GrpcProducer.java | 13 +- .../grpc/auth/jwt/JwtCallCredentials.java | 14 +- .../camel/component/grpc/auth/jwt/JwtHelper.java | 23 ++- .../grpc/auth/jwt/JwtServerInterceptor.java | 53 +++++- .../component/grpc/auth/jwt/JwtTokenSupplier.java | 103 ++++++++++++ .../component/grpc/GrpcConsumerJwtExpiryTest.java | 183 +++++++++++++++++++++ .../grpc/auth/jwt/JwtTokenSupplierTest.java | 137 +++++++++++++++ .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 13 ++ .../endpoint/dsl/GrpcEndpointBuilderFactory.java | 80 +++++++++ 17 files changed, 709 insertions(+), 30 deletions(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/grpc.json b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/grpc.json index b3a2a5589e16..5393500966f0 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/grpc.json +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/grpc.json @@ -79,13 +79,15 @@ "authenticationType": { "index": 35, "kind": "parameter", "displayName": "Authentication Type", "group": "security", "label": "security", "required": false, "type": "enum", "javaType": "org.apache.camel.component.grpc.GrpcAuthType", "enum": [ "NONE", "GOOGLE", "JWT" ], "deprecated": false, "autowired": false, "secret": false, "defaultValue": "NONE", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The au [...] "jwtAlgorithm": { "index": 36, "kind": "parameter", "displayName": "Jwt Algorithm", "group": "security", "label": "security", "required": false, "type": "enum", "javaType": "org.apache.camel.component.grpc.auth.jwt.JwtAlgorithm", "enum": [ "HMAC256", "HMAC384", "HMAC512" ], "deprecated": false, "autowired": false, "secret": false, "defaultValue": "HMAC256", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": [...] "jwtIssuer": { "index": 37, "kind": "parameter", "displayName": "Jwt Issuer", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The issuer (iss claim) of the JSON Web Token. The producer puts it in the token, and the consumer accepts only [...] - "jwtSecret": { "index": 38, "kind": "parameter", "displayName": "Jwt Secret", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The secret key of the HMAC algorithm that signs the JSON Web Token on the producer and ver [...] - "jwtSubject": { "index": 39, "kind": "parameter", "displayName": "Jwt Subject", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The subject (sub claim) of the JSON Web Token. The producer puts it in the token, and the consumer accepts on [...] - "keyCertChainResource": { "index": 40, "kind": "parameter", "displayName": "Key Cert Chain Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the X.509 certificate chain in PEM format [...] - "keyPassword": { "index": 41, "kind": "parameter", "displayName": "Key Password", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The password of the private key in keyResource, if the key is encrypted." }, - "keyResource": { "index": 42, "kind": "parameter", "displayName": "Key Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the PKCS#8 private key in PEM format of keyCertChainResource. [...] - "negotiationType": { "index": 43, "kind": "parameter", "displayName": "Negotiation Type", "group": "security", "label": "security", "required": false, "type": "enum", "javaType": "io.grpc.netty.NegotiationType", "enum": [ "PLAINTEXT", "TLS" ], "deprecated": false, "autowired": false, "secret": false, "defaultValue": "PLAINTEXT", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The transport security of t [...] - "serviceAccountResource": { "index": 44, "kind": "parameter", "displayName": "Service Account Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the Google Cloud service account key f [...] - "trustCertCollectionResource": { "index": 45, "kind": "parameter", "displayName": "Trust Cert Collection Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the trusted certificates in [...] + "jwtMaxTokenAge": { "index": 38, "kind": "parameter", "displayName": "Jwt Max Token Age", "group": "security", "label": "consumer,security", "required": false, "type": "duration", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The maximum age of a JSON Web Token that the consumer accepts, in milliseconds, from its iat (issued [...] + "jwtSecret": { "index": 39, "kind": "parameter", "displayName": "Jwt Secret", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The secret key of the HMAC algorithm that signs the JSON Web Token on the producer and ver [...] + "jwtSubject": { "index": 40, "kind": "parameter", "displayName": "Jwt Subject", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The subject (sub claim) of the JSON Web Token. The producer puts it in the token, and the consumer accepts on [...] + "jwtTokenLifetime": { "index": 41, "kind": "parameter", "displayName": "Jwt Token Lifetime", "group": "security", "label": "producer,security", "required": false, "type": "duration", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": "3600000", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "How long a JSON Web Token that the producer sends is valid, in millise [...] + "keyCertChainResource": { "index": 42, "kind": "parameter", "displayName": "Key Cert Chain Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the X.509 certificate chain in PEM format [...] + "keyPassword": { "index": 43, "kind": "parameter", "displayName": "Key Password", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The password of the private key in keyResource, if the key is encrypted." }, + "keyResource": { "index": 44, "kind": "parameter", "displayName": "Key Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the PKCS#8 private key in PEM format of keyCertChainResource. [...] + "negotiationType": { "index": 45, "kind": "parameter", "displayName": "Negotiation Type", "group": "security", "label": "security", "required": false, "type": "enum", "javaType": "io.grpc.netty.NegotiationType", "enum": [ "PLAINTEXT", "TLS" ], "deprecated": false, "autowired": false, "secret": false, "defaultValue": "PLAINTEXT", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The transport security of t [...] + "serviceAccountResource": { "index": 46, "kind": "parameter", "displayName": "Service Account Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the Google Cloud service account key f [...] + "trustCertCollectionResource": { "index": 47, "kind": "parameter", "displayName": "Trust Cert Collection Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the trusted certificates in [...] } } diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/grpc-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/grpc-component.adoc index 9912f0bb304d..7804bc33a4e5 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/grpc-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/grpc-component.adoc @@ -66,13 +66,27 @@ To enable these features, the following component properties combinations must b |||negotiationType|TLS|Required |||serviceAccountResource||Required |3|*Custom JSON Web Token implementation authentication*|authenticationType|JWT|Required -|||negotiationType|NONE or TLS|Optional. The TLS/SSL not checking for this type, but strongly recommended. +|||negotiationType|PLAINTEXT or TLS|Optional, but TLS is strongly recommended: with PLAINTEXT the token is sent in clear text, and whoever reads it can make calls with it until it expires |||jwtAlgorithm|HMAC256(default) or (HMAC384,HMAC512)|Optional |||jwtSecret||Required |||jwtIssuer||Optional |||jwtSubject||Optional +|||jwtTokenLifetime|1 hour (default)|Optional. On a producer: how long a token is valid (the exp claim). 0 sends a token without expiry +|||jwtMaxTokenAge||Optional. On a consumer: the maximum age of a token by its iat claim. Not checked by default |======================================================================= +==== JSON Web Token expiry + +With `authenticationType=JWT`, the producer sends a token with the `iat` (issued at) and `exp` (expires at) claims, +which is valid for `jwtTokenLifetime` (1 hour by default). The producer creates a new token when less than a tenth of +the lifetime, at most one minute, is left of the current one. With `jwtTokenLifetime=0` the producer sends a token +without `iat` and `exp`, as before Camel 4.24, which is valid until `jwtSecret` changes. + +The consumer rejects a token whose `exp` claim has passed, and a token whose `iat` claim is in the future. A clock +difference of up to one minute between the hosts is accepted. A token without `exp`, such as one from another client, +is accepted until `jwtSecret` changes, unless `jwtMaxTokenAge` is set: then the consumer also rejects a token that is +older than `jwtMaxTokenAge` by its `iat` claim, or that has no `iat` claim. + === gRPC consumer reply The message body at the end of the consumer route is the reply to the client: the response message of the called diff --git a/components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointConfigurer.java b/components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointConfigurer.java index 288b451ffa70..34127d75f27c 100644 --- a/components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointConfigurer.java +++ b/components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointConfigurer.java @@ -52,10 +52,14 @@ public class GrpcEndpointConfigurer extends PropertyConfigurerSupport implements case "jwtAlgorithm": target.getConfiguration().setJwtAlgorithm(property(camelContext, org.apache.camel.component.grpc.auth.jwt.JwtAlgorithm.class, value)); return true; case "jwtissuer": case "jwtIssuer": target.getConfiguration().setJwtIssuer(property(camelContext, java.lang.String.class, value)); return true; + case "jwtmaxtokenage": + case "jwtMaxTokenAge": target.getConfiguration().setJwtMaxTokenAge(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "jwtsecret": case "jwtSecret": target.getConfiguration().setJwtSecret(property(camelContext, java.lang.String.class, value)); return true; case "jwtsubject": case "jwtSubject": target.getConfiguration().setJwtSubject(property(camelContext, java.lang.String.class, value)); return true; + case "jwttokenlifetime": + case "jwtTokenLifetime": target.getConfiguration().setJwtTokenLifetime(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "keepalivetime": case "keepAliveTime": target.getConfiguration().setKeepAliveTime(property(camelContext, long.class, value)); return true; case "keepalivetimeout": @@ -143,10 +147,14 @@ public class GrpcEndpointConfigurer extends PropertyConfigurerSupport implements case "jwtAlgorithm": return org.apache.camel.component.grpc.auth.jwt.JwtAlgorithm.class; case "jwtissuer": case "jwtIssuer": return java.lang.String.class; + case "jwtmaxtokenage": + case "jwtMaxTokenAge": return long.class; case "jwtsecret": case "jwtSecret": return java.lang.String.class; case "jwtsubject": case "jwtSubject": return java.lang.String.class; + case "jwttokenlifetime": + case "jwtTokenLifetime": return long.class; case "keepalivetime": case "keepAliveTime": return long.class; case "keepalivetimeout": @@ -235,10 +243,14 @@ public class GrpcEndpointConfigurer extends PropertyConfigurerSupport implements case "jwtAlgorithm": return target.getConfiguration().getJwtAlgorithm(); case "jwtissuer": case "jwtIssuer": return target.getConfiguration().getJwtIssuer(); + case "jwtmaxtokenage": + case "jwtMaxTokenAge": return target.getConfiguration().getJwtMaxTokenAge(); case "jwtsecret": case "jwtSecret": return target.getConfiguration().getJwtSecret(); case "jwtsubject": case "jwtSubject": return target.getConfiguration().getJwtSubject(); + case "jwttokenlifetime": + case "jwtTokenLifetime": return target.getConfiguration().getJwtTokenLifetime(); case "keepalivetime": case "keepAliveTime": return target.getConfiguration().getKeepAliveTime(); case "keepalivetimeout": diff --git a/components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointUriFactory.java b/components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointUriFactory.java index f062e0f7f61b..b3aa428ec4b0 100644 --- a/components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointUriFactory.java +++ b/components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointUriFactory.java @@ -24,7 +24,7 @@ public class GrpcEndpointUriFactory extends org.apache.camel.support.component.E private static final Set<String> ENDPOINT_IDENTITY_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { - Set<String> props = new HashSet<>(46); + Set<String> props = new HashSet<>(48); props.add("authenticationType"); props.add("autoDiscoverClientInterceptors"); props.add("autoDiscoverServerInterceptors"); @@ -40,8 +40,10 @@ public class GrpcEndpointUriFactory extends org.apache.camel.support.component.E props.add("initialFlowControlWindow"); props.add("jwtAlgorithm"); props.add("jwtIssuer"); + props.add("jwtMaxTokenAge"); props.add("jwtSecret"); props.add("jwtSubject"); + props.add("jwtTokenLifetime"); props.add("keepAliveTime"); props.add("keepAliveTimeout"); props.add("keyCertChainResource"); diff --git a/components/camel-grpc/src/generated/resources/META-INF/org/apache/camel/component/grpc/grpc.json b/components/camel-grpc/src/generated/resources/META-INF/org/apache/camel/component/grpc/grpc.json index b3a2a5589e16..5393500966f0 100644 --- a/components/camel-grpc/src/generated/resources/META-INF/org/apache/camel/component/grpc/grpc.json +++ b/components/camel-grpc/src/generated/resources/META-INF/org/apache/camel/component/grpc/grpc.json @@ -79,13 +79,15 @@ "authenticationType": { "index": 35, "kind": "parameter", "displayName": "Authentication Type", "group": "security", "label": "security", "required": false, "type": "enum", "javaType": "org.apache.camel.component.grpc.GrpcAuthType", "enum": [ "NONE", "GOOGLE", "JWT" ], "deprecated": false, "autowired": false, "secret": false, "defaultValue": "NONE", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The au [...] "jwtAlgorithm": { "index": 36, "kind": "parameter", "displayName": "Jwt Algorithm", "group": "security", "label": "security", "required": false, "type": "enum", "javaType": "org.apache.camel.component.grpc.auth.jwt.JwtAlgorithm", "enum": [ "HMAC256", "HMAC384", "HMAC512" ], "deprecated": false, "autowired": false, "secret": false, "defaultValue": "HMAC256", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": [...] "jwtIssuer": { "index": 37, "kind": "parameter", "displayName": "Jwt Issuer", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The issuer (iss claim) of the JSON Web Token. The producer puts it in the token, and the consumer accepts only [...] - "jwtSecret": { "index": 38, "kind": "parameter", "displayName": "Jwt Secret", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The secret key of the HMAC algorithm that signs the JSON Web Token on the producer and ver [...] - "jwtSubject": { "index": 39, "kind": "parameter", "displayName": "Jwt Subject", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The subject (sub claim) of the JSON Web Token. The producer puts it in the token, and the consumer accepts on [...] - "keyCertChainResource": { "index": 40, "kind": "parameter", "displayName": "Key Cert Chain Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the X.509 certificate chain in PEM format [...] - "keyPassword": { "index": 41, "kind": "parameter", "displayName": "Key Password", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The password of the private key in keyResource, if the key is encrypted." }, - "keyResource": { "index": 42, "kind": "parameter", "displayName": "Key Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the PKCS#8 private key in PEM format of keyCertChainResource. [...] - "negotiationType": { "index": 43, "kind": "parameter", "displayName": "Negotiation Type", "group": "security", "label": "security", "required": false, "type": "enum", "javaType": "io.grpc.netty.NegotiationType", "enum": [ "PLAINTEXT", "TLS" ], "deprecated": false, "autowired": false, "secret": false, "defaultValue": "PLAINTEXT", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The transport security of t [...] - "serviceAccountResource": { "index": 44, "kind": "parameter", "displayName": "Service Account Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the Google Cloud service account key f [...] - "trustCertCollectionResource": { "index": 45, "kind": "parameter", "displayName": "Trust Cert Collection Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the trusted certificates in [...] + "jwtMaxTokenAge": { "index": 38, "kind": "parameter", "displayName": "Jwt Max Token Age", "group": "security", "label": "consumer,security", "required": false, "type": "duration", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The maximum age of a JSON Web Token that the consumer accepts, in milliseconds, from its iat (issued [...] + "jwtSecret": { "index": 39, "kind": "parameter", "displayName": "Jwt Secret", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The secret key of the HMAC algorithm that signs the JSON Web Token on the producer and ver [...] + "jwtSubject": { "index": 40, "kind": "parameter", "displayName": "Jwt Subject", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The subject (sub claim) of the JSON Web Token. The producer puts it in the token, and the consumer accepts on [...] + "jwtTokenLifetime": { "index": 41, "kind": "parameter", "displayName": "Jwt Token Lifetime", "group": "security", "label": "producer,security", "required": false, "type": "duration", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": "3600000", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "How long a JSON Web Token that the producer sends is valid, in millise [...] + "keyCertChainResource": { "index": 42, "kind": "parameter", "displayName": "Key Cert Chain Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the X.509 certificate chain in PEM format [...] + "keyPassword": { "index": 43, "kind": "parameter", "displayName": "Key Password", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The password of the private key in keyResource, if the key is encrypted." }, + "keyResource": { "index": 44, "kind": "parameter", "displayName": "Key Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the PKCS#8 private key in PEM format of keyCertChainResource. [...] + "negotiationType": { "index": 45, "kind": "parameter", "displayName": "Negotiation Type", "group": "security", "label": "security", "required": false, "type": "enum", "javaType": "io.grpc.netty.NegotiationType", "enum": [ "PLAINTEXT", "TLS" ], "deprecated": false, "autowired": false, "secret": false, "defaultValue": "PLAINTEXT", "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The transport security of t [...] + "serviceAccountResource": { "index": 46, "kind": "parameter", "displayName": "Service Account Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the Google Cloud service account key f [...] + "trustCertCollectionResource": { "index": 47, "kind": "parameter", "displayName": "Trust Cert Collection Resource", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "supportFileReference": true, "configurationClass": "org.apache.camel.component.grpc.GrpcConfiguration", "configurationField": "configuration", "description": "The location of the trusted certificates in [...] } } diff --git a/components/camel-grpc/src/main/docs/grpc-component.adoc b/components/camel-grpc/src/main/docs/grpc-component.adoc index 9912f0bb304d..7804bc33a4e5 100644 --- a/components/camel-grpc/src/main/docs/grpc-component.adoc +++ b/components/camel-grpc/src/main/docs/grpc-component.adoc @@ -66,13 +66,27 @@ To enable these features, the following component properties combinations must b |||negotiationType|TLS|Required |||serviceAccountResource||Required |3|*Custom JSON Web Token implementation authentication*|authenticationType|JWT|Required -|||negotiationType|NONE or TLS|Optional. The TLS/SSL not checking for this type, but strongly recommended. +|||negotiationType|PLAINTEXT or TLS|Optional, but TLS is strongly recommended: with PLAINTEXT the token is sent in clear text, and whoever reads it can make calls with it until it expires |||jwtAlgorithm|HMAC256(default) or (HMAC384,HMAC512)|Optional |||jwtSecret||Required |||jwtIssuer||Optional |||jwtSubject||Optional +|||jwtTokenLifetime|1 hour (default)|Optional. On a producer: how long a token is valid (the exp claim). 0 sends a token without expiry +|||jwtMaxTokenAge||Optional. On a consumer: the maximum age of a token by its iat claim. Not checked by default |======================================================================= +==== JSON Web Token expiry + +With `authenticationType=JWT`, the producer sends a token with the `iat` (issued at) and `exp` (expires at) claims, +which is valid for `jwtTokenLifetime` (1 hour by default). The producer creates a new token when less than a tenth of +the lifetime, at most one minute, is left of the current one. With `jwtTokenLifetime=0` the producer sends a token +without `iat` and `exp`, as before Camel 4.24, which is valid until `jwtSecret` changes. + +The consumer rejects a token whose `exp` claim has passed, and a token whose `iat` claim is in the future. A clock +difference of up to one minute between the hosts is accepted. A token without `exp`, such as one from another client, +is accepted until `jwtSecret` changes, unless `jwtMaxTokenAge` is set: then the consumer also rejects a token that is +older than `jwtMaxTokenAge` by its `iat` claim, or that has no `iat` claim. + === gRPC consumer reply The message body at the end of the consumer route is the reply to the client: the response message of the called diff --git a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcConfiguration.java b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcConfiguration.java index f2fd034e19ae..b0592d00de52 100644 --- a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcConfiguration.java +++ b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcConfiguration.java @@ -89,6 +89,22 @@ public class GrpcConfiguration { + " accepts only tokens with the same subject.") private String jwtSubject; + @UriParam(label = "producer,security", defaultValue = "3600000", javaType = "java.time.Duration", + description = "How long a JSON Web Token that the producer sends is valid, in milliseconds: the token has the iat" + + " (issued at) claim and an exp (expires at) claim this much later. The producer creates a new" + + " token when less than a tenth of the lifetime, at most one minute, is left. A value of 0 sends a" + + " token without iat and exp claims, which is valid until jwtSecret changes. Used when" + + " authenticationType is JWT.") + private long jwtTokenLifetime = 3600000; + + @UriParam(label = "consumer,security", javaType = "java.time.Duration", + description = "The maximum age of a JSON Web Token that the consumer accepts, in milliseconds, from its iat" + + " (issued at) claim. When set, the consumer rejects tokens that are older, or that have no iat" + + " claim. The consumer always rejects a token whose exp (expires at) claim has passed. The default" + + " 0 does not check the age, so tokens without an exp claim are valid until jwtSecret changes." + + " Used when authenticationType is JWT.") + private long jwtMaxTokenAge; + @UriParam(label = "security", description = "The location of the Google Cloud service account key file in JSON format, for example" + " classpath:service-account.json. Required when authenticationType is GOOGLE: the producer sends the" @@ -354,6 +370,22 @@ public class GrpcConfiguration { this.jwtSubject = jwtSubject; } + public long getJwtTokenLifetime() { + return jwtTokenLifetime; + } + + public void setJwtTokenLifetime(long jwtTokenLifetime) { + this.jwtTokenLifetime = jwtTokenLifetime; + } + + public long getJwtMaxTokenAge() { + return jwtMaxTokenAge; + } + + public void setJwtMaxTokenAge(long jwtMaxTokenAge) { + this.jwtMaxTokenAge = jwtMaxTokenAge; + } + public String getServiceAccountResource() { return serviceAccountResource; } diff --git a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcConsumer.java b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcConsumer.java index 252ca9a74305..6467ad6dd238 100644 --- a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcConsumer.java +++ b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcConsumer.java @@ -17,6 +17,7 @@ package org.apache.camel.component.grpc; import java.net.InetSocketAddress; +import java.time.Duration; import java.util.concurrent.TimeUnit; import io.grpc.BindableService; @@ -144,7 +145,8 @@ public class GrpcConsumer extends DefaultConsumer { serverBuilder = serverBuilder.intercept(new JwtServerInterceptor( configuration.getJwtAlgorithm(), configuration.getJwtSecret(), - configuration.getJwtIssuer(), configuration.getJwtSubject())); + configuration.getJwtIssuer(), configuration.getJwtSubject(), + Duration.ofMillis(configuration.getJwtMaxTokenAge()))); } // To configure RST_STREAM settings we need valid configuration for both maxRstFramesPerWindow & maxRstPeriodSeconds diff --git a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcProducer.java b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcProducer.java index 453382efc009..5cd0b0c2de7a 100644 --- a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcProducer.java +++ b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcProducer.java @@ -17,6 +17,7 @@ package org.apache.camel.component.grpc; import java.io.InputStream; +import java.time.Duration; import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; @@ -32,7 +33,7 @@ import io.netty.handler.ssl.SslContextBuilder; import org.apache.camel.AsyncCallback; import org.apache.camel.Exchange; import org.apache.camel.component.grpc.auth.jwt.JwtCallCredentials; -import org.apache.camel.component.grpc.auth.jwt.JwtHelper; +import org.apache.camel.component.grpc.auth.jwt.JwtTokenSupplier; import org.apache.camel.component.grpc.client.*; import org.apache.camel.support.DefaultAsyncProducer; import org.apache.camel.support.ResourceHelper; @@ -102,9 +103,13 @@ public class GrpcProducer extends DefaultAsyncProducer { } else if (configuration.getAuthenticationType() == GrpcAuthType.JWT) { ObjectHelper.notNull(configuration.getJwtSecret(), "jwtSecret"); - String jwtToken = JwtHelper.createJwtToken(configuration.getJwtAlgorithm(), configuration.getJwtSecret(), - configuration.getJwtIssuer(), configuration.getJwtSubject()); - callCreds = new JwtCallCredentials(jwtToken); + JwtTokenSupplier jwtTokenSupplier = new JwtTokenSupplier( + configuration.getJwtAlgorithm(), configuration.getJwtSecret(), + configuration.getJwtIssuer(), configuration.getJwtSubject(), + Duration.ofMillis(configuration.getJwtTokenLifetime())); + // create the first token now, so a wrong configuration fails at startup + jwtTokenSupplier.get(); + callCreds = new JwtCallCredentials(jwtTokenSupplier); } if (configuration.isSynchronous()) { diff --git a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtCallCredentials.java b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtCallCredentials.java index 3ff8565bbb6f..5eebb2f24059 100644 --- a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtCallCredentials.java +++ b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtCallCredentials.java @@ -17,6 +17,7 @@ package org.apache.camel.component.grpc.auth.jwt; import java.util.concurrent.Executor; +import java.util.function.Supplier; import io.grpc.CallCredentials; import io.grpc.Metadata; @@ -30,10 +31,17 @@ import org.slf4j.LoggerFactory; */ public class JwtCallCredentials extends CallCredentials { private static final Logger LOG = LoggerFactory.getLogger(JwtCallCredentials.class); - private final String jwtToken; + private final Supplier<String> jwtTokenSupplier; public JwtCallCredentials(String jwtToken) { - this.jwtToken = jwtToken; + this(() -> jwtToken); + } + + /** + * Sends the token that the supplier returns on each call, so the supplier can replace a token before it expires. + */ + public JwtCallCredentials(Supplier<String> jwtTokenSupplier) { + this.jwtTokenSupplier = jwtTokenSupplier; } @Override @@ -46,7 +54,7 @@ public class JwtCallCredentials extends CallCredentials { LOG.debug("Start to apply for the JWT token header"); Metadata headers = new Metadata(); Metadata.Key<String> jwtKey = GrpcConstants.GRPC_JWT_METADATA_KEY; - headers.put(jwtKey, jwtToken); + headers.put(jwtKey, jwtTokenSupplier.get()); metadataApplier.apply(headers); } catch (Exception e) { LOG.debug("Unable to set metadata credentials header", e); diff --git a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtHelper.java b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtHelper.java index 4074da234125..b336d87c7f7e 100644 --- a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtHelper.java +++ b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtHelper.java @@ -16,7 +16,10 @@ */ package org.apache.camel.component.grpc.auth.jwt; +import java.time.Instant; + import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTCreator; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; @@ -27,10 +30,28 @@ public final class JwtHelper { private JwtHelper() { } + /** + * Creates a token without the iat (issued at) and exp (expires at) claims, which is valid until the secret changes. + */ public static String createJwtToken(JwtAlgorithm algorithmName, String secret, String issuer, String subject) { + return createJwtToken(algorithmName, secret, issuer, subject, null, null); + } + + /** + * Creates a token with the given iat (issued at) and exp (expires at) claims. A null value leaves the claim out. + */ + public static String createJwtToken( + JwtAlgorithm algorithmName, String secret, String issuer, String subject, Instant issuedAt, Instant expiresAt) { try { Algorithm algorithm = selectAlgorithm(algorithmName, secret); - return JWT.create().withIssuer(issuer).withSubject(subject).sign(algorithm); + JWTCreator.Builder builder = JWT.create().withIssuer(issuer).withSubject(subject); + if (issuedAt != null) { + builder.withIssuedAt(issuedAt); + } + if (expiresAt != null) { + builder.withExpiresAt(expiresAt); + } + return builder.sign(algorithm); } catch (JWTCreationException e) { throw new IllegalArgumentException("Unable to create JWT token", e); } diff --git a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtServerInterceptor.java b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtServerInterceptor.java index a8b7d1e36f3b..a62b1d2649de 100644 --- a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtServerInterceptor.java +++ b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtServerInterceptor.java @@ -16,10 +16,15 @@ */ package org.apache.camel.component.grpc.auth.jwt; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; + import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; +import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import io.grpc.Context; import io.grpc.Contexts; @@ -43,10 +48,32 @@ public class JwtServerInterceptor implements ServerInterceptor { private static final ServerCall.Listener NOOP_LISTENER = new ServerCall.Listener() { }; + /** + * The clock difference between the hosts that is accepted for the exp (expires at) and iat (issued at) claims. + */ + public static final Duration CLOCK_SKEW = Duration.ofMinutes(1); + private final JWTVerifier verifier; + private final Duration maxTokenAge; + private final Clock clock; public JwtServerInterceptor(JwtAlgorithm algorithm, String secret, String issuer, String subject) { - verifier = prepareJwtVerifier(algorithm, secret, issuer, subject); + this(algorithm, secret, issuer, subject, Duration.ZERO); + } + + /** + * @param maxTokenAge the maximum age of a token by its iat (issued at) claim, 0 or less to not check the age + */ + public JwtServerInterceptor(JwtAlgorithm algorithm, String secret, String issuer, String subject, + Duration maxTokenAge) { + this(algorithm, secret, issuer, subject, maxTokenAge, Clock.systemUTC()); + } + + JwtServerInterceptor(JwtAlgorithm algorithm, String secret, String issuer, String subject, Duration maxTokenAge, + Clock clock) { + this.verifier = prepareJwtVerifier(algorithm, secret, issuer, subject); + this.maxTokenAge = maxTokenAge; + this.clock = clock; } @Override @@ -62,6 +89,7 @@ public class JwtServerInterceptor implements ServerInterceptor { Context ctx; try { DecodedJWT verified = verifier.verify(jwtToken); + checkTokenAge(verified); ctx = Context.current() .withValue(GrpcConstants.GRPC_JWT_USER_ID_CTX_KEY, verified.getSubject() == null ? "anonymous" : verified.getSubject()) @@ -75,10 +103,31 @@ public class JwtServerInterceptor implements ServerInterceptor { return Contexts.interceptCall(ctx, call, metadata, serverCallHandler); } + private void checkTokenAge(DecodedJWT token) { + if (maxTokenAge.isNegative() || maxTokenAge.isZero()) { + return; + } + Instant issuedAt = token.getIssuedAtAsInstant(); + if (issuedAt == null) { + throw new JWTVerificationException("The Token has no iat (issued at) claim, which jwtMaxTokenAge requires."); + } + if (issuedAt.plus(maxTokenAge).isBefore(clock.instant())) { + throw new JWTVerificationException( + "The Token was issued at " + issuedAt + ", which is longer ago than jwtMaxTokenAge."); + } + } + + /** + * The verifier checks the signature, the issuer and the subject, and, when the token has them, that the exp + * (expires at) claim has not passed and that the iat (issued at) claim is not in the future, accepting a clock + * difference of {@link #CLOCK_SKEW}. + */ public static JWTVerifier prepareJwtVerifier(JwtAlgorithm algorithmName, String secret, String issuer, String subject) { try { Algorithm algorithm = JwtHelper.selectAlgorithm(algorithmName, secret); - return JWT.require(algorithm).withIssuer(issuer).withSubject(subject).build(); + return JWT.require(algorithm).withIssuer(issuer).withSubject(subject) + .acceptLeeway(CLOCK_SKEW.toSeconds()) + .build(); } catch (JWTCreationException e) { throw new IllegalArgumentException("Unable to create JWT verifier", e); } diff --git a/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtTokenSupplier.java b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtTokenSupplier.java new file mode 100644 index 000000000000..197e88faaf32 --- /dev/null +++ b/components/camel-grpc/src/main/java/org/apache/camel/component/grpc/auth/jwt/JwtTokenSupplier.java @@ -0,0 +1,103 @@ +/* + * 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.camel.component.grpc.auth.jwt; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.function.Supplier; + +/** + * Supplies the JSON Web Token that the producer sends, with the iat (issued at) and exp (expires at) claims. A new + * token is created when less than a tenth of the lifetime, at most one minute, is left of the current one. The check is + * a volatile read and a clock read per call; only the call that finds the token due creates a new one. + */ +public class JwtTokenSupplier implements Supplier<String> { + + /** + * The longest time before the expiry of a token at which a new token is created. + */ + static final Duration MAX_REFRESH_AHEAD = Duration.ofMinutes(1); + + private final JwtAlgorithm algorithm; + private final String secret; + private final String issuer; + private final String subject; + private final Duration lifetime; + private final Clock clock; + + private volatile Token current; + + /** + * @param lifetime how long a token is valid, 0 or less for a token without iat and exp claims, which never expires + */ + public JwtTokenSupplier(JwtAlgorithm algorithm, String secret, String issuer, String subject, Duration lifetime) { + this(algorithm, secret, issuer, subject, lifetime, Clock.systemUTC()); + } + + public JwtTokenSupplier(JwtAlgorithm algorithm, String secret, String issuer, String subject, Duration lifetime, + Clock clock) { + if (!lifetime.isNegative() && !lifetime.isZero() && lifetime.compareTo(Duration.ofSeconds(1)) < 0) { + // the iat and exp claims are in seconds + throw new IllegalArgumentException( + "jwtTokenLifetime must be 0 (no expiry) or at least 1 second, was " + lifetime.toMillis() + " millis"); + } + this.algorithm = algorithm; + this.secret = secret; + this.issuer = issuer; + this.subject = subject; + this.lifetime = lifetime; + this.clock = clock; + } + + @Override + public String get() { + Token token = current; + if (token == null || token.isDue(clock.instant())) { + synchronized (this) { + token = current; + if (token == null || token.isDue(clock.instant())) { + token = createToken(); + current = token; + } + } + } + return token.value; + } + + private Token createToken() { + if (lifetime.isNegative() || lifetime.isZero()) { + return new Token(JwtHelper.createJwtToken(algorithm, secret, issuer, subject), Instant.MAX); + } + // the claims are in seconds, so compute the refresh time from the truncated values that the token carries + Instant issuedAt = clock.instant().truncatedTo(ChronoUnit.SECONDS); + Instant expiresAt = issuedAt.plus(lifetime).truncatedTo(ChronoUnit.SECONDS); + Duration ahead = lifetime.dividedBy(10); + if (ahead.compareTo(MAX_REFRESH_AHEAD) > 0) { + ahead = MAX_REFRESH_AHEAD; + } + String value = JwtHelper.createJwtToken(algorithm, secret, issuer, subject, issuedAt, expiresAt); + return new Token(value, expiresAt.minus(ahead)); + } + + private record Token(String value, Instant refreshAt) { + boolean isDue(Instant now) { + return !now.isBefore(refreshAt); + } + } +} diff --git a/components/camel-grpc/src/test/java/org/apache/camel/component/grpc/GrpcConsumerJwtExpiryTest.java b/components/camel-grpc/src/test/java/org/apache/camel/component/grpc/GrpcConsumerJwtExpiryTest.java new file mode 100644 index 000000000000..1f507f67374c --- /dev/null +++ b/components/camel-grpc/src/test/java/org/apache/camel/component/grpc/GrpcConsumerJwtExpiryTest.java @@ -0,0 +1,183 @@ +/* + * 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.camel.component.grpc; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.TimeUnit; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import org.apache.camel.CamelExecutionException; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.grpc.auth.jwt.JwtAlgorithm; +import org.apache.camel.component.grpc.auth.jwt.JwtCallCredentials; +import org.apache.camel.component.grpc.auth.jwt.JwtHelper; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The consumer checks the exp (expires at) and iat (issued at) claims of the JSON Web Token. + */ +public class GrpcConsumerJwtExpiryTest extends GrpcTestSupport { + + private static final String SECRET = "jwtexpirysecret"; + private static final String PING = "PING"; + private static final String PONG = "PONG"; + + private ManagedChannel noMaxAgeChannel; + private ManagedChannel maxAgeChannel; + + @BeforeEach + public void startGrpcChannels() { + noMaxAgeChannel = ManagedChannelBuilder.forAddress("localhost", getRoutePort("grpc-jwt-no-max-age")) + .usePlaintext().build(); + maxAgeChannel = ManagedChannelBuilder.forAddress("localhost", getRoutePort("grpc-jwt-max-age")) + .usePlaintext().build(); + } + + @AfterEach + public void stopGrpcChannels() throws Exception { + noMaxAgeChannel.shutdown().awaitTermination(5, TimeUnit.SECONDS); + maxAgeChannel.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + + @Test + public void testTokenWithoutExpiryIsAcceptedWithoutMaxAge() { + String token = JwtHelper.createJwtToken(JwtAlgorithm.HMAC256, SECRET, null, null); + + assertEquals(PING + PONG, ping(noMaxAgeChannel, token).getPongName()); + } + + @Test + public void testExpiredTokenIsRejected() { + Instant now = Instant.now(); + String token = JwtHelper.createJwtToken(JwtAlgorithm.HMAC256, SECRET, null, null, + now.minus(Duration.ofHours(2)), now.minus(Duration.ofHours(1))); + + assertUnauthenticated(noMaxAgeChannel, token); + assertUnauthenticated(maxAgeChannel, token); + } + + @Test + public void testTokenWithinClockDifferenceIsAccepted() { + Instant now = Instant.now(); + // issued "in the future" and expired a little ago, as seen from a host whose clock differs by some seconds + String token = JwtHelper.createJwtToken(JwtAlgorithm.HMAC256, SECRET, null, null, + now.plus(Duration.ofSeconds(20)), now.minus(Duration.ofSeconds(20))); + + assertEquals(PING + PONG, ping(noMaxAgeChannel, token).getPongName()); + } + + @Test + public void testTokenOlderThanMaxAgeIsRejected() { + Instant now = Instant.now(); + String token = JwtHelper.createJwtToken(JwtAlgorithm.HMAC256, SECRET, null, null, + now.minus(Duration.ofHours(2)), now.plus(Duration.ofHours(1))); + + assertUnauthenticated(maxAgeChannel, token); + // the same token is accepted by a consumer without jwtMaxTokenAge + assertEquals(PING + PONG, ping(noMaxAgeChannel, token).getPongName()); + } + + @Test + public void testTokenWithoutIssuedAtIsRejectedWithMaxAge() { + String token = JwtHelper.createJwtToken(JwtAlgorithm.HMAC256, SECRET, null, null); + + assertUnauthenticated(maxAgeChannel, token); + } + + @Test + public void testRecentTokenIsAcceptedWithMaxAge() { + Instant now = Instant.now(); + String token = JwtHelper.createJwtToken(JwtAlgorithm.HMAC256, SECRET, null, null, + now.minus(Duration.ofMinutes(10)), now.plus(Duration.ofMinutes(50))); + + assertEquals(PING + PONG, ping(maxAgeChannel, token).getPongName()); + } + + @Test + public void testProducerTokenIsAcceptedWithMaxAge() { + Object reply = template.requestBody(producerUri(""), pingRequest()); + + assertEquals(PING + PONG, assertInstanceOf(PongResponse.class, reply).getPongName()); + } + + @Test + public void testProducerTokenWithoutExpiryIsRejectedWithMaxAge() { + CamelExecutionException e = assertThrows(CamelExecutionException.class, + () -> template.requestBody(producerUri("&jwtTokenLifetime=0"), pingRequest())); + + StatusRuntimeException cause = assertInstanceOf(StatusRuntimeException.class, e.getCause().getCause()); + assertEquals(Status.Code.UNAUTHENTICATED, cause.getStatus().getCode()); + assertTrue(cause.getMessage().contains("jwtMaxTokenAge"), cause.getMessage()); + } + + private String producerUri(String options) { + return "grpc://localhost:" + getRoutePort("grpc-jwt-max-age") + "/org.apache.camel.component.grpc.PingPong" + + "?method=pingSyncSync&synchronous=true&authenticationType=JWT&jwtSecret=" + SECRET + options; + } + + private static PingRequest pingRequest() { + return PingRequest.newBuilder().setPingName(PING).setPingId(1).build(); + } + + private static PongResponse ping(ManagedChannel channel, String token) { + return PingPongGrpc.newBlockingStub(channel).withCallCredentials(new JwtCallCredentials(token)) + .pingSyncSync(pingRequest()); + } + + private static void assertUnauthenticated(ManagedChannel channel, String token) { + StatusRuntimeException e = assertThrows(StatusRuntimeException.class, () -> ping(channel, token)); + assertEquals(Status.Code.UNAUTHENTICATED, e.getStatus().getCode()); + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("grpc://localhost:0/org.apache.camel.component.grpc.PingPong?synchronous=true" + + "&consumerStrategy=AGGREGATION&authenticationType=JWT&jwtSecret=" + SECRET) + .routeId("grpc-jwt-no-max-age") + .bean(new GrpcMessageBuilder(), "buildPongResponse"); + + from("grpc://localhost:0/org.apache.camel.component.grpc.PingPong?synchronous=true" + + "&consumerStrategy=AGGREGATION&authenticationType=JWT&jwtSecret=" + SECRET + + "&jwtMaxTokenAge=1h") + .routeId("grpc-jwt-max-age") + .bean(new GrpcMessageBuilder(), "buildPongResponse"); + + } + }; + } + + static class GrpcMessageBuilder { + public PongResponse buildPongResponse(PingRequest pingRequest) { + return PongResponse.newBuilder().setPongName(pingRequest.getPingName() + PONG) + .setPongId(pingRequest.getPingId()).build(); + } + } +} diff --git a/components/camel-grpc/src/test/java/org/apache/camel/component/grpc/auth/jwt/JwtTokenSupplierTest.java b/components/camel-grpc/src/test/java/org/apache/camel/component/grpc/auth/jwt/JwtTokenSupplierTest.java new file mode 100644 index 000000000000..7e2b654c9e53 --- /dev/null +++ b/components/camel-grpc/src/test/java/org/apache/camel/component/grpc/auth/jwt/JwtTokenSupplierTest.java @@ -0,0 +1,137 @@ +/* + * 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.camel.component.grpc.auth.jwt; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.interfaces.DecodedJWT; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class JwtTokenSupplierTest { + + private static final String SECRET = "supersecuredsecret"; + private static final Instant START = Instant.parse("2026-11-27T10:00:00Z"); + + @Test + void tokenHasIssuedAtAndExpiresAt() { + MutableClock clock = new MutableClock(START); + JwtTokenSupplier supplier = new JwtTokenSupplier( + JwtAlgorithm.HMAC256, SECRET, "issuer", "subject", Duration.ofHours(1), clock); + + DecodedJWT token = JWT.decode(supplier.get()); + + assertEquals(START, token.getIssuedAtAsInstant()); + assertEquals(START.plus(Duration.ofHours(1)), token.getExpiresAtAsInstant()); + assertEquals("issuer", token.getIssuer()); + assertEquals("subject", token.getSubject()); + } + + @Test + void tokenIsRefreshedOneMinuteBeforeExpiry() { + MutableClock clock = new MutableClock(START); + JwtTokenSupplier supplier = new JwtTokenSupplier( + JwtAlgorithm.HMAC256, SECRET, null, null, Duration.ofHours(1), clock); + + String first = supplier.get(); + clock.set(START.plus(Duration.ofMinutes(58))); + assertSame(first, supplier.get()); + + // one minute before the expiry, a new token is created + clock.set(START.plus(Duration.ofMinutes(59))); + String second = supplier.get(); + assertNotEquals(first, second); + DecodedJWT token = JWT.decode(second); + assertEquals(START.plus(Duration.ofMinutes(59)), token.getIssuedAtAsInstant()); + assertEquals(START.plus(Duration.ofMinutes(119)), token.getExpiresAtAsInstant()); + assertSame(second, supplier.get()); + } + + @Test + void shortTokenIsRefreshedWhenATenthOfTheLifetimeIsLeft() { + MutableClock clock = new MutableClock(START); + JwtTokenSupplier supplier = new JwtTokenSupplier( + JwtAlgorithm.HMAC256, SECRET, null, null, Duration.ofSeconds(10), clock); + + String first = supplier.get(); + clock.set(START.plus(Duration.ofMillis(8999))); + assertSame(first, supplier.get()); + + clock.set(START.plus(Duration.ofSeconds(9))); + DecodedJWT token = JWT.decode(supplier.get()); + assertEquals(START.plus(Duration.ofSeconds(9)), token.getIssuedAtAsInstant()); + assertEquals(START.plus(Duration.ofSeconds(19)), token.getExpiresAtAsInstant()); + } + + @Test + void zeroLifetimeCreatesTokenWithoutExpiry() { + MutableClock clock = new MutableClock(START); + JwtTokenSupplier supplier = new JwtTokenSupplier( + JwtAlgorithm.HMAC256, SECRET, null, null, Duration.ZERO, clock); + + String first = supplier.get(); + DecodedJWT token = JWT.decode(first); + assertNull(token.getIssuedAt()); + assertNull(token.getExpiresAt()); + + clock.set(START.plus(Duration.ofDays(365))); + assertSame(first, supplier.get()); + } + + @Test + void lifetimeBelowOneSecondIsRefused() { + assertThrows(IllegalArgumentException.class, + () -> new JwtTokenSupplier(JwtAlgorithm.HMAC256, SECRET, null, null, Duration.ofMillis(500))); + } + + private static final class MutableClock extends Clock { + private volatile Instant now; + + MutableClock(Instant now) { + this.now = now; + } + + void set(Instant now) { + this.now = now; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + } +} diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc index 842cdec20280..485c2ee68cd5 100644 --- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc +++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc @@ -12423,6 +12423,19 @@ With `mimeType` `PAGEABLE`, `PRINTABLE` or `RENDERABLE_IMAGE`, the producer now `java.awt.print.Pageable`, `java.awt.print.Printable` or `java.awt.image.renderable.RenderableImage`, as these doc flavors need, instead of a stream. With `sendToPrinter=false`, the body is still written to a file as bytes. +=== camel-grpc - JSON Web Tokens expire after one hour + +With `authenticationType=JWT`, the `grpc` producer now sends a token with the `iat` (issued at) and `exp` (expires at) +claims, valid for the new `jwtTokenLifetime` option (1 hour by default), and creates a new token before the current one +expires. Before, the producer created one token without these claims at startup, which was valid until `jwtSecret` +changed. A server that checks `exp` and `iat`, such as a Camel consumer, rejects a token issued in the future, so keep +the clocks of the hosts in sync (a Camel 4.24 consumer accepts a difference of up to one minute). Set +`jwtTokenLifetime=0` to send tokens without `iat` and `exp` as before. + +The consumer now accepts a clock difference of up to one minute for the `exp` and `iat` claims, and has the new +`jwtMaxTokenAge` option to reject tokens older than this age (by `iat`). Tokens without `exp` are still accepted by +default. + === Kamelets - removed Kamelets The Kamelet catalog (camel-kamelets 4.24) removes Kamelets that could not work on Camel 4.23 or 4.24: diff --git a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GrpcEndpointBuilderFactory.java b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GrpcEndpointBuilderFactory.java index 09e7bbf76932..d7e3de25f436 100644 --- a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GrpcEndpointBuilderFactory.java +++ b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GrpcEndpointBuilderFactory.java @@ -839,6 +839,46 @@ public interface GrpcEndpointBuilderFactory { doSetProperty("jwtIssuer", jwtIssuer); return this; } + /** + * The maximum age of a JSON Web Token that the consumer accepts, in + * milliseconds, from its iat (issued at) claim. When set, the consumer + * rejects tokens that are older, or that have no iat claim. The + * consumer always rejects a token whose exp (expires at) claim has + * passed. The default 0 does not check the age, so tokens without an + * exp claim are valid until jwtSecret changes. Used when + * authenticationType is JWT. + * + * The option is a: <code>long</code> type. + * + * Group: security + * + * @param jwtMaxTokenAge the value to set + * @return the dsl builder + */ + default GrpcEndpointConsumerBuilder jwtMaxTokenAge(long jwtMaxTokenAge) { + doSetProperty("jwtMaxTokenAge", jwtMaxTokenAge); + return this; + } + /** + * The maximum age of a JSON Web Token that the consumer accepts, in + * milliseconds, from its iat (issued at) claim. When set, the consumer + * rejects tokens that are older, or that have no iat claim. The + * consumer always rejects a token whose exp (expires at) claim has + * passed. The default 0 does not check the age, so tokens without an + * exp claim are valid until jwtSecret changes. Used when + * authenticationType is JWT. + * + * The option will be converted to a <code>long</code> type. + * + * Group: security + * + * @param jwtMaxTokenAge the value to set + * @return the dsl builder + */ + default GrpcEndpointConsumerBuilder jwtMaxTokenAge(String jwtMaxTokenAge) { + doSetProperty("jwtMaxTokenAge", jwtMaxTokenAge); + return this; + } /** * The secret key of the HMAC algorithm that signs the JSON Web Token on * the producer and verifies it on the consumer. Required when @@ -1642,6 +1682,46 @@ public interface GrpcEndpointBuilderFactory { doSetProperty("jwtSubject", jwtSubject); return this; } + /** + * How long a JSON Web Token that the producer sends is valid, in + * milliseconds: the token has the iat (issued at) claim and an exp + * (expires at) claim this much later. The producer creates a new token + * when less than a tenth of the lifetime, at most one minute, is left. + * A value of 0 sends a token without iat and exp claims, which is valid + * until jwtSecret changes. Used when authenticationType is JWT. + * + * The option is a: <code>long</code> type. + * + * Default: 3600000 + * Group: security + * + * @param jwtTokenLifetime the value to set + * @return the dsl builder + */ + default GrpcEndpointProducerBuilder jwtTokenLifetime(long jwtTokenLifetime) { + doSetProperty("jwtTokenLifetime", jwtTokenLifetime); + return this; + } + /** + * How long a JSON Web Token that the producer sends is valid, in + * milliseconds: the token has the iat (issued at) claim and an exp + * (expires at) claim this much later. The producer creates a new token + * when less than a tenth of the lifetime, at most one minute, is left. + * A value of 0 sends a token without iat and exp claims, which is valid + * until jwtSecret changes. Used when authenticationType is JWT. + * + * The option will be converted to a <code>long</code> type. + * + * Default: 3600000 + * Group: security + * + * @param jwtTokenLifetime the value to set + * @return the dsl builder + */ + default GrpcEndpointProducerBuilder jwtTokenLifetime(String jwtTokenLifetime) { + doSetProperty("jwtTokenLifetime", jwtTokenLifetime); + return this; + } /** * The location of the X.509 certificate chain in PEM format. For the * consumer, the certificate of the server, required with TLS. For the
