Repository navigation
Feat/add teams channel plugin #96
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
arefbehboudi
merged 7 commits into
ClawRunr:main
from
AlirezaValikhani:feat/add-teams-channel-plugin
Oct 31, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7a1970a
feat: Add teams plugin to the project
AlirezaValikhani 3746e6e
feat: add tests, JWT auth and docs for Teams channel plugin
AlirezaValikhani 7f68a6a
fix: register Teams webhook controller and correct AutoConfiguration …
AlirezaValikhani 5e578d0
chore: Remove dummy Teams config from application.yaml
AlirezaValikhani 63cb15d
fix: Address review feedback on Teams channel plugin
AlirezaValikhani c4ef78f
docs: Document Microsoft Teams channel setup in README
AlirezaValikhani d1d4059
fix: Encode token request, restrict Teams to personal chats, report a…
arefbehboudi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| plugins { | ||
| id 'java-library' | ||
| } | ||
|
|
||
| dependencies { | ||
| implementation project(':base') | ||
| implementation 'org.springframework.boot:spring-boot-starter' | ||
| implementation 'org.springframework.boot:spring-boot-starter-webmvc' | ||
| implementation(libs.nimbus.jose.jwt) | ||
|
|
||
| testImplementation 'org.springframework.boot:spring-boot-starter-test' | ||
| testImplementation 'org.springframework.boot:spring-boot-starter-json' | ||
| } |
107 changes: 107 additions & 0 deletions
107
plugins/teams/src/main/java/ai/javaclaw/channels/teams/BotFrameworkJwtValidator.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| package ai.javaclaw.channels.teams; | ||
|
|
||
| import com.nimbusds.jose.JWSAlgorithm; | ||
| import com.nimbusds.jose.jwk.source.JWKSource; | ||
| import com.nimbusds.jose.jwk.source.JWKSourceBuilder; | ||
| import com.nimbusds.jose.proc.JWSVerificationKeySelector; | ||
| import com.nimbusds.jose.proc.SecurityContext; | ||
| import com.nimbusds.jwt.JWTClaimsSet; | ||
| import com.nimbusds.jwt.SignedJWT; | ||
| import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier; | ||
| import com.nimbusds.jwt.proc.DefaultJWTProcessor; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import java.net.MalformedURLException; | ||
| import java.net.URI; | ||
| import java.time.Duration; | ||
| import java.util.Set; | ||
|
|
||
| /** | ||
| * Validates the Bot Framework Connector JWT sent on every incoming Teams webhook call | ||
| * (the {@code Authorization: Bearer <token>} header), per | ||
| * https://learn.microsoft.com/azure/bot-service/rest-api/bot-framework-rest-connector-authentication | ||
| * <p> | ||
| * A valid token must: (1) be signed with RS256 by a key currently published in Bot Framework's JWKS, | ||
| * (2) have issuer {@code https://api.botframework.com}, (3) have this bot's App ID as audience, | ||
| * (4) not be expired, allowing five minutes of clock skew as Microsoft recommends, and (5) carry a | ||
| * {@code serviceUrl} claim equal to the activity's {@code serviceUrl}. The last check matters because | ||
| * the bot later sends its own outbound token to that URL. The JWKS is fetched once and | ||
| * cached/refreshed automatically by the underlying {@link JWKSource}. | ||
| */ | ||
| class BotFrameworkJwtValidator { | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory.getLogger(BotFrameworkJwtValidator.class); | ||
| static final String EXPECTED_ISSUER = "https://api.botframework.com"; | ||
| static final String SERVICE_URL_CLAIM = "serviceUrl"; | ||
| static final int MAX_CLOCK_SKEW_SECONDS = (int) Duration.ofMinutes(5).toSeconds(); | ||
| private static final String JWKS_URL = "https://login.botframework.com/v1/.well-known/keys"; | ||
|
|
||
| private final DefaultJWTProcessor<SecurityContext> jwtProcessor; | ||
|
|
||
| BotFrameworkJwtValidator(TeamsProperties properties) { | ||
| this(properties, remoteJwkSource()); | ||
| } | ||
|
|
||
| /** Test seam: inject a local key set instead of hitting the real JWKS endpoint. */ | ||
| BotFrameworkJwtValidator(TeamsProperties properties, JWKSource<SecurityContext> jwkSource) { | ||
| String appId = properties.getAppId(); | ||
| // An empty accepted-audience set rejects every token, which is what we want without an App ID | ||
| Set<String> acceptedAudience = appId == null || appId.isBlank() ? Set.of() : Set.of(appId); | ||
|
|
||
| DefaultJWTClaimsVerifier<SecurityContext> claimsVerifier = new DefaultJWTClaimsVerifier<>( | ||
| acceptedAudience, | ||
| new JWTClaimsSet.Builder().issuer(EXPECTED_ISSUER).build(), | ||
| Set.of("exp", SERVICE_URL_CLAIM), | ||
| null); | ||
| claimsVerifier.setMaxClockSkew(MAX_CLOCK_SKEW_SECONDS); | ||
|
|
||
| this.jwtProcessor = new DefaultJWTProcessor<>(); | ||
| this.jwtProcessor.setJWSKeySelector(new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource)); | ||
| this.jwtProcessor.setJWTClaimsSetVerifier(claimsVerifier); | ||
| } | ||
|
|
||
| private static JWKSource<SecurityContext> remoteJwkSource() { | ||
| try { | ||
| return JWKSourceBuilder | ||
| .create(URI.create(JWKS_URL).toURL()) | ||
| .cache(Duration.ofMinutes(30).toMillis(), Duration.ofMinutes(1).toMillis()) | ||
| .build(); | ||
| } catch (MalformedURLException e) { | ||
| throw new IllegalStateException("Invalid Bot Framework JWKS URL: " + JWKS_URL, e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * @param bearerToken the token from the {@code Authorization} header, without the {@code Bearer } prefix | ||
| * @param serviceUrl the {@code serviceUrl} of the incoming activity | ||
| * @return true if {@code bearerToken} is a currently valid Bot Framework Connector token for this bot | ||
| * that was issued for {@code serviceUrl} | ||
| */ | ||
| boolean isValid(String bearerToken, String serviceUrl) { | ||
| try { | ||
| // Throws if the signature, algorithm, issuer, audience or expiry is wrong | ||
| JWTClaimsSet claims = jwtProcessor.process(SignedJWT.parse(bearerToken), null); | ||
|
|
||
| String tokenServiceUrl = claims.getStringClaim(SERVICE_URL_CLAIM); | ||
| if (serviceUrl == null || !sameUrl(tokenServiceUrl, serviceUrl)) { | ||
| LOGGER.warn("Rejected Teams webhook JWT issued for serviceUrl '{}' on an activity for '{}'", | ||
| tokenServiceUrl, serviceUrl); | ||
| return false; | ||
| } | ||
| return true; | ||
| } catch (Exception e) { | ||
| LOGGER.warn("Rejected Teams webhook JWT: {}", e.getMessage()); | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /** Compares two URLs, ignoring a trailing slash and letter case. */ | ||
| private static boolean sameUrl(String a, String b) { | ||
| return a != null && stripTrailingSlash(a).equalsIgnoreCase(stripTrailingSlash(b)); | ||
| } | ||
|
|
||
| private static String stripTrailingSlash(String url) { | ||
| return url.endsWith("/") ? url.substring(0, url.length() - 1) : url; | ||
| } | ||
| } | ||
91 changes: 91 additions & 0 deletions
91
plugins/teams/src/main/java/ai/javaclaw/channels/teams/BotFrameworkTokenProvider.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| package ai.javaclaw.channels.teams; | ||
|
|
||
| import tools.jackson.databind.json.JsonMapper; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import java.net.URI; | ||
| import java.net.URLEncoder; | ||
| import java.net.http.HttpClient; | ||
| import java.net.http.HttpRequest; | ||
| import java.net.http.HttpResponse; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.time.Instant; | ||
| import java.util.concurrent.atomic.AtomicReference; | ||
|
|
||
| /** | ||
| * Fetches and caches an OAuth2 client-credentials token for the Bot Framework | ||
| * Connector API, using the Azure AD v2 endpoint (login.microsoftonline.com). | ||
| */ | ||
| class BotFrameworkTokenProvider { | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory.getLogger(BotFrameworkTokenProvider.class); | ||
| private static final String SCOPE = "https://api.botframework.com/.default"; | ||
| private static final JsonMapper JSON = JsonMapper.builder().build(); | ||
|
|
||
| private final TeamsProperties properties; | ||
| private final HttpClient httpClient; | ||
| private final AtomicReference<CachedToken> cached = new AtomicReference<>(); | ||
|
|
||
| BotFrameworkTokenProvider(TeamsProperties properties, HttpClient httpClient) { | ||
| this.properties = properties; | ||
| this.httpClient = httpClient; | ||
| } | ||
|
|
||
| /** @return a valid bearer token, refreshing it if expired or missing */ | ||
| synchronized String getToken() { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. synchronized together with AtomicReference (line 26) is redundant. Since the method is already synchronized, a plain field is enough. |
||
| CachedToken token = cached.get(); | ||
| if (token != null && Instant.now().isBefore(token.expiresAt())) { | ||
| return token.value(); | ||
| } | ||
| CachedToken fresh = fetchToken(); | ||
| cached.set(fresh); | ||
| return fresh.value(); | ||
| } | ||
|
|
||
| private CachedToken fetchToken() { | ||
| String tenantId = properties.getTenantId(); | ||
| if (tenantId == null || tenantId.isBlank()) { | ||
| throw new IllegalStateException("No agent.channels.teams.tenant-id configured, cannot obtain a Bot Framework access token"); | ||
| } | ||
| // URLEncoder encodes a space as '+', which is only valid in a form body, not in a path segment | ||
| String tokenUrl = "https://login.microsoftonline.com/" + encode(tenantId.trim()).replace("+", "%20") | ||
| + "/oauth2/v2.0/token"; | ||
| // Client secrets may contain '+', '&' or '=', so every value must be form-encoded | ||
| String body = "grant_type=client_credentials" | ||
| + "&client_id=" + encode(properties.getAppId()) | ||
| + "&client_secret=" + encode(properties.getAppSecret()) | ||
| + "&scope=" + encode(SCOPE); | ||
|
|
||
| HttpRequest request = HttpRequest.newBuilder(URI.create(tokenUrl)) | ||
| .header("Content-Type", "application/x-www-form-urlencoded") | ||
| .POST(HttpRequest.BodyPublishers.ofString(body)) | ||
| .build(); | ||
| try { | ||
| HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); | ||
| if (response.statusCode() != 200) { | ||
| // The response body is left out on purpose: it may echo request details | ||
| throw new IllegalStateException( | ||
| "Bot Framework token request failed with status " + response.statusCode()); | ||
| } | ||
| TokenResponse parsed = JSON.readValue(response.body(), TokenResponse.class); | ||
| return new CachedToken(parsed.accessToken(), | ||
| Instant.now().plusSeconds(Math.max(0, parsed.expiresIn() - 60))); | ||
| } catch (Exception e) { | ||
| LOGGER.error("Failed to fetch Bot Framework access token", e); | ||
| throw new IllegalStateException("Could not obtain Bot Framework access token", e); | ||
| } | ||
| } | ||
|
|
||
| private static String encode(String value) { | ||
| return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8); | ||
| } | ||
|
|
||
| private record CachedToken(String value, Instant expiresAt) { | ||
| } | ||
|
|
||
| private record TokenResponse( | ||
| @com.fasterxml.jackson.annotation.JsonProperty("access_token") String accessToken, | ||
| @com.fasterxml.jackson.annotation.JsonProperty("expires_in") int expiresIn) { | ||
| } | ||
| } | ||
26 changes: 26 additions & 0 deletions
26
plugins/teams/src/main/java/ai/javaclaw/channels/teams/TeamsActivityPayload.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package ai.javaclaw.channels.teams; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties; | ||
| import com.fasterxml.jackson.annotation.JsonProperty; | ||
|
|
||
| @JsonIgnoreProperties(ignoreUnknown = true) | ||
| public record TeamsActivityPayload( | ||
| @JsonProperty("type") String type, | ||
| @JsonProperty("id") String id, | ||
| @JsonProperty("serviceUrl") String serviceUrl, | ||
| @JsonProperty("channelId") String channelId, | ||
| @JsonProperty("text") String text, | ||
| @JsonProperty("from") From from, | ||
| @JsonProperty("conversation") Conversation conversation) { | ||
|
|
||
| @JsonIgnoreProperties(ignoreUnknown = true) | ||
| public record From(@JsonProperty("id") String id, @JsonProperty("name") String name, | ||
| @JsonProperty("aadObjectId") String aadObjectId) { | ||
| } | ||
|
|
||
| @JsonIgnoreProperties(ignoreUnknown = true) | ||
| /** {@code conversationType} is {@code "personal"}, {@code "groupChat"} or {@code "channel"}. */ | ||
| public record Conversation(@JsonProperty("id") String id, | ||
| @JsonProperty("conversationType") String conversationType) { | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.