This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new cd5fb084faff CAMEL-27144: camel-ai-tool - allowedRoles option to
authorize a tool call by the caller's roles (#30317)
cd5fb084faff is described below
commit cd5fb084faff1ee025233f9af211d3ba6969f53b
Author: Serdar Gökay <[email protected]>
AuthorDate: Wed Nov 18 15:20:22 2026 +0300
CAMEL-27144: camel-ai-tool - allowedRoles option to authorize a tool call
by the caller's roles (#30317)
A tool route can name the roles its caller needs: allowedRoles
(comma-separated,
any one of them) and allRolesRequired (all of them). The check runs in
front of
the route, where authorizationPolicy is applied, and reads the caller's
roles
only from the CamelMcpSecurityPrincipalRoles exchange property that the MCP
server sets since CAMEL-25405. A call without that property is refused.
An allowedRoles that is set but names no role refuses every call; the route
starts and a WARN names the tool. Not set means no check, so existing routes
are unchanged.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
---
.../apache/camel/catalog/components/ai-tool.json | 8 +-
.../camel/catalog/docs/ai-tool-component.adoc | 99 ++++-
.../org/apache/camel/catalog/docs/mcp-server.adoc | 12 +-
.../ai/tool/AiToolComponentConfigurer.java | 12 +
.../ai/tool/AiToolConfigurationConfigurer.java | 12 +
.../ai/tool/AiToolEndpointConfigurer.java | 12 +
.../ai/tool/AiToolEndpointUriFactory.java | 4 +-
.../apache/camel/component/ai/tool/ai-tool.json | 8 +-
.../src/main/docs/ai-tool-component.adoc | 99 ++++-
.../ai/tool/AiToolAllowedRolesProcessor.java | 116 ++++++
.../ai/tool/AiToolAuthorizationDeniedEvent.java | 6 +-
.../component/ai/tool/AiToolConfiguration.java | 31 ++
.../camel/component/ai/tool/AiToolConstants.java | 22 +-
.../camel/component/ai/tool/AiToolConsumer.java | 80 ++--
.../camel/component/ai/tool/AiToolExecutor.java | 6 +-
.../camel/component/ai/tool/AiToolResult.java | 10 +-
.../ai/tool/AiToolAllowedRolesStartupTest.java | 83 ++++
.../component/ai/tool/AiToolAllowedRolesTest.java | 444 +++++++++++++++++++++
.../ai/tool/AiToolComponentAllowedRolesTest.java | 204 ++++++++++
.../component/mcp/server/McpServerBridge.java | 2 +-
.../component/mcp/server/McpToolCallContext.java | 13 +-
.../camel-mcp-server/src/main/docs/mcp-server.adoc | 12 +-
.../mcp/server/vertx/VertxMcpPrincipal.java | 5 +-
.../server/main/McpServerMainAllowedRolesTest.java | 178 +++++++++
.../main/McpServerMainAuthenticationTest.java | 8 +-
.../mcp/server/main/McpServerMainOAuthTest.java | 35 +-
.../src/main/java/org/apache/camel/ai/AiEvent.java | 6 +-
.../dsl/AiToolComponentBuilderFactory.java | 42 ++
.../endpoint/dsl/AiToolEndpointBuilderFactory.java | 53 +++
29 files changed, 1537 insertions(+), 85 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/ai-tool.json
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/ai-tool.json
index b0d2d153f464..ffb0d797818a 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/ai-tool.json
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/ai-tool.json
@@ -41,7 +41,9 @@
"tags": { "index": 14, "kind": "property", "displayName": "Tags", "group":
"consumer", "label": "consumer", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Comma-separated list of tags used to group
tools. Producers filter the registry by these tags to select which tools to
[...]
"title": { "index": 15, "kind": "property", "displayName": "Title",
"group": "consumer", "label": "consumer", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Optional display title for MCP tool listings.
Advisory hint for MCP clients only." },
"autowiredEnabled": { "index": 16, "kind": "property", "displayName":
"Autowired Enabled", "group": "advanced", "label": "advanced", "required":
false, "type": "boolean", "javaType": "boolean", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": true, "description":
"Whether autowiring is enabled. This is used for automatic autowiring options
(the option must be marked as autowired) by looking up in the registry to find
if there is a single instance of matching [...]
- "authorizationPolicy": { "index": 17, "kind": "property", "displayName":
"Authorization Policy", "group": "security", "label": "consumer,security",
"required": false, "type": "object", "javaType":
"org.apache.camel.spi.AuthorizationPolicy", "deprecated": false, "autowired":
false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Reference to an
org.apache.camel.spi.AuthorizationPoli [...]
+ "allowedRoles": { "index": 17, "kind": "property", "displayName": "Allowed
Roles", "group": "security", "label": "consumer,security", "required": false,
"type": "string", "javaType": "java.lang.String", "deprecated": false,
"autowired": false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Comma-separated list of the roles a caller
needs to call the tool, for example finance,contr [...]
+ "allRolesRequired": { "index": 18, "kind": "property", "displayName": "All
Roles Required", "group": "security", "label": "consumer,security", "required":
false, "type": "boolean", "javaType": "boolean", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": false,
"configurationClass": "org.apache.camel.component.ai.tool.AiToolConfiguration",
"configurationField": "configuration", "description": "Whether the caller needs
all the roles in allowedRoles, rather than [...]
+ "authorizationPolicy": { "index": 19, "kind": "property", "displayName":
"Authorization Policy", "group": "security", "label": "consumer,security",
"required": false, "type": "object", "javaType":
"org.apache.camel.spi.AuthorizationPolicy", "deprecated": false, "autowired":
false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Reference to an
org.apache.camel.spi.AuthorizationPoli [...]
},
"headers": {
"CamelAiToolCallId": { "index": 0, "kind": "header", "displayName": "",
"group": "consumer", "label": "consumer", "required": false, "javaType":
"String", "deprecated": false, "autowired": false, "secret": false,
"description": "The tool invocation identifier supplied by the calling
framework. Absent when the framework does not supply one.", "constantName":
"org.apache.camel.component.ai.tool.AiToolConstants#TOOL_CALL_ID" },
@@ -70,6 +72,8 @@
"bridgeErrorHandler": { "index": 15, "kind": "parameter", "displayName":
"Bridge Error Handler", "group": "consumer (advanced)", "label":
"consumer,advanced", "required": false, "type": "boolean", "javaType":
"boolean", "deprecated": false, "autowired": false, "secret": false,
"defaultValue": false, "description": "Allows for bridging the consumer to the
Camel routing Error Handler, which mean any exceptions (if possible) occurred
while the Camel consumer is trying to pickup incoming [...]
"exceptionHandler": { "index": 16, "kind": "parameter", "displayName":
"Exception Handler", "group": "consumer (advanced)", "label":
"consumer,advanced", "required": false, "type": "object", "javaType":
"org.apache.camel.spi.ExceptionHandler", "optionalPrefix": "consumer.",
"deprecated": false, "autowired": false, "secret": false, "description": "To
let the consumer use a custom ExceptionHandler. Notice if the option
bridgeErrorHandler is enabled then this option is not in use. By de [...]
"exchangePattern": { "index": 17, "kind": "parameter", "displayName":
"Exchange Pattern", "group": "consumer (advanced)", "label":
"consumer,advanced", "required": false, "type": "enum", "javaType":
"org.apache.camel.ExchangePattern", "enum": [ "InOnly", "InOut" ],
"deprecated": false, "autowired": false, "secret": false, "description": "Sets
the exchange pattern when the consumer creates an exchange." },
- "authorizationPolicy": { "index": 18, "kind": "parameter", "displayName":
"Authorization Policy", "group": "security", "label": "consumer,security",
"required": false, "type": "object", "javaType":
"org.apache.camel.spi.AuthorizationPolicy", "deprecated": false, "autowired":
false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Reference to an
org.apache.camel.spi.AuthorizationPol [...]
+ "allowedRoles": { "index": 18, "kind": "parameter", "displayName":
"Allowed Roles", "group": "security", "label": "consumer,security", "required":
false, "type": "string", "javaType": "java.lang.String", "deprecated": false,
"autowired": false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Comma-separated list of the roles a caller
needs to call the tool, for example finance,cont [...]
+ "allRolesRequired": { "index": 19, "kind": "parameter", "displayName":
"All Roles Required", "group": "security", "label": "consumer,security",
"required": false, "type": "boolean", "javaType": "boolean", "deprecated":
false, "autowired": false, "secret": false, "defaultValue": false,
"configurationClass": "org.apache.camel.component.ai.tool.AiToolConfiguration",
"configurationField": "configuration", "description": "Whether the caller needs
all the roles in allowedRoles, rather than [...]
+ "authorizationPolicy": { "index": 20, "kind": "parameter", "displayName":
"Authorization Policy", "group": "security", "label": "consumer,security",
"required": false, "type": "object", "javaType":
"org.apache.camel.spi.AuthorizationPolicy", "deprecated": false, "autowired":
false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Reference to an
org.apache.camel.spi.AuthorizationPol [...]
}
}
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ai-tool-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ai-tool-component.adoc
index 88f381f58828..a656f564715b 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ai-tool-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ai-tool-component.adoc
@@ -444,6 +444,9 @@ an `authorizationPolicy` — a reference to an
`org.apache.camel.spi.Authorizati
call before the route runs. Set it on the *component* to guard every tool
route by construction, or on a single
endpoint to override.
+When the rule is which roles the caller needs, the `allowedRoles` option
states it on the endpoint and no policy bean
+is needed: see <<Authorizing by role>> below.
+
[tabs]
====
Java::
@@ -501,16 +504,91 @@ Which runtimes carry the caller identity:
* Over the xref:others:mcp-server.adoc[MCP server] the authenticated transport
caller is carried onto the tool
exchange as the `CamelMcpSecurityPrincipal` property (the raw transport
principal — for the Vert.x streamable HTTP
server, an `io.vertx.ext.auth.User`). Alongside it the server stamps a
runtime-neutral view derived from that
- principal — `CamelMcpSecurityPrincipalName` (a `String`) and
`CamelMcpSecurityPrincipalRoles` (a
+ principal — `CamelAiToolSecurityPrincipalName` (a `String`) and
`CamelAiToolSecurityPrincipalRoles` (a
`Collection<String>`) — so a tool route or a policy can authorize on a
stable name and roles without knowing the
runtime type. Only the Vert.x streamable HTTP server (Camel Main / JBang)
populates these today. There the name is
- the user subject (or the `username`/`sub` claim), and the roles come from
the authenticated token's `roles`, Keycloak
- `realm_access.roles`, or `groups` claim (JWT/OIDC); a basic-auth caller
(camel-main property-file auth) carries no
- roles in its principal, so `CamelMcpSecurityPrincipalRoles` is not set for
it. Each property is set only when the
- server could determine it, so treat a missing name or roles as unauthorized.
Camel's shipped identity/token
- policies (Keycloak, Spring Security, Shiro) do not consume these
automatically yet, so MCP authorization still needs
- a policy (or route guard) that inspects
`CamelMcpSecurityPrincipalName`/`CamelMcpSecurityPrincipalRoles` or the raw
- `CamelMcpSecurityPrincipal`.
+ the user subject (or the `username`/`sub` claim), and the roles come from
the first of the authenticated token's
+ `roles`, Keycloak `realm_access.roles`, or `groups` claim that is an array
(JWT/OIDC); a basic-auth caller
+ (camel-main property-file auth) carries no roles in its principal, so
`CamelAiToolSecurityPrincipalRoles` is not set
+ for it. Each property is set only when the server could determine it, so
treat a missing name or roles as
+ unauthorized. The `allowedRoles` option checks
`CamelAiToolSecurityPrincipalRoles` (see <<Authorizing by role>>
+ below), so authorizing an MCP caller by role needs no code. Camel's shipped
identity/token policies (Keycloak,
+ Spring Security, Shiro) do not consume these properties automatically yet,
so any other rule over MCP, for example
+ on the caller's name or on a claim, still needs a policy (or route guard)
that inspects
+ `CamelAiToolSecurityPrincipalName`/`CamelAiToolSecurityPrincipalRoles` or
the raw `CamelMcpSecurityPrincipal`.
+
+=== Authorizing by role
+
+Set `allowedRoles` on a tool to name the roles its caller needs, as a
comma-separated list. The check needs no Java
+code. The caller needs one of the roles; with `allRolesRequired=true` the
caller needs all of them. A role name is
+compared exactly.
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("ai-tool:orderCosts?tags=erp&description=Costs of a production
order&allowedRoles=finance,controlling")
+ .to("bean:costs");
+
+// ...or as the default of every ai-tool route, which an endpoint replaces
with its own value
+AiToolComponent ai = context.getComponent("ai-tool", AiToolComponent.class);
+ai.getConfiguration().setAllowedRoles("finance,controlling");
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: ai-tool:orderCosts
+ parameters:
+ tags: erp
+ description: "Costs of a production order"
+ allowedRoles: finance,controlling
+ steps:
+ - to:
+ uri: bean:costs
+----
+====
+
+The caller's roles are read only from the exchange property
`CamelAiToolSecurityPrincipalRoles` (a
+`Collection<String>`). A role named in a message header or in a tool argument
never counts: on a tool route the
+headers carry the tool arguments, which the model controls. A call without
that property is refused.
+
+* Over the xref:others:mcp-server.adoc[MCP server] the server sets the
property from the roles of the authenticated
+ caller. That page says which claim of the token the roles are read from. A
caller without roles, such as a
+ basic-auth caller, is refused. Over stdio, or on an MCP server without
authentication, no caller has roles, so a
+ tool with `allowedRoles` refuses every call. The same holds on a runtime
whose MCP engine
+ does not set the property.
+* With `camel-langchain4j-agent`, `camel-openai` and `camel-spring-ai-chat`
the calling route sets the same property
+ before the agent runs, from the identity it has authenticated. The tool
exchange is a copy of the calling exchange
+ (see <<The calling exchange>> above), so the property reaches the tool route:
++
+[source,java]
+----
+from("platform-http:/assistant")
+ // the roles of the caller this route has authenticated: here a bean reads
them from the validated token
+ .setProperty("CamelAiToolSecurityPrincipalRoles", method("callerIdentity",
"roles"))
+ .to("langchain4j-agent:assistant?agentConfiguration=#myConfig&tags=erp");
+----
+
+When a call is refused, the model gets the same short refusal as for a denial
by an `authorizationPolicy`, and the
+denial is logged and published as described in <<Observing denials>> below.
The log entry names the tool, the roles
+it asks for and, when the `CamelAiToolSecurityPrincipalName` property is set,
the caller. The model is told none of
+this.
+
+`allowedRoles` and `authorizationPolicy` can be set on the same tool, and then
both must pass. The roles are checked
+first, and a call that fails them does not reach the policy. This combines a
role with a rule that needs more than a
+role, for example a xref:cedar-component.adoc[Cedar] or
xref:opa-component.adoc[OPA] policy over attributes.
+
+Set on the *component*, `allowedRoles` and `allRolesRequired` are the default
of every tool route, and an endpoint's
+own value replaces the component's. An endpoint can therefore replace the
component's roles, but it cannot remove the
+check: a value that names no role, such as an empty one, refuses every call.
The route still starts, and a `WARN` at
+its start names the tool. Only an option that is not set takes the component's
value; that includes an optional
+placeholder (`{{?name}}`) whose property is absent.
=== Observing denials
@@ -520,7 +598,8 @@ exchange-lifecycle event or route span. Every denial is
instead:
* logged at `WARN`, and
* published as an
`org.apache.camel.component.ai.tool.AiToolAuthorizationDeniedEvent` — an
`org.apache.camel.ai.AiEvent.ToolCallDeniedEvent` (a `CamelEvent` of type
`Ai`) carrying the denied tool name, the
- tool exchange (for correlation), and the `CamelAuthorizationException` the
policy raised.
+ tool exchange (for correlation), and the `CamelAuthorizationException` that
refused the call. For a call that the
+ `allowedRoles` check refused, its `getPolicyId()` returns `allowedRoles`.
Register an `EventNotifier` to count, log or alert on denials — for example to
drive a micrometer counter — without
changing what the model sees (still the short refusal). Match on the shared
`AiEvent.ToolCallDeniedEvent` interface so
@@ -545,7 +624,7 @@ never affects the refusal returned to the model.
`searchable` controls whether a route tool is sent to the model immediately or
only after a producer with tool search enabled finds it. The default is
`false`, so the tool stays directly visible. `searchable=true` omits the tool
from the initial model request and makes it eligible for search together with
remote MCP tools.
-Searchability is a visibility policy. It does not authorize the call. An
`authorizationPolicy` on the tool is still applied when the model invokes it.
With tool search disabled on the producer, `searchable` has no effect and the
tool is exposed as before.
+Searchability is a visibility policy. It does not authorize the call. The
`allowedRoles` and the `authorizationPolicy` of the tool are still applied when
the model invokes it. With tool search disabled on the producer, `searchable`
has no effect and the tool is exposed as before.
[source,yaml]
----
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mcp-server.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mcp-server.adoc
index 405061078c75..67029722e767 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mcp-server.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mcp-server.adoc
@@ -495,9 +495,15 @@ For an authenticated tool call, the bridge exposes the
following exchange proper
* `CamelMcpOAuthSubject`, `CamelMcpOAuthScopes`, and `CamelMcpOAuthClaims`
contain the subject,
scopes, and claims from the validated token.
-* `CamelMcpSecurityPrincipalName` and `CamelMcpSecurityPrincipalRoles` expose
the runtime-neutral
- caller name and roles when available. Roles are extracted from common
`roles`,
- `realm_access.roles`, or `groups` claim shapes.
+* `CamelAiToolSecurityPrincipalName` and `CamelAiToolSecurityPrincipalRoles`
expose the runtime-neutral
+ caller name and roles when available. The roles are the first of the `roles`,
+ `realm_access.roles` and `groups` claims that is an array: the claims are
not merged, and
+ client roles (`resource_access`) are not read. With Keycloak, realm roles
work as issued, and a
+ client role or a group needs a mapper into the `roles` claim, which is then
read instead of the
+ realm roles; the group mapper writes the full path (`/finance-team`) unless
its "Full group path"
+ switch is off. The `allowedRoles` option of an
xref:ROOT:ai-tool-component.adoc[ai-tool] route
+ checks these roles before the route runs. Without an authenticated caller,
as over stdio or on a
+ server without authentication, they are not set and a tool with
`allowedRoles` refuses every call.
* `CamelOAuthTokenValidationResult` contains the full Camel OAuth validation
result for route code
that already consumes the standard HTTP OAuth exchange property.
diff --git
a/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolComponentConfigurer.java
b/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolComponentConfigurer.java
index 4e227fec8af4..b1a2f592b4fe 100644
---
a/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolComponentConfigurer.java
+++
b/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolComponentConfigurer.java
@@ -31,6 +31,10 @@ public class AiToolComponentConfigurer extends
PropertyConfigurerSupport impleme
public boolean configure(CamelContext camelContext, Object obj, String
name, Object value, boolean ignoreCase) {
AiToolComponent target = (AiToolComponent) obj;
switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) {
+ case "allrolesrequired":
+ case "allRolesRequired":
getOrCreateConfiguration(target).setAllRolesRequired(property(camelContext,
boolean.class, value)); return true;
+ case "allowedroles":
+ case "allowedRoles":
getOrCreateConfiguration(target).setAllowedRoles(property(camelContext,
java.lang.String.class, value)); return true;
case "argschema":
case "argSchema":
getOrCreateConfiguration(target).setArgSchema(property(camelContext,
java.lang.String.class, value)); return true;
case "argumentsasbody":
@@ -68,6 +72,10 @@ public class AiToolComponentConfigurer extends
PropertyConfigurerSupport impleme
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) {
+ case "allrolesrequired":
+ case "allRolesRequired": return boolean.class;
+ case "allowedroles":
+ case "allowedRoles": return java.lang.String.class;
case "argschema":
case "argSchema": return java.lang.String.class;
case "argumentsasbody":
@@ -106,6 +114,10 @@ public class AiToolComponentConfigurer extends
PropertyConfigurerSupport impleme
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
AiToolComponent target = (AiToolComponent) obj;
switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) {
+ case "allrolesrequired":
+ case "allRolesRequired": return
getOrCreateConfiguration(target).isAllRolesRequired();
+ case "allowedroles":
+ case "allowedRoles": return
getOrCreateConfiguration(target).getAllowedRoles();
case "argschema":
case "argSchema": return
getOrCreateConfiguration(target).getArgSchema();
case "argumentsasbody":
diff --git
a/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolConfigurationConfigurer.java
b/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolConfigurationConfigurer.java
index 96088b115415..3470e8b19085 100644
---
a/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolConfigurationConfigurer.java
+++
b/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolConfigurationConfigurer.java
@@ -24,6 +24,10 @@ public class AiToolConfigurationConfigurer extends
org.apache.camel.support.comp
public boolean configure(CamelContext camelContext, Object obj, String
name, Object value, boolean ignoreCase) {
org.apache.camel.component.ai.tool.AiToolConfiguration target =
(org.apache.camel.component.ai.tool.AiToolConfiguration) obj;
switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) {
+ case "allrolesrequired":
+ case "allRolesRequired":
target.setAllRolesRequired(property(camelContext, boolean.class, value));
return true;
+ case "allowedroles":
+ case "allowedRoles": target.setAllowedRoles(property(camelContext,
java.lang.String.class, value)); return true;
case "argschema":
case "argSchema": target.setArgSchema(property(camelContext,
java.lang.String.class, value)); return true;
case "argumentsasbody":
@@ -56,6 +60,10 @@ public class AiToolConfigurationConfigurer extends
org.apache.camel.support.comp
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) {
+ case "allrolesrequired":
+ case "allRolesRequired": return boolean.class;
+ case "allowedroles":
+ case "allowedRoles": return java.lang.String.class;
case "argschema":
case "argSchema": return java.lang.String.class;
case "argumentsasbody":
@@ -89,6 +97,10 @@ public class AiToolConfigurationConfigurer extends
org.apache.camel.support.comp
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.component.ai.tool.AiToolConfiguration target =
(org.apache.camel.component.ai.tool.AiToolConfiguration) obj;
switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) {
+ case "allrolesrequired":
+ case "allRolesRequired": return target.isAllRolesRequired();
+ case "allowedroles":
+ case "allowedRoles": return target.getAllowedRoles();
case "argschema":
case "argSchema": return target.getArgSchema();
case "argumentsasbody":
diff --git
a/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolEndpointConfigurer.java
b/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolEndpointConfigurer.java
index cc7adcfe378e..788cd8c87f9f 100644
---
a/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolEndpointConfigurer.java
+++
b/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolEndpointConfigurer.java
@@ -24,6 +24,10 @@ public class AiToolEndpointConfigurer extends
PropertyConfigurerSupport implemen
public boolean configure(CamelContext camelContext, Object obj, String
name, Object value, boolean ignoreCase) {
AiToolEndpoint target = (AiToolEndpoint) obj;
switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) {
+ case "allrolesrequired":
+ case "allRolesRequired":
target.getConfiguration().setAllRolesRequired(property(camelContext,
boolean.class, value)); return true;
+ case "allowedroles":
+ case "allowedRoles":
target.getConfiguration().setAllowedRoles(property(camelContext,
java.lang.String.class, value)); return true;
case "argschema":
case "argSchema":
target.getConfiguration().setArgSchema(property(camelContext,
java.lang.String.class, value)); return true;
case "argumentsasbody":
@@ -62,6 +66,10 @@ public class AiToolEndpointConfigurer extends
PropertyConfigurerSupport implemen
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) {
+ case "allrolesrequired":
+ case "allRolesRequired": return boolean.class;
+ case "allowedroles":
+ case "allowedRoles": return java.lang.String.class;
case "argschema":
case "argSchema": return java.lang.String.class;
case "argumentsasbody":
@@ -101,6 +109,10 @@ public class AiToolEndpointConfigurer extends
PropertyConfigurerSupport implemen
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
AiToolEndpoint target = (AiToolEndpoint) obj;
switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) {
+ case "allrolesrequired":
+ case "allRolesRequired": return
target.getConfiguration().isAllRolesRequired();
+ case "allowedroles":
+ case "allowedRoles": return
target.getConfiguration().getAllowedRoles();
case "argschema":
case "argSchema": return target.getConfiguration().getArgSchema();
case "argumentsasbody":
diff --git
a/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolEndpointUriFactory.java
b/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolEndpointUriFactory.java
index 607007de5688..382c27f10719 100644
---
a/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolEndpointUriFactory.java
+++
b/components/camel-ai/camel-ai-tool/src/generated/java/org/apache/camel/component/ai/tool/AiToolEndpointUriFactory.java
@@ -24,7 +24,9 @@ public class AiToolEndpointUriFactory extends
org.apache.camel.support.component
private static final Set<String> ENDPOINT_IDENTITY_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
- Set<String> props = new HashSet<>(19);
+ Set<String> props = new HashSet<>(21);
+ props.add("allRolesRequired");
+ props.add("allowedRoles");
props.add("argSchema");
props.add("argumentsAsBody");
props.add("authorizationPolicy");
diff --git
a/components/camel-ai/camel-ai-tool/src/generated/resources/META-INF/org/apache/camel/component/ai/tool/ai-tool.json
b/components/camel-ai/camel-ai-tool/src/generated/resources/META-INF/org/apache/camel/component/ai/tool/ai-tool.json
index b0d2d153f464..ffb0d797818a 100644
---
a/components/camel-ai/camel-ai-tool/src/generated/resources/META-INF/org/apache/camel/component/ai/tool/ai-tool.json
+++
b/components/camel-ai/camel-ai-tool/src/generated/resources/META-INF/org/apache/camel/component/ai/tool/ai-tool.json
@@ -41,7 +41,9 @@
"tags": { "index": 14, "kind": "property", "displayName": "Tags", "group":
"consumer", "label": "consumer", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Comma-separated list of tags used to group
tools. Producers filter the registry by these tags to select which tools to
[...]
"title": { "index": 15, "kind": "property", "displayName": "Title",
"group": "consumer", "label": "consumer", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Optional display title for MCP tool listings.
Advisory hint for MCP clients only." },
"autowiredEnabled": { "index": 16, "kind": "property", "displayName":
"Autowired Enabled", "group": "advanced", "label": "advanced", "required":
false, "type": "boolean", "javaType": "boolean", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": true, "description":
"Whether autowiring is enabled. This is used for automatic autowiring options
(the option must be marked as autowired) by looking up in the registry to find
if there is a single instance of matching [...]
- "authorizationPolicy": { "index": 17, "kind": "property", "displayName":
"Authorization Policy", "group": "security", "label": "consumer,security",
"required": false, "type": "object", "javaType":
"org.apache.camel.spi.AuthorizationPolicy", "deprecated": false, "autowired":
false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Reference to an
org.apache.camel.spi.AuthorizationPoli [...]
+ "allowedRoles": { "index": 17, "kind": "property", "displayName": "Allowed
Roles", "group": "security", "label": "consumer,security", "required": false,
"type": "string", "javaType": "java.lang.String", "deprecated": false,
"autowired": false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Comma-separated list of the roles a caller
needs to call the tool, for example finance,contr [...]
+ "allRolesRequired": { "index": 18, "kind": "property", "displayName": "All
Roles Required", "group": "security", "label": "consumer,security", "required":
false, "type": "boolean", "javaType": "boolean", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": false,
"configurationClass": "org.apache.camel.component.ai.tool.AiToolConfiguration",
"configurationField": "configuration", "description": "Whether the caller needs
all the roles in allowedRoles, rather than [...]
+ "authorizationPolicy": { "index": 19, "kind": "property", "displayName":
"Authorization Policy", "group": "security", "label": "consumer,security",
"required": false, "type": "object", "javaType":
"org.apache.camel.spi.AuthorizationPolicy", "deprecated": false, "autowired":
false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Reference to an
org.apache.camel.spi.AuthorizationPoli [...]
},
"headers": {
"CamelAiToolCallId": { "index": 0, "kind": "header", "displayName": "",
"group": "consumer", "label": "consumer", "required": false, "javaType":
"String", "deprecated": false, "autowired": false, "secret": false,
"description": "The tool invocation identifier supplied by the calling
framework. Absent when the framework does not supply one.", "constantName":
"org.apache.camel.component.ai.tool.AiToolConstants#TOOL_CALL_ID" },
@@ -70,6 +72,8 @@
"bridgeErrorHandler": { "index": 15, "kind": "parameter", "displayName":
"Bridge Error Handler", "group": "consumer (advanced)", "label":
"consumer,advanced", "required": false, "type": "boolean", "javaType":
"boolean", "deprecated": false, "autowired": false, "secret": false,
"defaultValue": false, "description": "Allows for bridging the consumer to the
Camel routing Error Handler, which mean any exceptions (if possible) occurred
while the Camel consumer is trying to pickup incoming [...]
"exceptionHandler": { "index": 16, "kind": "parameter", "displayName":
"Exception Handler", "group": "consumer (advanced)", "label":
"consumer,advanced", "required": false, "type": "object", "javaType":
"org.apache.camel.spi.ExceptionHandler", "optionalPrefix": "consumer.",
"deprecated": false, "autowired": false, "secret": false, "description": "To
let the consumer use a custom ExceptionHandler. Notice if the option
bridgeErrorHandler is enabled then this option is not in use. By de [...]
"exchangePattern": { "index": 17, "kind": "parameter", "displayName":
"Exchange Pattern", "group": "consumer (advanced)", "label":
"consumer,advanced", "required": false, "type": "enum", "javaType":
"org.apache.camel.ExchangePattern", "enum": [ "InOnly", "InOut" ],
"deprecated": false, "autowired": false, "secret": false, "description": "Sets
the exchange pattern when the consumer creates an exchange." },
- "authorizationPolicy": { "index": 18, "kind": "parameter", "displayName":
"Authorization Policy", "group": "security", "label": "consumer,security",
"required": false, "type": "object", "javaType":
"org.apache.camel.spi.AuthorizationPolicy", "deprecated": false, "autowired":
false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Reference to an
org.apache.camel.spi.AuthorizationPol [...]
+ "allowedRoles": { "index": 18, "kind": "parameter", "displayName":
"Allowed Roles", "group": "security", "label": "consumer,security", "required":
false, "type": "string", "javaType": "java.lang.String", "deprecated": false,
"autowired": false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Comma-separated list of the roles a caller
needs to call the tool, for example finance,cont [...]
+ "allRolesRequired": { "index": 19, "kind": "parameter", "displayName":
"All Roles Required", "group": "security", "label": "consumer,security",
"required": false, "type": "boolean", "javaType": "boolean", "deprecated":
false, "autowired": false, "secret": false, "defaultValue": false,
"configurationClass": "org.apache.camel.component.ai.tool.AiToolConfiguration",
"configurationField": "configuration", "description": "Whether the caller needs
all the roles in allowedRoles, rather than [...]
+ "authorizationPolicy": { "index": 20, "kind": "parameter", "displayName":
"Authorization Policy", "group": "security", "label": "consumer,security",
"required": false, "type": "object", "javaType":
"org.apache.camel.spi.AuthorizationPolicy", "deprecated": false, "autowired":
false, "secret": false, "configurationClass":
"org.apache.camel.component.ai.tool.AiToolConfiguration", "configurationField":
"configuration", "description": "Reference to an
org.apache.camel.spi.AuthorizationPol [...]
}
}
diff --git
a/components/camel-ai/camel-ai-tool/src/main/docs/ai-tool-component.adoc
b/components/camel-ai/camel-ai-tool/src/main/docs/ai-tool-component.adoc
index 88f381f58828..a656f564715b 100644
--- a/components/camel-ai/camel-ai-tool/src/main/docs/ai-tool-component.adoc
+++ b/components/camel-ai/camel-ai-tool/src/main/docs/ai-tool-component.adoc
@@ -444,6 +444,9 @@ an `authorizationPolicy` — a reference to an
`org.apache.camel.spi.Authorizati
call before the route runs. Set it on the *component* to guard every tool
route by construction, or on a single
endpoint to override.
+When the rule is which roles the caller needs, the `allowedRoles` option
states it on the endpoint and no policy bean
+is needed: see <<Authorizing by role>> below.
+
[tabs]
====
Java::
@@ -501,16 +504,91 @@ Which runtimes carry the caller identity:
* Over the xref:others:mcp-server.adoc[MCP server] the authenticated transport
caller is carried onto the tool
exchange as the `CamelMcpSecurityPrincipal` property (the raw transport
principal — for the Vert.x streamable HTTP
server, an `io.vertx.ext.auth.User`). Alongside it the server stamps a
runtime-neutral view derived from that
- principal — `CamelMcpSecurityPrincipalName` (a `String`) and
`CamelMcpSecurityPrincipalRoles` (a
+ principal — `CamelAiToolSecurityPrincipalName` (a `String`) and
`CamelAiToolSecurityPrincipalRoles` (a
`Collection<String>`) — so a tool route or a policy can authorize on a
stable name and roles without knowing the
runtime type. Only the Vert.x streamable HTTP server (Camel Main / JBang)
populates these today. There the name is
- the user subject (or the `username`/`sub` claim), and the roles come from
the authenticated token's `roles`, Keycloak
- `realm_access.roles`, or `groups` claim (JWT/OIDC); a basic-auth caller
(camel-main property-file auth) carries no
- roles in its principal, so `CamelMcpSecurityPrincipalRoles` is not set for
it. Each property is set only when the
- server could determine it, so treat a missing name or roles as unauthorized.
Camel's shipped identity/token
- policies (Keycloak, Spring Security, Shiro) do not consume these
automatically yet, so MCP authorization still needs
- a policy (or route guard) that inspects
`CamelMcpSecurityPrincipalName`/`CamelMcpSecurityPrincipalRoles` or the raw
- `CamelMcpSecurityPrincipal`.
+ the user subject (or the `username`/`sub` claim), and the roles come from
the first of the authenticated token's
+ `roles`, Keycloak `realm_access.roles`, or `groups` claim that is an array
(JWT/OIDC); a basic-auth caller
+ (camel-main property-file auth) carries no roles in its principal, so
`CamelAiToolSecurityPrincipalRoles` is not set
+ for it. Each property is set only when the server could determine it, so
treat a missing name or roles as
+ unauthorized. The `allowedRoles` option checks
`CamelAiToolSecurityPrincipalRoles` (see <<Authorizing by role>>
+ below), so authorizing an MCP caller by role needs no code. Camel's shipped
identity/token policies (Keycloak,
+ Spring Security, Shiro) do not consume these properties automatically yet,
so any other rule over MCP, for example
+ on the caller's name or on a claim, still needs a policy (or route guard)
that inspects
+ `CamelAiToolSecurityPrincipalName`/`CamelAiToolSecurityPrincipalRoles` or
the raw `CamelMcpSecurityPrincipal`.
+
+=== Authorizing by role
+
+Set `allowedRoles` on a tool to name the roles its caller needs, as a
comma-separated list. The check needs no Java
+code. The caller needs one of the roles; with `allRolesRequired=true` the
caller needs all of them. A role name is
+compared exactly.
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("ai-tool:orderCosts?tags=erp&description=Costs of a production
order&allowedRoles=finance,controlling")
+ .to("bean:costs");
+
+// ...or as the default of every ai-tool route, which an endpoint replaces
with its own value
+AiToolComponent ai = context.getComponent("ai-tool", AiToolComponent.class);
+ai.getConfiguration().setAllowedRoles("finance,controlling");
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: ai-tool:orderCosts
+ parameters:
+ tags: erp
+ description: "Costs of a production order"
+ allowedRoles: finance,controlling
+ steps:
+ - to:
+ uri: bean:costs
+----
+====
+
+The caller's roles are read only from the exchange property
`CamelAiToolSecurityPrincipalRoles` (a
+`Collection<String>`). A role named in a message header or in a tool argument
never counts: on a tool route the
+headers carry the tool arguments, which the model controls. A call without
that property is refused.
+
+* Over the xref:others:mcp-server.adoc[MCP server] the server sets the
property from the roles of the authenticated
+ caller. That page says which claim of the token the roles are read from. A
caller without roles, such as a
+ basic-auth caller, is refused. Over stdio, or on an MCP server without
authentication, no caller has roles, so a
+ tool with `allowedRoles` refuses every call. The same holds on a runtime
whose MCP engine
+ does not set the property.
+* With `camel-langchain4j-agent`, `camel-openai` and `camel-spring-ai-chat`
the calling route sets the same property
+ before the agent runs, from the identity it has authenticated. The tool
exchange is a copy of the calling exchange
+ (see <<The calling exchange>> above), so the property reaches the tool route:
++
+[source,java]
+----
+from("platform-http:/assistant")
+ // the roles of the caller this route has authenticated: here a bean reads
them from the validated token
+ .setProperty("CamelAiToolSecurityPrincipalRoles", method("callerIdentity",
"roles"))
+ .to("langchain4j-agent:assistant?agentConfiguration=#myConfig&tags=erp");
+----
+
+When a call is refused, the model gets the same short refusal as for a denial
by an `authorizationPolicy`, and the
+denial is logged and published as described in <<Observing denials>> below.
The log entry names the tool, the roles
+it asks for and, when the `CamelAiToolSecurityPrincipalName` property is set,
the caller. The model is told none of
+this.
+
+`allowedRoles` and `authorizationPolicy` can be set on the same tool, and then
both must pass. The roles are checked
+first, and a call that fails them does not reach the policy. This combines a
role with a rule that needs more than a
+role, for example a xref:cedar-component.adoc[Cedar] or
xref:opa-component.adoc[OPA] policy over attributes.
+
+Set on the *component*, `allowedRoles` and `allRolesRequired` are the default
of every tool route, and an endpoint's
+own value replaces the component's. An endpoint can therefore replace the
component's roles, but it cannot remove the
+check: a value that names no role, such as an empty one, refuses every call.
The route still starts, and a `WARN` at
+its start names the tool. Only an option that is not set takes the component's
value; that includes an optional
+placeholder (`{{?name}}`) whose property is absent.
=== Observing denials
@@ -520,7 +598,8 @@ exchange-lifecycle event or route span. Every denial is
instead:
* logged at `WARN`, and
* published as an
`org.apache.camel.component.ai.tool.AiToolAuthorizationDeniedEvent` — an
`org.apache.camel.ai.AiEvent.ToolCallDeniedEvent` (a `CamelEvent` of type
`Ai`) carrying the denied tool name, the
- tool exchange (for correlation), and the `CamelAuthorizationException` the
policy raised.
+ tool exchange (for correlation), and the `CamelAuthorizationException` that
refused the call. For a call that the
+ `allowedRoles` check refused, its `getPolicyId()` returns `allowedRoles`.
Register an `EventNotifier` to count, log or alert on denials — for example to
drive a micrometer counter — without
changing what the model sees (still the short refusal). Match on the shared
`AiEvent.ToolCallDeniedEvent` interface so
@@ -545,7 +624,7 @@ never affects the refusal returned to the model.
`searchable` controls whether a route tool is sent to the model immediately or
only after a producer with tool search enabled finds it. The default is
`false`, so the tool stays directly visible. `searchable=true` omits the tool
from the initial model request and makes it eligible for search together with
remote MCP tools.
-Searchability is a visibility policy. It does not authorize the call. An
`authorizationPolicy` on the tool is still applied when the model invokes it.
With tool search disabled on the producer, `searchable` has no effect and the
tool is exposed as before.
+Searchability is a visibility policy. It does not authorize the call. The
`allowedRoles` and the `authorizationPolicy` of the tool are still applied when
the model invokes it. With tool search disabled on the producer, `searchable`
has no effect and the tool is exposed as before.
[source,yaml]
----
diff --git
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolAllowedRolesProcessor.java
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolAllowedRolesProcessor.java
new file mode 100644
index 000000000000..3f153a56cb64
--- /dev/null
+++
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolAllowedRolesProcessor.java
@@ -0,0 +1,116 @@
+/*
+ * 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.ai.tool;
+
+import java.util.Collection;
+import java.util.List;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.AsyncProcessor;
+import org.apache.camel.CamelAuthorizationException;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.support.AsyncProcessorConverterHelper;
+import org.apache.camel.support.AsyncProcessorSupport;
+
+/**
+ * Enforces the {@code allowedRoles} option of an {@code ai-tool} endpoint
before the wrapped processor runs: the call
+ * passes when the caller has one of the named roles, or all of them with
{@code allRolesRequired}.
+ * <p>
+ * The caller's roles are read only from the {@link
AiToolConstants#SECURITY_PRINCIPAL_ROLES_PROPERTY} exchange
+ * property. On a tool route the message headers carry the tool arguments,
which the model controls, so a role named in
+ * a header or in an argument never counts. A call without the property, or
with a property that is not a collection, is
+ * refused.
+ * <p>
+ * An {@code allowedRoles} that is set but names no role refuses every call: a
check with nothing to check fails closed,
+ * it does not disappear. This holds with {@code allRolesRequired} too, where
"all of no roles" would otherwise pass.
+ * <p>
+ * A refusal is a {@link CamelAuthorizationException} set on the exchange, as
the shipped security policies do under the
+ * asynchronous routing engine. {@link AiToolExecutor} turns it into the
generic refusal the model gets, logs its
+ * message and fires {@link AiToolAuthorizationDeniedEvent}. The message names
the tool, the roles it asks for and the
+ * caller, and goes to the log only.
+ * <p>
+ * It has no lifecycle on the processor it guards: it neither starts nor stops
it, as that processor belongs to the
+ * route (or is the one {@code authorizationPolicy} wrapped, which {@link
AiToolConsumer} starts and stops). A call that
+ * passes continues on the asynchronous routing engine.
+ */
+final class AiToolAllowedRolesProcessor extends AsyncProcessorSupport {
+
+ /**
+ * What {@link CamelAuthorizationException#getPolicyId()} returns for a
call this check refused: the name of the
+ * option.
+ */
+ static final String POLICY_ID = "allowedRoles";
+
+ private final AsyncProcessor processor;
+ private final String toolName;
+ private final List<String> allowedRoles;
+ private final boolean allRolesRequired;
+
+ AiToolAllowedRolesProcessor(Processor processor, String toolName,
List<String> allowedRoles, boolean allRolesRequired) {
+ this.processor = AsyncProcessorConverterHelper.convert(processor);
+ this.toolName = toolName;
+ this.allowedRoles = allowedRoles;
+ this.allRolesRequired = allRolesRequired;
+ }
+
+ @Override
+ public boolean process(Exchange exchange, AsyncCallback callback) {
+ Object callerRoles =
exchange.getProperty(AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY);
+ if (allowedRoles.isEmpty() || !(callerRoles instanceof Collection<?>
roles) || !isAllowed(roles)) {
+
exchange.getMessage().setHeader(Exchange.AUTHENTICATION_FAILURE_POLICY_ID,
POLICY_ID);
+ exchange.setException(new
CamelAuthorizationException(refusal(exchange, callerRoles), exchange));
+ callback.done(true);
+ return true;
+ }
+ return processor.process(exchange, callback);
+ }
+
+ private boolean isAllowed(Collection<?> callerRoles) {
+ return allRolesRequired
+ ? allowedRoles.stream().allMatch(role -> hasRole(callerRoles,
role))
+ : allowedRoles.stream().anyMatch(role -> hasRole(callerRoles,
role));
+ }
+
+ /**
+ * Compares with {@link String#equals(Object)} rather than {@link
Collection#contains(Object)}, so the comparison is
+ * exact whatever collection carries the caller's roles.
+ */
+ private static boolean hasRole(Collection<?> callerRoles, String role) {
+ return callerRoles.stream().anyMatch(role::equals);
+ }
+
+ private String refusal(Exchange exchange, Object callerRoles) {
+ if (allowedRoles.isEmpty()) {
+ return "Tool '" + toolName + "' sets an allowedRoles that names no
role, so every call is refused";
+ }
+ String name =
exchange.getProperty(AiToolConstants.SECURITY_PRINCIPAL_NAME_PROPERTY,
String.class);
+ String caller = name != null ? "caller '" + name + "'" : "the caller";
+ String needs = "Tool '" + toolName + "' needs " + (allRolesRequired ?
"all" : "one") + " of the roles "
+ + allowedRoles;
+ if (callerRoles == null) {
+ // the MCP bridge leaves the property out for a caller who has no
roles
+ return needs + "; " + caller + " has no roles";
+ }
+ if (!(callerRoles instanceof Collection)) {
+ // a property of another type: what to fix is who sets it, not the
caller's roles
+ return needs + "; " + caller + " has no collection of roles in the
exchange property "
+ + AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY;
+ }
+ return needs + "; " + caller + (allRolesRequired ? " does not have all
of them" : " has none of them");
+ }
+}
diff --git
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolAuthorizationDeniedEvent.java
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolAuthorizationDeniedEvent.java
index 3fbfd4c82743..d470f0cba89d 100644
---
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolAuthorizationDeniedEvent.java
+++
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolAuthorizationDeniedEvent.java
@@ -24,10 +24,10 @@ import org.apache.camel.Exchange;
import org.apache.camel.ai.AiEvent;
/**
- * Fired when an {@code ai-tool} route's {@code authorizationPolicy} denies a
tool call.
+ * Fired when an {@code ai-tool} route's {@code allowedRoles} check or {@code
authorizationPolicy} denies a tool call.
* <p>
- * The policy guards the route's <em>outer</em> processor, so a denial is
caught in front of the route: it never enters
- * the route's unit of work and therefore produces no exchange-lifecycle event
or route span. This event is the
+ * The guard is in front of the route's <em>outer</em> processor, so a denial
is caught in front of the route: it never
+ * enters the route's unit of work and therefore produces no
exchange-lifecycle event or route span. This event is the
* observable signal operators can subscribe to (with an {@code
EventNotifier}, JMX, or a micrometer counter) to see and
* alert on authorization denials, without changing what the model sees — the
call is still relayed back to the model as
* a short refusal.
diff --git
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConfiguration.java
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConfiguration.java
index 30f7e87f5cd0..64526f5bdcb9 100644
---
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConfiguration.java
+++
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConfiguration.java
@@ -133,6 +133,21 @@ public class AiToolConfiguration implements Cloneable {
+ "model as a short refusal rather than a stack
trace.")
private AuthorizationPolicy authorizationPolicy;
+ @Metadata(label = "consumer,security")
+ @UriParam(description = "Comma-separated list of the roles a caller needs
to call the tool, for example "
+ + "finance,controlling. Any one of them is enough
unless allRolesRequired is set. The roles "
+ + "are checked before the route runs, against the
caller's roles in the exchange property "
+ + "CamelAiToolSecurityPrincipalRoles: a call
without that property is refused. A value "
+ + "that is set but names no role refuses every
call. Set it on the component as the "
+ + "default of every tool route, or per endpoint to
replace it.")
+ private String allowedRoles;
+
+ @Metadata(label = "consumer,security")
+ @UriParam(defaultValue = "false", description = "Whether the caller needs
all the roles in allowedRoles, rather "
+ + "than any one of them.
Has no effect when allowedRoles is not "
+ + "set.")
+ private boolean allRolesRequired;
+
public AiToolConfiguration() {
}
@@ -256,6 +271,22 @@ public class AiToolConfiguration implements Cloneable {
this.authorizationPolicy = authorizationPolicy;
}
+ public String getAllowedRoles() {
+ return allowedRoles;
+ }
+
+ public void setAllowedRoles(String allowedRoles) {
+ this.allowedRoles = allowedRoles;
+ }
+
+ public boolean isAllRolesRequired() {
+ return allRolesRequired;
+ }
+
+ public void setAllRolesRequired(boolean allRolesRequired) {
+ this.allRolesRequired = allRolesRequired;
+ }
+
public AiToolConfiguration copy() {
try {
AiToolConfiguration copy = (AiToolConfiguration) super.clone();
diff --git
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConstants.java
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConstants.java
index 3137494782b0..4d1d191ec638 100644
---
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConstants.java
+++
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConstants.java
@@ -19,10 +19,30 @@ package org.apache.camel.component.ai.tool;
import org.apache.camel.spi.Metadata;
/**
- * Headers populated when an AI framework invokes a tool route.
+ * Headers populated when an AI framework invokes a tool route, and the
exchange properties that carry the caller's
+ * identity to it.
*/
public final class AiToolConstants {
+ /**
+ * Exchange property carrying the caller's role names (a {@code
Collection<String>}), which the {@code allowedRoles}
+ * option checks. Over the MCP server the bridge sets it from the
authenticated caller; on the other paths the
+ * calling route sets it before the agent runs. It is an exchange property
rather than a message header because on a
+ * tool route the headers carry the tool arguments, which the model
controls.
+ *
+ * @since 4.24
+ */
+ public static final String SECURITY_PRINCIPAL_ROLES_PROPERTY =
"CamelAiToolSecurityPrincipalRoles";
+
+ /**
+ * Exchange property carrying the caller's name (a {@code String}), set
where
+ * {@link #SECURITY_PRINCIPAL_ROLES_PROPERTY} is. The log entry of a call
that {@code allowedRoles} refused names
+ * the caller with it.
+ *
+ * @since 4.24
+ */
+ public static final String SECURITY_PRINCIPAL_NAME_PROPERTY =
"CamelAiToolSecurityPrincipalName";
+
@Metadata(label = "consumer", description = "The tool invocation
identifier supplied by the calling framework. "
+ "Absent when the framework
does not supply one.",
javaType = "String")
diff --git
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConsumer.java
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConsumer.java
index e79562314182..0877ead30001 100644
---
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConsumer.java
+++
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConsumer.java
@@ -16,6 +16,7 @@
*/
package org.apache.camel.component.ai.tool;
+import java.util.List;
import java.util.Map;
import org.apache.camel.CamelAuthorizationException;
@@ -48,6 +49,8 @@ public class AiToolConsumer extends DefaultConsumer
implements Suspendable {
private String[] registeredTags;
private boolean registeredInDefaultPool;
private volatile Processor toolProcessor;
+ // the processor authorizationPolicy.wrap returned, which this consumer
starts and stops; null without a policy
+ private Processor policyProcessor;
public AiToolConsumer(AiToolEndpoint endpoint, Processor processor) {
super(endpoint, processor);
@@ -65,49 +68,74 @@ public class AiToolConsumer extends DefaultConsumer
implements Suspendable {
}
/**
- * Wraps the tool route's processor with the configured {@link
AuthorizationPolicy}, if any, so the call is
- * authorized before the route runs. The policy is applied via {@code
beforeWrap} then {@code wrap} (as the
- * {@code .policy()} DSL does through {@code PolicyReifier}); the wrapped
processor is started and stopped with this
- * consumer. Because {@code getProcessor()} is the route's <em>outer</em>
processor, the guard runs in front of the
- * route (before its unit of work, tracing and error handling): a denied
call is logged and returned to the model as
- * {@link AiToolResult.AuthorizationDenied}, but it does not produce a
route span or metric. There is no
- * {@code ProcessorDefinition} here (the component owns the guard, not the
DSL), so {@code beforeWrap} gets a
+ * Puts the authorization guard in front of the tool route's processor, so
the call is authorized before the route
+ * runs. The guard is the {@code allowedRoles} check and the configured
{@link AuthorizationPolicy}, whichever are
+ * set. The roles check is the outer one: with both set the roles are
checked first, and a call that fails them does
+ * not reach the policy. An {@code allowedRoles} that is set but names no
role is still a guard, which refuses every
+ * call. The route starts, so that one misconfigured tool does not stop
the other routes, and a {@code WARN} says
+ * that the tool refuses its calls.
+ * <p>
+ * The policy is applied via {@code beforeWrap} then {@code wrap} (as the
{@code .policy()} DSL does through
+ * {@code PolicyReifier}); the wrapped processor is started and stopped
with this consumer. The roles check has no
+ * lifecycle on the processor it guards, so with {@code allowedRoles}
alone this consumer starts and stops nothing
+ * more than without it. Because {@code getProcessor()} is the route's
<em>outer</em> processor, the guard runs in
+ * front of the route (before its unit of work, tracing and error
handling): a denied call is logged and returned to
+ * the model as {@link AiToolResult.AuthorizationDenied}, but it does not
produce a route span or metric. There is
+ * no {@code ProcessorDefinition} here (the component owns the guard, not
the DSL), so {@code beforeWrap} gets a
* {@code null} definition, which Camel's {@link AuthorizationPolicy}
implementations ignore (they use only the
* route). Called from {@link #prepare()} before the tool is registered,
so the tool is never discoverable
- * unguarded; idempotent (a policy already applied is not wrapped twice).
+ * unguarded; idempotent (a guard already applied is not wrapped twice).
*/
- private void applyAuthorizationPolicy() throws Exception {
+ private void applyAuthorizationGuard() throws Exception {
if (toolProcessor != null) {
return;
}
AuthorizationPolicy policy = configuration.getAuthorizationPolicy();
+ String allowedRoles = configuration.getAllowedRoles();
+ if (policy == null && allowedRoles == null) {
+ return;
+ }
Processor target = getProcessor();
- if (policy == null || target == null) {
+ if (target == null) {
return;
}
- policy.beforeWrap(getRoute(), null);
- Processor guarded = policy.wrap(getRoute(), target);
- ServiceHelper.startService(guarded);
+ Processor guarded = target;
+ if (policy != null) {
+ policy.beforeWrap(getRoute(), null);
+ guarded = policy.wrap(getRoute(), guarded);
+ ServiceHelper.startService(guarded);
+ policyProcessor = guarded;
+ LOG.debug("Tool '{}' is guarded by authorization policy {}",
toolName, policy.getClass().getName());
+ }
+ if (allowedRoles != null) {
+ List<String> roles =
List.of(AiToolParameterHelper.splitTags(allowedRoles));
+ if (roles.isEmpty()) {
+ LOG.warn("Tool '{}' sets an allowedRoles that names no role,
so every call to it is refused", toolName);
+ } else {
+ LOG.debug("Tool '{}' is guarded by allowedRoles {}
(allRolesRequired={})", toolName, roles,
+ configuration.isAllRolesRequired());
+ }
+ guarded = new AiToolAllowedRolesProcessor(guarded, toolName,
roles, configuration.isAllRolesRequired());
+ }
toolProcessor = guarded;
- LOG.debug("Tool '{}' is guarded by authorization policy {}", toolName,
policy.getClass().getName());
}
/**
- * The processor {@link AiToolExecutor} invokes for this tool: the
authorization-guarded processor when an
- * {@link AuthorizationPolicy} is configured, otherwise the plain route
processor. Fails <em>closed</em>: if a
- * policy is configured but the guard is not yet in place, it returns a
processor that denies the call rather than
- * exposing the unguarded route processor.
+ * The processor {@link AiToolExecutor} invokes for this tool: the
authorization guard when {@code allowedRoles} or
+ * an {@link AuthorizationPolicy} is set, otherwise the plain route
processor. Fails <em>closed</em>: if either is
+ * set but the guard is not in place, it returns a processor that denies
the call rather than exposing the unguarded
+ * route processor.
*/
Processor getToolProcessor() {
Processor guarded = toolProcessor;
if (guarded != null) {
return guarded;
}
- if (configuration.getAuthorizationPolicy() != null) {
- // fail closed: never fall back to the unguarded route processor
while a policy is configured
+ if (configuration.getAuthorizationPolicy() != null ||
configuration.getAllowedRoles() != null) {
+ // fail closed: never fall back to the unguarded route processor
while a guard is configured
return exchange -> {
throw new CamelAuthorizationException(
- "Authorization policy for tool '" + toolName + "' is
not ready", exchange);
+ "Authorization for tool '" + toolName + "' is not
ready", exchange);
};
}
return getProcessor();
@@ -132,10 +160,11 @@ public class AiToolConsumer extends DefaultConsumer
implements Suspendable {
if (registeredSpec != null && !isStarted()) {
deregister();
registeredSpec = null;
- // prepare() may have wrapped and started the guard during early
registration; stop it so an undone early
+ // prepare() may have wrapped and started the policy during early
registration; stop it so an undone early
// registration does not leave a started processor behind (matches
doStop)
if (toolProcessor != null) {
- ServiceHelper.stopService(toolProcessor);
+ ServiceHelper.stopService(policyProcessor);
+ policyProcessor = null;
toolProcessor = null;
}
}
@@ -193,7 +222,7 @@ public class AiToolConsumer extends DefaultConsumer
implements Suspendable {
// Apply the authorization guard BEFORE the tool is registered
(register() follows in both doStart() and
// registerEarly()), so the tool is never discoverable in an unguarded
state during route warm-up.
- applyAuthorizationPolicy();
+ applyAuthorizationGuard();
}
@Override
@@ -221,7 +250,8 @@ public class AiToolConsumer extends DefaultConsumer
implements Suspendable {
registeredInDefaultPool = false;
}
if (toolProcessor != null) {
- ServiceHelper.stopService(toolProcessor);
+ ServiceHelper.stopService(policyProcessor);
+ policyProcessor = null;
toolProcessor = null;
}
super.doStop();
diff --git
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolExecutor.java
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolExecutor.java
index b1570bfe073e..6d9ed88cc455 100644
---
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolExecutor.java
+++
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolExecutor.java
@@ -182,8 +182,8 @@ public final class AiToolExecutor {
return new AiToolResult.ExecutionError(cause.getMessage(), cause);
}
- // Use the authorization-guarded processor when the consumer applied
an AuthorizationPolicy, so the guard runs
- // before the route body; falls back to the plain route processor
otherwise.
+ // Use the authorization-guarded processor when the consumer applied
allowedRoles or an AuthorizationPolicy, so
+ // the guard runs before the route body; falls back to the plain route
processor otherwise.
Processor routeProcessor = consumer instanceof AiToolConsumer atc ?
atc.getToolProcessor() : consumer.getProcessor();
if (routeProcessor == null) {
IllegalStateException cause = new IllegalStateException(
@@ -295,7 +295,7 @@ public final class AiToolExecutor {
if (denial == null) {
return null;
}
- LOG.warn("Tool '{}' call denied by authorization policy: {}",
toolName, denial.getMessage());
+ LOG.warn("Tool '{}' call denied by the authorization check: {}",
toolName, denial.getMessage());
fireAuthorizationDeniedEvent(exchange, toolName, denial);
return new AiToolResult.AuthorizationDenied(
String.format("Access denied: not authorized to call tool
'%s'", toolName), denial);
diff --git
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolResult.java
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolResult.java
index 5cea14576540..51e21274e3db 100644
---
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolResult.java
+++
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolResult.java
@@ -63,11 +63,11 @@ public sealed interface AiToolResult {
}
/**
- * The route's {@link org.apache.camel.spi.AuthorizationPolicy} denied the
call: the caller is not authorized to
- * invoke this tool. Framework adapters should return {@link #message()}
to the model as a short refusal it can
- * relay, rather than rethrowing or failing the exchange — a denial is
expected control flow, not a tool error, so
- * it is not subject to the tool-execution error strategy. {@link
#message()} is a generic, caller-safe refusal and
- * must not be enriched with the cause before returning it to the model.
+ * The route's {@code allowedRoles} check or its {@link
org.apache.camel.spi.AuthorizationPolicy} denied the call:
+ * the caller is not authorized to invoke this tool. Framework adapters
should return {@link #message()} to the
+ * model as a short refusal it can relay, rather than rethrowing or
failing the exchange — a denial is expected
+ * control flow, not a tool error, so it is not subject to the
tool-execution error strategy. {@link #message()} is
+ * a generic, caller-safe refusal and must not be enriched with the cause
before returning it to the model.
*
* @param message a short, caller-safe refusal message (no internal policy
detail)
* @param cause the underlying {@link
org.apache.camel.CamelAuthorizationException}
diff --git
a/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolAllowedRolesStartupTest.java
b/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolAllowedRolesStartupTest.java
new file mode 100644
index 000000000000..cb40aaf67856
--- /dev/null
+++
b/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolAllowedRolesStartupTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.ai.tool;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.EventNotifierSupport;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The {@code allowedRoles} check must hold in the window between a tool's
early (warm-up) registration and the start of
+ * its consumer, as an {@code authorizationPolicy} does (see {@link
AiToolAuthorizationPolicyStartupTest}): a route with
+ * a lower startupOrder can call the tool before the tool route's own consumer
starts.
+ */
+class AiToolAllowedRolesStartupTest extends CamelTestSupport {
+
+ private final AtomicReference<AiToolResult> withoutTheRole = new
AtomicReference<>();
+ private final AtomicReference<AiToolResult> withTheRole = new
AtomicReference<>();
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ CamelContext ctx = super.createCamelContext();
+ ctx.getManagementStrategy().addEventNotifier(new
EventNotifierSupport() {
+ @Override
+ public void notify(CamelEvent event) {
+ // the caller route has started but the ai-tool route's
consumer has not: the roles must already apply
+ if (event instanceof CamelEvent.RouteStartedEvent rse &&
"caller".equals(rse.getRoute().getRouteId())) {
+
AiToolRegistry.getOrCreate(ctx).getToolsByTag("t").stream().findFirst().ifPresent(spec
-> {
+ withoutTheRole.set(AiToolExecutor.execute(spec,
Map.of(), new DefaultExchange(ctx)));
+ Exchange finance = new DefaultExchange(ctx);
+
finance.setProperty(AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY,
List.of("finance"));
+ withTheRole.set(AiToolExecutor.execute(spec, Map.of(),
finance));
+ });
+ }
+ }
+ });
+ return ctx;
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+
from("direct:caller").routeId("caller").startupOrder(1).log("caller started");
+
from("ai-tool:transfer?tags=t&description=Transfer&allowedRoles=finance")
+
.routeId("tool").startupOrder(2).setBody(constant("TRANSFERRED"));
+ }
+ };
+ }
+
+ @Test
+ void theRolesAreCheckedDuringStartup() {
+ assertThat(withoutTheRole.get())
+ .as("a tool call during the warm-up/start window must be
guarded, not fall back to the unguarded route")
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ // the check itself is in place by then, not only the refusal of a
guard that is not ready
+ assertThat(withTheRole.get()).isInstanceOf(AiToolResult.Success.class);
+ }
+}
diff --git
a/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolAllowedRolesTest.java
b/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolAllowedRolesTest.java
new file mode 100644
index 000000000000..649eac3301a5
--- /dev/null
+++
b/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolAllowedRolesTest.java
@@ -0,0 +1,444 @@
+/*
+ * 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.ai.tool;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelAuthorizationException;
+import org.apache.camel.Exchange;
+import org.apache.camel.NamedNode;
+import org.apache.camel.Processor;
+import org.apache.camel.Route;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.spi.AuthorizationPolicy;
+import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.spi.Registry;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.EventNotifierSupport;
+import org.apache.camel.support.service.ServiceHelper;
+import org.apache.camel.support.service.ServiceSupport;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * The {@code allowedRoles} option of an {@code ai-tool} route: the caller
needs one of the named roles, or all of them
+ * with {@code allRolesRequired}. The caller's roles are read only from the
{@code CamelAiToolSecurityPrincipalRoles}
+ * exchange property, and a refusal takes the path of an {@code
authorizationPolicy} denial: a short refusal to the
+ * model, and an {@link AiToolAuthorizationDeniedEvent}.
+ */
+class AiToolAllowedRolesTest extends CamelTestSupport {
+
+ private final List<AiToolAuthorizationDeniedEvent> events = new
CopyOnWriteArrayList<>();
+ private final AtomicInteger policyCalls = new AtomicInteger();
+
+ /** Counts the calls that reach it, and allows the call only when the
exchange carries {@code subject == alice}. */
+ final class CountingSubjectPolicy implements AuthorizationPolicy {
+ @Override
+ public void beforeWrap(Route route, NamedNode definition) {
+ // nothing to prepare
+ }
+
+ @Override
+ public Processor wrap(Route route, Processor processor) {
+ return exchange -> {
+ policyCalls.incrementAndGet();
+ if (!"alice".equals(exchange.getProperty("subject",
String.class))) {
+ throw new CamelAuthorizationException("caller is not
authorized", exchange);
+ }
+ processor.process(exchange);
+ };
+ }
+ }
+
+ @Override
+ protected void bindToRegistry(Registry registry) {
+ registry.bind("subjectPolicy", new CountingSubjectPolicy());
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ from("ai-tool:orderCosts?tags=test&description=Costs of a
production order&allowedRoles=finance")
+ .setBody(constant("ok"));
+
+ from("ai-tool:anyOf?tags=test&description=One of two
roles&allowedRoles=finance,controlling")
+ .setBody(constant("ok"));
+
+ from("ai-tool:allOf?tags=test&description=Both
roles&allowedRoles=finance,controlling"
+ + "&allRolesRequired=true")
+ .setBody(constant("ok"));
+
+ from("ai-tool:withArgument?tags=test&description=Takes an
argument named roles&allowedRoles=finance"
+ + "¶meter.roles=string")
+ .setBody(constant("ok"));
+
+ from("ai-tool:withPolicy?tags=test&description=Roles and a
policy&allowedRoles=finance"
+ + "&authorizationPolicy=#subjectPolicy")
+ .setBody(constant("ok"));
+
+
from("ai-tool:allRolesRequiredAlone?tags=test&description=Names no
roles&allRolesRequired=true")
+ .setBody(constant("ok"));
+ }
+ };
+ }
+
+ @BeforeEach
+ void registerEventNotifier() {
+ context.getManagementStrategy().addEventNotifier(new
EventNotifierSupport() {
+ @Override
+ public void notify(CamelEvent event) {
+ if (event instanceof AiToolAuthorizationDeniedEvent denied) {
+ events.add(denied);
+ }
+ }
+ });
+ }
+
+ @Test
+ void aCallerWithTheRoleMayCall() {
+ AiToolResult result = AiToolExecutor.execute(findSpec("orderCosts"),
Map.of(), callerWithRoles("sales", "finance"));
+
+ assertThat(result).isInstanceOf(AiToolResult.Success.class);
+ assertThat(((AiToolResult.Success) result).value()).isEqualTo("ok");
+ assertThat(events).isEmpty();
+ }
+
+ @Test
+ void aCallerWithoutTheRoleIsRefused() {
+ AiToolResult result = AiToolExecutor.execute(findSpec("orderCosts"),
Map.of(), callerWithRoles("sales"));
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @Test
+ void theRoleNameIsComparedExactly() {
+ AiToolResult result = AiToolExecutor.execute(findSpec("orderCosts"),
Map.of(),
+ callerWithRoles("Finance", "finance-admin", " finance"));
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @Test
+ void anyOneOfTheRolesIsEnough() {
+ AiToolSpec spec = findSpec("anyOf");
+
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("controlling")))
+ .isInstanceOf(AiToolResult.Success.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance")))
+ .isInstanceOf(AiToolResult.Success.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("sales")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @Test
+ void allRolesRequiredNeedsEveryRole() {
+ AiToolSpec spec = findSpec("allOf");
+
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("controlling", "sales", "finance")))
+ .isInstanceOf(AiToolResult.Success.class);
+ }
+
+ @Test
+ void theEntriesAreTrimmedAndBlankEntriesAreIgnored() throws Exception {
+ context.addRoutes(new RouteBuilder() {
+ public void configure() {
+ AiToolEndpoint endpoint = getContext().getEndpoint(
+ "ai-tool:spaced?tags=test&description=Roles written
with spaces&allRolesRequired=true",
+ AiToolEndpoint.class);
+ endpoint.getConfiguration().setAllowedRoles(" finance ,
,controlling,, ");
+ from(endpoint).setBody(constant("ok"));
+ }
+ });
+ AiToolSpec spec = findSpec("spaced");
+
+ // every role is needed: a blank entry that counted as a role would
refuse this caller
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance", "controlling")))
+ .isInstanceOf(AiToolResult.Success.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @Test
+ void aCallWithoutTheRolesPropertyIsRefused() {
+ AiToolResult result = AiToolExecutor.execute(findSpec("orderCosts"),
Map.of(), new DefaultExchange(context));
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @Test
+ void aRolesPropertyThatIsNotACollectionIsRefused() {
+ Exchange exchange = new DefaultExchange(context);
+
exchange.setProperty(AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY,
"finance");
+
+ AiToolResult result = AiToolExecutor.execute(findSpec("orderCosts"),
Map.of(), exchange);
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ // the log points at the property, which someone set to another type
+ assertThat(((AiToolResult.AuthorizationDenied)
result).cause().getMessage())
+ .contains("orderCosts", "finance",
AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY);
+ }
+
+ @Test
+ void aRoleInAHeaderOrAnArgumentDoesNotCount() {
+ // on a tool route the headers carry the tool arguments, which the
model controls
+ Exchange exchange = callerWithRoles("sales");
+
exchange.getMessage().setHeader(AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY,
List.of("finance"));
+
+ AiToolResult result = AiToolExecutor.execute(findSpec("withArgument"),
Map.of("roles", "finance"), exchange);
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @Test
+ void aRoleInAHeaderOrAnArgumentDoesNotStandInForAMissingProperty() {
+ // no roles property at all: the header and the argument must not be
read in its place
+ Exchange exchange = new DefaultExchange(context);
+
exchange.getMessage().setHeader(AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY,
List.of("finance"));
+
+ AiToolResult result = AiToolExecutor.execute(findSpec("withArgument"),
Map.of("roles", "finance"), exchange);
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @Test
+ void theRolesTheCallingRouteSetReachTheTool() {
+ // langchain4j-agent, openai and spring-ai-chat run the tool on a copy
of the calling exchange, so the roles
+ // the calling route set before the agent ran are the ones the tool
checks
+ Exchange toolExchange =
AiToolExecutor.createToolExchange(callerWithRoles("finance"));
+
+ AiToolResult result = AiToolExecutor.execute(findSpec("orderCosts"),
Map.of(), toolExchange);
+
+ assertThat(result).isInstanceOf(AiToolResult.Success.class);
+ }
+
+ @Test
+ void theRefusalNamesTheToolTheRolesAndTheCallerInTheLogOnly() {
+ Exchange exchange = callerWithRoles("sales");
+ exchange.setProperty(AiToolConstants.SECURITY_PRINCIPAL_NAME_PROPERTY,
"alice");
+
+ AiToolResult result = AiToolExecutor.execute(findSpec("anyOf"),
Map.of(), exchange);
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ AiToolResult.AuthorizationDenied denied =
(AiToolResult.AuthorizationDenied) result;
+ // the model is told neither the roles nor the caller
+
assertThat(denied.message()).contains("anyOf").doesNotContain("finance",
"controlling", "alice");
+ // the exception, which AiToolExecutor logs at WARN, says what the
tool asks for and who called
+
assertThat(denied.cause()).isInstanceOf(CamelAuthorizationException.class);
+ assertThat(denied.cause().getMessage()).contains("anyOf", "finance",
"controlling", "alice");
+ assertThat(((CamelAuthorizationException)
denied.cause()).getPolicyId()).isEqualTo("allowedRoles");
+ }
+
+ @Test
+ void theRefusalSaysWhenTheCallerHasNoRoles() {
+ // the MCP bridge leaves the property out for a caller without roles:
an ordinary caller, not a wiring fault
+ Exchange exchange = new DefaultExchange(context);
+ exchange.setProperty(AiToolConstants.SECURITY_PRINCIPAL_NAME_PROPERTY,
"alice");
+
+ AiToolResult result = AiToolExecutor.execute(findSpec("allOf"),
Map.of(), exchange);
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(((AiToolResult.AuthorizationDenied)
result).cause().getMessage())
+ .contains("allOf", "finance", "controlling", "alice", "no
roles")
+
.doesNotContain(AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY);
+ }
+
+ @Test
+ void aRefusalFiresTheDeniedEvent() {
+ Exchange exchange = callerWithRoles("sales");
+
+ AiToolResult result = AiToolExecutor.execute(findSpec("orderCosts"),
Map.of(), exchange);
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(events).hasSize(1);
+ AiToolAuthorizationDeniedEvent event = events.get(0);
+ assertThat(event.getToolName()).isEqualTo("orderCosts");
+ assertThat(event.getExchange()).isSameAs(exchange);
+
assertThat(event.getCause()).isInstanceOf(CamelAuthorizationException.class);
+ assertThat(event.getCause().getPolicyId()).isEqualTo("allowedRoles");
+ }
+
+ @Test
+ void withAPolicyBothMustPass() {
+ AiToolSpec spec = findSpec("withPolicy");
+
+ Exchange alice = callerWithRoles("finance");
+ alice.setProperty("subject", "alice");
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
alice)).isInstanceOf(AiToolResult.Success.class);
+ assertThat(policyCalls).hasValue(1);
+
+ // bob has the role, so the call reaches the policy, which refuses him
+ Exchange bob = callerWithRoles("finance");
+ bob.setProperty("subject", "bob");
+ AiToolResult result = AiToolExecutor.execute(spec, Map.of(), bob);
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(((AiToolResult.AuthorizationDenied)
result).cause().getMessage()).contains("caller is not authorized");
+ assertThat(policyCalls).hasValue(2);
+ }
+
+ @Test
+ void aCallThatFailsTheRolesDoesNotReachThePolicy() {
+ Exchange alice = callerWithRoles("sales");
+ alice.setProperty("subject", "alice");
+
+ AiToolResult result = AiToolExecutor.execute(findSpec("withPolicy"),
Map.of(), alice);
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(policyCalls).hasValue(0);
+ }
+
+ @Test
+ void allRolesRequiredAloneHasNoEffect() {
+ AiToolSpec spec = findSpec("allRolesRequiredAlone");
+
+ assertThat(AiToolExecutor.execute(spec, Map.of(), new
DefaultExchange(context)))
+ .isInstanceOf(AiToolResult.Success.class);
+ // no guard is put in front of the route
+ AiToolConsumer consumer = (AiToolConsumer) spec.getConsumer();
+
assertThat(consumer.getToolProcessor()).isSameAs(consumer.getProcessor());
+ }
+
+ @Test
+ void failsClosedWhileTheGuardIsNotInPlace() throws Exception {
+ // a consumer that is not started has no guard yet: it must refuse the
call, also for a caller who has the
+ // role, rather than hand out the unguarded route processor
+ AtomicBoolean routeRan = new AtomicBoolean();
+ AiToolEndpoint endpoint
+ =
context.getEndpoint("ai-tool:notStarted?tags=test&allowedRoles=finance",
AiToolEndpoint.class);
+ AiToolConsumer consumer = (AiToolConsumer)
endpoint.createConsumer(exchange -> routeRan.set(true));
+ Exchange exchange = callerWithRoles("finance");
+
+ assertThatThrownBy(() -> consumer.getToolProcessor().process(exchange))
+ .isInstanceOf(CamelAuthorizationException.class);
+ assertThat(routeRan).isFalse();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "", ",", " , " })
+ void anAllowedRolesThatNamesNoRoleRefusesEveryCall(String allowedRoles)
throws Exception {
+ // an empty value is what an empty property placeholder gives. The
route starts, so one such tool does not
+ // stop the others.
+ context.addRoutes(new RouteBuilder() {
+ public void configure() {
+ from("ai-tool:namesNoRole?tags=test&description=Names no
role&allowedRoles=" + allowedRoles)
+ .setBody(constant("ok"));
+ }
+ });
+
+ AiToolResult result = AiToolExecutor.execute(findSpec("namesNoRole"),
Map.of(), callerWithRoles("finance"));
+
+
assertThat(result).isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ AiToolResult.AuthorizationDenied denied =
(AiToolResult.AuthorizationDenied) result;
+ assertThat(denied.cause().getMessage()).contains("namesNoRole", "names
no role");
+ assertThat(((CamelAuthorizationException)
denied.cause()).getPolicyId()).isEqualTo("allowedRoles");
+ }
+
+ @Test
+ void
anAllowedRolesThatNamesNoRoleRefusesEveryCallWithAllRolesRequiredToo() throws
Exception {
+ // "all of no roles" would pass if the empty list were checked like
any other
+ context.addRoutes(new RouteBuilder() {
+ public void configure() {
+ from("ai-tool:namesNoRole?tags=test&description=Names no
role&allowedRoles=,&allRolesRequired=true")
+ .setBody(constant("ok"));
+ }
+ });
+
+ assertThat(AiToolExecutor.execute(findSpec("namesNoRole"), Map.of(),
callerWithRoles("finance")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(AiToolExecutor.execute(findSpec("namesNoRole"), Map.of(),
new DefaultExchange(context)))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @Test
+ void theRolesCheckDoesNotStopTheProcessorItGuards() {
+ // the processor it guards belongs to the route, which starts and
stops it
+ LifecycleProcessor routeProcessor = new LifecycleProcessor();
+ routeProcessor.start();
+ AiToolAllowedRolesProcessor check
+ = new AiToolAllowedRolesProcessor(routeProcessor,
"orderCosts", List.of("finance"), false);
+
+ ServiceHelper.startService(check);
+ ServiceHelper.stopService(check);
+
+ assertThat(routeProcessor.isStarted()).isTrue();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "", "&allowedRoles=finance" })
+ void theConsumerStartsAndStopsTheProcessorThePolicyWrapped(String
allowedRoles) throws Exception {
+ // with allowedRoles the roles check wraps the policy's processor, and
does not start or stop it itself
+ LifecycleProcessor policyProcessor = new LifecycleProcessor();
+ context.getRegistry().bind("lifecyclePolicy", new
AuthorizationPolicy() {
+ @Override
+ public void beforeWrap(Route route, NamedNode definition) {
+ // nothing to prepare
+ }
+
+ @Override
+ public Processor wrap(Route route, Processor processor) {
+ return policyProcessor;
+ }
+ });
+ context.addRoutes(new RouteBuilder() {
+ public void configure() {
+ from("ai-tool:lifecycle?tags=test&description=A policy with a
lifecycle"
+ + "&authorizationPolicy=#lifecyclePolicy" + allowedRoles)
+ .routeId("lifecycle")
+ .setBody(constant("ok"));
+ }
+ });
+ assertThat(policyProcessor.isStarted()).isTrue();
+
+ context.getRouteController().stopRoute("lifecycle");
+
+ assertThat(policyProcessor.isStarted()).isFalse();
+ assertThat(policyProcessor.isStopped()).isTrue();
+ }
+
+ /** A processor whose lifecycle the test reads. */
+ static final class LifecycleProcessor extends ServiceSupport implements
Processor {
+ @Override
+ public void process(Exchange exchange) {
+ // the tests only start and stop it
+ }
+ }
+
+ private Exchange callerWithRoles(String... roles) {
+ Exchange exchange = new DefaultExchange(context);
+
exchange.setProperty(AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY,
List.of(roles));
+ return exchange;
+ }
+
+ private AiToolSpec findSpec(String toolName) {
+ return
AiToolRegistry.getOrCreate(context).getToolsByTag("test").stream()
+ .filter(s -> toolName.equals(s.getName()))
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("Tool not found: " +
toolName));
+ }
+}
diff --git
a/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolComponentAllowedRolesTest.java
b/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolComponentAllowedRolesTest.java
new file mode 100644
index 000000000000..5a0ac7f6fe34
--- /dev/null
+++
b/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolComponentAllowedRolesTest.java
@@ -0,0 +1,204 @@
+/*
+ * 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.ai.tool;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.NamedNode;
+import org.apache.camel.Processor;
+import org.apache.camel.Route;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.AuthorizationPolicy;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * {@code allowedRoles} and {@code allRolesRequired} set on the ai-tool
component are the default for every tool route.
+ * An endpoint's own value replaces the component's; only an option that is
not set at all takes the component's value.
+ */
+class AiToolComponentAllowedRolesTest extends CamelTestSupport {
+
+ /** Allows every call (delegates straight to the route). */
+ static final class AllowAll implements AuthorizationPolicy {
+ @Override
+ public void beforeWrap(Route route, NamedNode definition) {
+ // nothing to prepare
+ }
+
+ @Override
+ public Processor wrap(Route route, Processor processor) {
+ return processor::process;
+ }
+ }
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ CamelContext ctx = super.createCamelContext();
+ ctx.getRegistry().bind("allowAll", new AllowAll());
+ ctx.getPropertiesComponent().addInitialProperty("roles.empty", "");
+ AiToolComponent component = ctx.getComponent("ai-tool",
AiToolComponent.class);
+ component.getConfiguration().setAllowedRoles("finance,controlling");
+ component.getConfiguration().setAllRolesRequired(true);
+ return ctx;
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ from("ai-tool:inherits?tags=t&description=Inherits both
options")
+ .setBody(constant("ok"));
+ from("ai-tool:ownRoles?tags=t&description=Names its own
roles&allowedRoles=sales,marketing")
+ .setBody(constant("ok"));
+ from("ai-tool:anyRole?tags=t&description=Asks for one of the
roles&allRolesRequired=false")
+ .setBody(constant("ok"));
+ from("ai-tool:blankRoles?tags=t&description=Names no
role&allowedRoles=")
+ .setBody(constant("ok"));
+ from("ai-tool:placeholderRoles?tags=t&description=Roles from
an empty property"
+ + "&allowedRoles={{roles.empty}}")
+ .setBody(constant("ok"));
+ from("ai-tool:optionalRoles?tags=t&description=Roles from an
optional property that is absent"
+ + "&allowedRoles={{?roles.absent}}")
+ .setBody(constant("ok"));
+ from("ai-tool:ownPolicy?tags=t&description=Sets only its own
policy&authorizationPolicy=#allowAll")
+ .setBody(constant("ok"));
+ }
+ };
+ }
+
+ @Test
+ void theComponentOptionsGuardRoutesWithoutAnEndpointOption() {
+ AiToolSpec spec = findSpec("inherits");
+
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance", "controlling")))
+ .isInstanceOf(AiToolResult.Success.class);
+ }
+
+ @Test
+ void theEndpointRolesReplaceTheComponentRoles() {
+ AiToolSpec spec = findSpec("ownRoles");
+
+ // the endpoint's roles are not added to the component's: finance and
controlling no longer count
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance", "controlling")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ // the component's allRolesRequired applies to the endpoint's own list
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("sales")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("sales", "marketing")))
+ .isInstanceOf(AiToolResult.Success.class);
+ }
+
+ @Test
+ void theEndpointAllRolesRequiredReplacesTheComponentValue() {
+ AiToolSpec spec = findSpec("anyRole");
+
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("controlling")))
+ .isInstanceOf(AiToolResult.Success.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("sales")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "blankRoles", "placeholderRoles" })
+ void anEndpointValueThatNamesNoRoleRefusesEveryCall(String toolName) {
+ // an empty value, also the one an empty property placeholder resolves
to, is the endpoint's own value: it
+ // neither opens the tool nor falls back to the roles of the component
+ AiToolSpec spec = findSpec(toolName);
+
+ assertThat(AiToolExecutor.execute(spec, Map.of(), new
DefaultExchange(context)))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance", "controlling")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ }
+
+ @Test
+ void anOptionalPlaceholderWhosePropertyIsAbsentTakesTheComponentRoles() {
+ // {{?name}} without the property removes the option: it is not set,
as when it is not written at all
+ AiToolSpec spec = findSpec("optionalRoles");
+
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance")))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance", "controlling")))
+ .isInstanceOf(AiToolResult.Success.class);
+ }
+
+ @Test
+ void aComponentValueThatNamesNoRoleClosesEveryToolThatNamesNone() throws
Exception {
+ try (DefaultCamelContext closed = new DefaultCamelContext()) {
+ closed.getComponent("ai-tool",
AiToolComponent.class).getConfiguration().setAllowedRoles("");
+ closed.addRoutes(new RouteBuilder() {
+ public void configure() {
+ from("ai-tool:namesNone?tags=t&description=Names no role
itself")
+ .setBody(constant("ok"));
+ from("ai-tool:namesItsOwn?tags=t&description=Names its own
role&allowedRoles=finance")
+ .setBody(constant("ok"));
+ }
+ });
+ closed.start();
+
+ assertThat(AiToolExecutor.execute(findSpec(closed, "namesNone"),
Map.of(), finance(closed)))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(AiToolExecutor.execute(findSpec(closed, "namesItsOwn"),
Map.of(), finance(closed)))
+ .isInstanceOf(AiToolResult.Success.class);
+ }
+ }
+
+ private static Exchange finance(CamelContext camelContext) {
+ Exchange exchange = new DefaultExchange(camelContext);
+
exchange.setProperty(AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY,
List.of("finance"));
+ return exchange;
+ }
+
+ @Test
+ void theComponentRolesApplyToAToolThatSetsOnlyItsOwnPolicy() {
+ AiToolSpec spec = findSpec("ownPolicy");
+
+ // the policy allows every call, so it is the component's roles that
refuse this one
+ assertThat(AiToolExecutor.execute(spec, Map.of(), new
DefaultExchange(context)))
+ .isInstanceOf(AiToolResult.AuthorizationDenied.class);
+ assertThat(AiToolExecutor.execute(spec, Map.of(),
callerWithRoles("finance", "controlling")))
+ .isInstanceOf(AiToolResult.Success.class);
+ }
+
+ private Exchange callerWithRoles(String... roles) {
+ Exchange exchange = new DefaultExchange(context);
+
exchange.setProperty(AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY,
List.of(roles));
+ return exchange;
+ }
+
+ private AiToolSpec findSpec(String toolName) {
+ return findSpec(context, toolName);
+ }
+
+ private static AiToolSpec findSpec(CamelContext camelContext, String
toolName) {
+ return
AiToolRegistry.getOrCreate(camelContext).getToolsByTag("t").stream()
+ .filter(s -> toolName.equals(s.getName()))
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("Tool not found: " +
toolName));
+ }
+}
diff --git
a/components/camel-ai/camel-mcp-server-api/src/main/java/org/apache/camel/component/mcp/server/McpServerBridge.java
b/components/camel-ai/camel-mcp-server-api/src/main/java/org/apache/camel/component/mcp/server/McpServerBridge.java
index 08c7f24e8ae9..793de6fe5362 100644
---
a/components/camel-ai/camel-mcp-server-api/src/main/java/org/apache/camel/component/mcp/server/McpServerBridge.java
+++
b/components/camel-ai/camel-mcp-server-api/src/main/java/org/apache/camel/component/mcp/server/McpServerBridge.java
@@ -871,7 +871,7 @@ public class McpServerBridge extends ServiceSupport
implements CamelContextAware
return new McpToolCallResult(error.message(), true);
} else if (result instanceof AiToolResult.AuthorizationDenied
denied) {
// The denial message is already generic and caller-safe, so
it is safe to return to the MCP client.
- LOG.warn("MCP tool '{}' call denied by authorization policy",
spec.getName());
+ LOG.warn("MCP tool '{}' call denied by the authorization
check", spec.getName());
return new McpToolCallResult(denied.message(), true);
} else {
AiToolResult.ExecutionError error =
(AiToolResult.ExecutionError) result;
diff --git
a/components/camel-ai/camel-mcp-server-api/src/main/java/org/apache/camel/component/mcp/server/McpToolCallContext.java
b/components/camel-ai/camel-mcp-server-api/src/main/java/org/apache/camel/component/mcp/server/McpToolCallContext.java
index 7e1cf9521728..ffb856689e33 100644
---
a/components/camel-ai/camel-mcp-server-api/src/main/java/org/apache/camel/component/mcp/server/McpToolCallContext.java
+++
b/components/camel-ai/camel-mcp-server-api/src/main/java/org/apache/camel/component/mcp/server/McpToolCallContext.java
@@ -22,6 +22,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import org.apache.camel.component.ai.tool.AiToolConstants;
import org.apache.camel.spi.OAuthTokenValidationResult;
/**
@@ -75,23 +76,23 @@ public record McpToolCallContext(
/**
* Exchange property under which the bridge stamps {@link
#principalName()} on the tool exchange: the
* runtime-neutral caller name, so a tool route (or its {@link
org.apache.camel.spi.AuthorizationPolicy}) can
- * authorize on a stable identity via {@code
exchangeProperty.CamelMcpSecurityPrincipalName}, regardless of the MCP
- * server runtime. Not set when there is no principal or no name could be
determined.
+ * authorize on a stable identity via {@code
exchangeProperty.CamelAiToolSecurityPrincipalName}, regardless of the
+ * MCP server runtime. Not set when there is no principal or no name could
be determined.
*
* @since 4.24
*/
- public static final String SECURITY_PRINCIPAL_NAME_PROPERTY =
"CamelMcpSecurityPrincipalName";
+ public static final String SECURITY_PRINCIPAL_NAME_PROPERTY =
AiToolConstants.SECURITY_PRINCIPAL_NAME_PROPERTY;
/**
* Exchange property under which the bridge stamps {@link
#principalRoles()} on the tool exchange: the
* runtime-neutral caller role names (a {@code Collection<String>}), so a
tool route (or its
* {@link org.apache.camel.spi.AuthorizationPolicy}) can authorize on
stable roles via
- * {@code exchangeProperty.CamelMcpSecurityPrincipalRoles}, regardless of
the MCP server runtime. Not set when there
- * is no principal or no roles could be determined.
+ * {@code exchangeProperty.CamelAiToolSecurityPrincipalRoles}, regardless
of the MCP server runtime. Not set when
+ * there is no principal or no roles could be determined.
*
* @since 4.24
*/
- public static final String SECURITY_PRINCIPAL_ROLES_PROPERTY =
"CamelMcpSecurityPrincipalRoles";
+ public static final String SECURITY_PRINCIPAL_ROLES_PROPERTY =
AiToolConstants.SECURITY_PRINCIPAL_ROLES_PROPERTY;
/** Exchange property containing the validated OAuth subject. */
public static final String OAUTH_SUBJECT_PROPERTY = "CamelMcpOAuthSubject";
diff --git a/components/camel-ai/camel-mcp-server/src/main/docs/mcp-server.adoc
b/components/camel-ai/camel-mcp-server/src/main/docs/mcp-server.adoc
index 405061078c75..67029722e767 100644
--- a/components/camel-ai/camel-mcp-server/src/main/docs/mcp-server.adoc
+++ b/components/camel-ai/camel-mcp-server/src/main/docs/mcp-server.adoc
@@ -495,9 +495,15 @@ For an authenticated tool call, the bridge exposes the
following exchange proper
* `CamelMcpOAuthSubject`, `CamelMcpOAuthScopes`, and `CamelMcpOAuthClaims`
contain the subject,
scopes, and claims from the validated token.
-* `CamelMcpSecurityPrincipalName` and `CamelMcpSecurityPrincipalRoles` expose
the runtime-neutral
- caller name and roles when available. Roles are extracted from common
`roles`,
- `realm_access.roles`, or `groups` claim shapes.
+* `CamelAiToolSecurityPrincipalName` and `CamelAiToolSecurityPrincipalRoles`
expose the runtime-neutral
+ caller name and roles when available. The roles are the first of the `roles`,
+ `realm_access.roles` and `groups` claims that is an array: the claims are
not merged, and
+ client roles (`resource_access`) are not read. With Keycloak, realm roles
work as issued, and a
+ client role or a group needs a mapper into the `roles` claim, which is then
read instead of the
+ realm roles; the group mapper writes the full path (`/finance-team`) unless
its "Full group path"
+ switch is off. The `allowedRoles` option of an
xref:ROOT:ai-tool-component.adoc[ai-tool] route
+ checks these roles before the route runs. Without an authenticated caller,
as over stdio or on a
+ server without authentication, they are not set and a tool with
`allowedRoles` refuses every call.
* `CamelOAuthTokenValidationResult` contains the full Camel OAuth validation
result for route code
that already consumes the standard HTTP OAuth exchange property.
diff --git
a/components/camel-ai/camel-mcp-server/src/main/java/org/apache/camel/component/mcp/server/vertx/VertxMcpPrincipal.java
b/components/camel-ai/camel-mcp-server/src/main/java/org/apache/camel/component/mcp/server/vertx/VertxMcpPrincipal.java
index 51f665b3af80..30a6896dda9e 100644
---
a/components/camel-ai/camel-mcp-server/src/main/java/org/apache/camel/component/mcp/server/vertx/VertxMcpPrincipal.java
+++
b/components/camel-ai/camel-mcp-server/src/main/java/org/apache/camel/component/mcp/server/vertx/VertxMcpPrincipal.java
@@ -25,8 +25,9 @@ import io.vertx.ext.auth.User;
/**
* Derives a runtime-neutral view — a caller name and role names — from a
Vert.x {@link User}, so the MCP bridge can
- * stamp a stable caller identity ({@code CamelMcpSecurityPrincipalName} /
{@code CamelMcpSecurityPrincipalRoles}) that
- * a tool route or its {@link org.apache.camel.spi.AuthorizationPolicy} can
authorize on without depending on Vert.x.
+ * stamp a stable caller identity ({@code CamelAiToolSecurityPrincipalName} /
{@code CamelAiToolSecurityPrincipalRoles})
+ * that a tool route or its {@link org.apache.camel.spi.AuthorizationPolicy}
can authorize on without depending on
+ * Vert.x.
*/
final class VertxMcpPrincipal {
diff --git
a/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainAllowedRolesTest.java
b/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainAllowedRolesTest.java
new file mode 100644
index 000000000000..9c80f7bad7fd
--- /dev/null
+++
b/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainAllowedRolesTest.java
@@ -0,0 +1,178 @@
+/*
+ * 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.mcp.server.main;
+
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyStore;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+
+import javax.crypto.KeyGenerator;
+
+import io.modelcontextprotocol.client.McpClient;
+import io.modelcontextprotocol.client.McpSyncClient;
+import
io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
+import io.modelcontextprotocol.spec.McpSchema;
+import io.vertx.core.Vertx;
+import io.vertx.core.json.JsonArray;
+import io.vertx.core.json.JsonObject;
+import io.vertx.ext.auth.JWTOptions;
+import io.vertx.ext.auth.jwt.JWTAuth;
+import io.vertx.ext.auth.jwt.JWTAuthOptions;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.main.Main;
+import org.apache.camel.test.AvailablePortFinder;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The {@code allowedRoles} option of an {@code ai-tool} route over a real MCP
call: the Camel Main HTTP server
+ * authenticates the caller with a signed JWT, the MCP bridge puts the roles
of the token on the tool exchange, and the
+ * tool answers the caller who has the role and refuses the one who has not.
+ */
+class McpServerMainAllowedRolesTest {
+
+ private static final String ISSUER = "https://issuer.camel.example";
+ private static final String KEYSTORE_PASSWORD = "changeme";
+
+ @TempDir
+ static Path keystoreDir;
+
+ private static AvailablePortFinder.Port portRef;
+ private static int port;
+ private static Main main;
+ private static Vertx vertx;
+ private static JWTAuth tokens;
+
+ @BeforeAll
+ static void startMain() throws Exception {
+ Path keystore = createKeystore();
+ portRef = AvailablePortFinder.find();
+ port = portRef.getPort();
+ main = new Main();
+ main.configure().addRoutesBuilder(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("ai-tool:order_costs?tags=roles&description=Costs of a
production order&allowedRoles=finance")
+ .setBody(constant("costs=42"));
+ }
+ });
+ main.addInitialProperty("camel.server.enabled", "true");
+ main.addInitialProperty("camel.server.port", String.valueOf(port));
+ main.addInitialProperty("camel.server.authentication-enabled", "true");
+ main.addInitialProperty("camel.server.jwt-keystore-type", "pkcs12");
+ main.addInitialProperty("camel.server.jwt-keystore-path",
keystore.toString());
+ main.addInitialProperty("camel.server.jwt-keystore-password",
KEYSTORE_PASSWORD);
+ main.addInitialProperty("camel.server.jwt-issuer", ISSUER);
+ main.addInitialProperty("camel.server.mcp-enabled", "true");
+ main.addInitialProperty("camel.server.mcp-tags", "roles");
+ main.start();
+
+ vertx = Vertx.vertx();
+ tokens = JWTAuth.create(vertx, new JWTAuthOptions(
+ new JsonObject().put("keyStore", new JsonObject()
+ .put("type", "pkcs12")
+ .put("path", keystore.toString())
+ .put("password", KEYSTORE_PASSWORD))));
+ }
+
+ @AfterAll
+ static void stopMain() {
+ if (main != null) {
+ main.stop();
+ }
+ if (vertx != null) {
+ vertx.close();
+ }
+ if (portRef != null) {
+ portRef.release();
+ }
+ }
+
+ @Test
+ void theToolAnswersACallerWhoHasTheRole() {
+ McpSyncClient client = newClient(token("alice", "sales", "finance"));
+ try {
+ client.initialize();
+
+ McpSchema.CallToolResult result = client.callTool(new
McpSchema.CallToolRequest("order_costs", Map.of()));
+
+ assertThat(result.isError()).isNotEqualTo(Boolean.TRUE);
+ assertThat(result.content().toString()).contains("costs=42");
+ } finally {
+ client.closeGracefully();
+ }
+ }
+
+ @Test
+ void theToolRefusesACallerWhoDoesNotHaveTheRole() {
+ McpSyncClient client = newClient(token("bob", "sales"));
+ try {
+ client.initialize();
+
+ McpSchema.CallToolResult result = client.callTool(new
McpSchema.CallToolRequest("order_costs", Map.of()));
+
+ assertThat(result.isError()).isEqualTo(Boolean.TRUE);
+ // the generic refusal: neither the result of the route nor the
roles the tool asks for
+ assertThat(result.content().toString())
+ .contains("Access denied: not authorized to call tool
'order_costs'")
+ .doesNotContain("costs=42")
+ .doesNotContain("finance");
+ } finally {
+ client.closeGracefully();
+ }
+ }
+
+ /**
+ * A keystore with the secret key the server verifies the HS256 signature
of a token with, and this test signs with.
+ * Vert.x reads the key whose alias is the name of the algorithm.
+ */
+ private static Path createKeystore() throws Exception {
+ KeyStore keyStore = KeyStore.getInstance("pkcs12");
+ keyStore.load(null, null);
+ keyStore.setEntry("HS256", new
KeyStore.SecretKeyEntry(KeyGenerator.getInstance("HmacSHA256").generateKey()),
+ new
KeyStore.PasswordProtection(KEYSTORE_PASSWORD.toCharArray()));
+ Path keystore = keystoreDir.resolve("jwt.p12");
+ try (OutputStream out = Files.newOutputStream(keystore)) {
+ keyStore.store(out, KEYSTORE_PASSWORD.toCharArray());
+ }
+ return keystore;
+ }
+
+ private static String token(String subject, String... roles) {
+ return tokens.generateToken(
+ new JsonObject().put("sub", subject).put("roles", new
JsonArray(List.of(roles))),
+ new JWTOptions().setAlgorithm("HS256").setIssuer(ISSUER));
+ }
+
+ private static McpSyncClient newClient(String token) {
+ return
McpClient.sync(HttpClientStreamableHttpTransport.builder("http://localhost:" +
port)
+ .httpRequestCustomizer((builder, method, uri, body, context)
-> builder
+ .header("Authorization", "Bearer " + token))
+ .build())
+ .requestTimeout(Duration.ofSeconds(10))
+ .initializationTimeout(Duration.ofSeconds(10))
+ .build();
+ }
+}
diff --git
a/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainAuthenticationTest.java
b/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainAuthenticationTest.java
index 62e96e310e84..837ba346f8c5 100644
---
a/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainAuthenticationTest.java
+++
b/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainAuthenticationTest.java
@@ -192,8 +192,8 @@ class McpServerMainAuthenticationTest {
@Test
void testMcpToolCallCarriesRuntimeNeutralPrincipalNameToTheToolRoute() {
// CAMEL-25405: alongside the raw principal, the runtime-neutral
caller name must reach the tool route over MCP
- // as the CamelMcpSecurityPrincipalName exchange property, so a policy
can authorize on a stable name without
- // depending on the Vert.x user type. For the basic-auth user the name
is the username "camel".
+ // as the CamelAiToolSecurityPrincipalName exchange property, so a
policy can authorize on a stable name
+ // without depending on the Vert.x user type. For the basic-auth user
the name is the username "camel".
String credentials =
Base64.getEncoder().encodeToString("camel:mcpPass".getBytes(UTF_8));
McpSyncClient client = null;
try {
@@ -222,8 +222,8 @@ class McpServerMainAuthenticationTest {
void testMcpBasicAuthCallerHasNoRuntimeNeutralRoles() {
// CAMEL-25405: roles are read from the authenticated token's claims.
The camel-main basic-auth user carries
// no roles in its principal (property-file roles live in the Vert.x
authorizations, not principal()), so the
- // CamelMcpSecurityPrincipalRoles property is not stamped for a
basic-auth caller. This locks in the documented
- // limitation; positive role extraction from token claims is covered
by VertxMcpPrincipalTest.
+ // CamelAiToolSecurityPrincipalRoles property is not stamped for a
basic-auth caller. This locks in the
+ // documented limitation; positive role extraction from token claims
is covered by VertxMcpPrincipalTest.
String credentials =
Base64.getEncoder().encodeToString("camel:mcpPass".getBytes(UTF_8));
McpSyncClient client = null;
try {
diff --git
a/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainOAuthTest.java
b/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainOAuthTest.java
index 9ab628a1b406..f9783a4d25f1 100644
---
a/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainOAuthTest.java
+++
b/components/camel-ai/camel-mcp-server/src/test/java/org/apache/camel/component/mcp/server/main/McpServerMainOAuthTest.java
@@ -100,6 +100,9 @@ class McpServerMainOAuthTest {
+
(exchange.getProperty(
McpToolCallContext.OAUTH_TOKEN_VALIDATION_RESULT_PROPERTY)
!= null)));
+
+ from("ai-tool:oauth_admin?tags=oauth&description=A tool for
administrators&allowedRoles=admin")
+ .setBody(constant("admin-only"));
}
});
@@ -312,6 +315,36 @@ class McpServerMainOAuthTest {
}
}
+ @Test
+ void aToolWithAllowedRolesAnswersAnOAuthCallerWhoHasTheRole() {
+ McpSyncClient client = newClient("valid");
+ try {
+ client.initialize();
+
+ McpSchema.CallToolResult result = client.callTool(new
McpSchema.CallToolRequest("oauth_admin", Map.of()));
+
+ assertThat(result.isError()).isNotEqualTo(Boolean.TRUE);
+ assertThat(result.content().toString()).contains("admin-only");
+ } finally {
+ client.closeGracefully();
+ }
+ }
+
+ @Test
+ void aToolWithAllowedRolesRefusesAnOAuthCallerWhoDoesNotHaveTheRole() {
+ McpSyncClient client = newClient("bob");
+ try {
+ client.initialize();
+
+ McpSchema.CallToolResult result = client.callTool(new
McpSchema.CallToolRequest("oauth_admin", Map.of()));
+
+ assertThat(result.isError()).isEqualTo(Boolean.TRUE);
+ assertThat(result.content().toString()).contains("Access
denied").doesNotContain("admin-only");
+ } finally {
+ client.closeGracefully();
+ }
+ }
+
private static void assertRejectedLargePostDoesNotBlockConnection(
String token, int expectedStatus, byte[] body)
throws Exception {
@@ -481,7 +514,7 @@ class McpServerMainOAuthTest {
claims.put("sub", subject);
}
claims.put("tenant", "engineering");
- claims.put("roles", List.of("admin", "analyst"));
+ claims.put("roles", "bob".equals(token) ? List.of("analyst") :
List.of("admin", "analyst"));
return OAuthTokenValidationResult.valid(
subject,
"https://id.example.test/realms/camel",
diff --git a/core/camel-api/src/main/java/org/apache/camel/ai/AiEvent.java
b/core/camel-api/src/main/java/org/apache/camel/ai/AiEvent.java
index 9c8ba82d8080..4b8b423eb762 100644
--- a/core/camel-api/src/main/java/org/apache/camel/ai/AiEvent.java
+++ b/core/camel-api/src/main/java/org/apache/camel/ai/AiEvent.java
@@ -58,9 +58,9 @@ public interface AiEvent extends CamelEvent {
}
/**
- * Fired when a tool call is denied by the route's {@code
authorizationPolicy}. Also a
- * {@link CamelEvent.FailureEvent}, so {@link #getCause()} returns the
{@code CamelAuthorizationException} the
- * policy raised.
+ * Fired when a tool call is denied by the route's {@code allowedRoles} or
{@code authorizationPolicy}. Also a
+ * {@link CamelEvent.FailureEvent}, so {@link #getCause()} returns the
{@code CamelAuthorizationException} the check
+ * raised.
*
* @since 4.24
*/
diff --git
a/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/AiToolComponentBuilderFactory.java
b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/AiToolComponentBuilderFactory.java
index 79f22a894163..8448ba04a3c9 100644
---
a/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/AiToolComponentBuilderFactory.java
+++
b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/AiToolComponentBuilderFactory.java
@@ -377,6 +377,46 @@ public interface AiToolComponentBuilderFactory {
return this;
}
+ /**
+ * Comma-separated list of the roles a caller needs to call the tool,
+ * for example finance,controlling. Any one of them is enough unless
+ * allRolesRequired is set. The roles are checked before the route
runs,
+ * against the caller's roles in the exchange property
+ * CamelAiToolSecurityPrincipalRoles: a call without that property is
+ * refused. A value that is set but names no role refuses every call.
+ * Set it on the component as the default of every tool route, or per
+ * endpoint to replace it.
+ *
+ * The option is a: <code>java.lang.String</code> type.
+ *
+ * Group: security
+ *
+ * @param allowedRoles the value to set
+ * @return the dsl builder
+ */
+ default AiToolComponentBuilder allowedRoles(java.lang.String
allowedRoles) {
+ doSetProperty("allowedRoles", allowedRoles);
+ return this;
+ }
+
+
+ /**
+ * Whether the caller needs all the roles in allowedRoles, rather than
+ * any one of them. Has no effect when allowedRoles is not set.
+ *
+ * The option is a: <code>boolean</code> type.
+ *
+ * Default: false
+ * Group: security
+ *
+ * @param allRolesRequired the value to set
+ * @return the dsl builder
+ */
+ default AiToolComponentBuilder allRolesRequired(boolean
allRolesRequired) {
+ doSetProperty("allRolesRequired", allRolesRequired);
+ return this;
+ }
+
/**
* Reference to an org.apache.camel.spi.AuthorizationPolicy used to
* authorize tool calls before the route runs. Set it on the component
@@ -441,6 +481,8 @@ public interface AiToolComponentBuilderFactory {
case "tags": getOrCreateConfiguration((AiToolComponent)
component).setTags((java.lang.String) value); return true;
case "title": getOrCreateConfiguration((AiToolComponent)
component).setTitle((java.lang.String) value); return true;
case "autowiredEnabled": ((AiToolComponent)
component).setAutowiredEnabled((boolean) value); return true;
+ case "allowedRoles": getOrCreateConfiguration((AiToolComponent)
component).setAllowedRoles((java.lang.String) value); return true;
+ case "allRolesRequired":
getOrCreateConfiguration((AiToolComponent)
component).setAllRolesRequired((boolean) value); return true;
case "authorizationPolicy":
getOrCreateConfiguration((AiToolComponent)
component).setAuthorizationPolicy((org.apache.camel.spi.AuthorizationPolicy)
value); return true;
default: return false;
}
diff --git
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AiToolEndpointBuilderFactory.java
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AiToolEndpointBuilderFactory.java
index 23e6ba69d198..11a5b7aa49ee 100644
---
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AiToolEndpointBuilderFactory.java
+++
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AiToolEndpointBuilderFactory.java
@@ -459,6 +459,59 @@ public interface AiToolEndpointBuilderFactory {
doSetProperty("title", title);
return this;
}
+ /**
+ * Comma-separated list of the roles a caller needs to call the tool,
+ * for example finance,controlling. Any one of them is enough unless
+ * allRolesRequired is set. The roles are checked before the route
runs,
+ * against the caller's roles in the exchange property
+ * CamelAiToolSecurityPrincipalRoles: a call without that property is
+ * refused. A value that is set but names no role refuses every call.
+ * Set it on the component as the default of every tool route, or per
+ * endpoint to replace it.
+ *
+ * The option is a: <code>java.lang.String</code> type.
+ *
+ * Group: security
+ *
+ * @param allowedRoles the value to set
+ * @return the dsl builder
+ */
+ default AiToolEndpointBuilder allowedRoles(String allowedRoles) {
+ doSetProperty("allowedRoles", allowedRoles);
+ return this;
+ }
+ /**
+ * Whether the caller needs all the roles in allowedRoles, rather than
+ * any one of them. Has no effect when allowedRoles is not set.
+ *
+ * The option is a: <code>boolean</code> type.
+ *
+ * Default: false
+ * Group: security
+ *
+ * @param allRolesRequired the value to set
+ * @return the dsl builder
+ */
+ default AiToolEndpointBuilder allRolesRequired(boolean
allRolesRequired) {
+ doSetProperty("allRolesRequired", allRolesRequired);
+ return this;
+ }
+ /**
+ * Whether the caller needs all the roles in allowedRoles, rather than
+ * any one of them. Has no effect when allowedRoles is not set.
+ *
+ * The option will be converted to a <code>boolean</code> type.
+ *
+ * Default: false
+ * Group: security
+ *
+ * @param allRolesRequired the value to set
+ * @return the dsl builder
+ */
+ default AiToolEndpointBuilder allRolesRequired(String
allRolesRequired) {
+ doSetProperty("allRolesRequired", allRolesRequired);
+ return this;
+ }
/**
* Reference to an org.apache.camel.spi.AuthorizationPolicy used to
* authorize tool calls before the route runs. Set it on the component