Skip to content

Auth: Support required endorsements #2019

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
merged 5 commits into from
Jun 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build/PublishToCoveralls.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Param(

Write-Host Install tools
$basePath = (get-item $pathToCoverageFiles ).parent.FullName
$coverageAnalyzer = "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Team Tools\Dynamic Code Coverage Tools\CodeCoverage.exe"
$coverageAnalyzer = "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Team Tools\Dynamic Code Coverage Tools\CodeCoverage.exe"
dotnet tool install coveralls.net --version 1.0.0 --tool-path tools
$coverageUploader = ".\tools\csmacnz.Coveralls.exe"

Expand Down
33 changes: 32 additions & 1 deletion libraries/Microsoft.Bot.Builder/BotFrameworkAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public class BotFrameworkAdapter : BotAdapter, IAdapterIntegration, IUserTokenPr
private readonly RetryPolicy _connectorClientRetryPolicy;
private readonly ILogger _logger;
private readonly ConcurrentDictionary<string, MicrosoftAppCredentials> _appCredentialMap = new ConcurrentDictionary<string, MicrosoftAppCredentials>();
private readonly AuthenticationConfiguration _authConfiguration;

// There is a significant boost in throughput if we reuse a connectorClient
// _connectorClients is a cache using [serviceUrl + appId].
Expand Down Expand Up @@ -82,12 +83,42 @@ public BotFrameworkAdapter(
HttpClient customHttpClient = null,
IMiddleware middleware = null,
ILogger logger = null)
: this(credentialProvider, new AuthenticationConfiguration(), channelProvider, connectorClientRetryPolicy, customHttpClient, middleware, logger)
{
}

/// <summary>
/// Initializes a new instance of the <see cref="BotFrameworkAdapter"/> class,
/// using a credential provider.
/// </summary>
/// <param name="credentialProvider">The credential provider.</param>
/// <param name="authConfig">The authentication configuration.</param>
/// <param name="channelProvider">The channel provider.</param>
/// <param name="connectorClientRetryPolicy">Retry policy for retrying HTTP operations.</param>
/// <param name="customHttpClient">The HTTP client.</param>
/// <param name="middleware">The middleware to initially add to the adapter.</param>
/// <param name="logger">The ILogger implementation this adapter should use.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="credentialProvider"/> is <c>null</c>.</exception>
/// <remarks>Use a <see cref="MiddlewareSet"/> object to add multiple middleware
/// components in the constructor. Use the <see cref="Use(IMiddleware)"/> method to
/// add additional middleware to the adapter after construction.
/// </remarks>
public BotFrameworkAdapter(
ICredentialProvider credentialProvider,
AuthenticationConfiguration authConfig,
IChannelProvider channelProvider = null,
RetryPolicy connectorClientRetryPolicy = null,
HttpClient customHttpClient = null,
IMiddleware middleware = null,
ILogger logger = null)
{
_credentialProvider = credentialProvider ?? throw new ArgumentNullException(nameof(credentialProvider));
_channelProvider = channelProvider;
_httpClient = customHttpClient ?? _defaultHttpClient;
_connectorClientRetryPolicy = connectorClientRetryPolicy;
_logger = logger ?? NullLogger.Instance;
_authConfiguration = authConfig ?? throw new ArgumentNullException(nameof(authConfig));

if (middleware != null)
{
Expand Down Expand Up @@ -211,7 +242,7 @@ public async Task<InvokeResponse> ProcessActivityAsync(string authHeader, Activi
{
BotAssert.ActivityNotNull(activity);

var claimsIdentity = await JwtTokenValidation.AuthenticateRequest(activity, authHeader, _credentialProvider, _channelProvider, _httpClient).ConfigureAwait(false);
var claimsIdentity = await JwtTokenValidation.AuthenticateRequest(activity, authHeader, _credentialProvider, _channelProvider, _authConfiguration, _httpClient).ConfigureAwait(false);
return await ProcessActivityAsync(claimsIdentity, activity, callback, cancellationToken).ConfigureAwait(false);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

namespace Microsoft.Bot.Connector.Authentication
{
/// <summary>
/// General configuration settings for authentication.
/// </summary>
/// <remarks>
/// Note that this is explicitly a class and not an interface,
/// since interfaces don't support default values, after the initial release any change would break backwards compatibility.
/// </remarks>
public class AuthenticationConfiguration
{
public string[] RequiredEndorsements { get; set; } = new string[] { };
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,39 @@ public static class ChannelValidation
/// </returns>
public static async Task<ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, HttpClient httpClient, string channelId)
{
return await AuthenticateChannelToken(authHeader, credentials, httpClient, channelId, new AuthenticationConfiguration()).ConfigureAwait(false);
}

/// <summary>
/// Validate the incoming Auth Header as a token sent from the Bot Framework Service.
/// </summary>
/// <remarks>
/// A token issued by the Bot Framework emulator will FAIL this check.
/// </remarks>
/// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param>
/// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param>
/// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The
/// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to
/// setup and teardown, so a shared HttpClient is recommended.</param>
/// <param name="channelId">The ID of the channel to validate.</param>
/// <param name="authConfig">The authentication configuration.</param>
/// <returns>
/// A valid ClaimsIdentity.
/// </returns>
public static async Task<ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfig)
{
if (authConfig == null)
{
throw new ArgumentNullException(nameof(authConfig));
}

var tokenExtractor = new JwtTokenExtractor(
httpClient,
ToBotFromChannelTokenValidationParameters,
OpenIdMetadataUrl,
AuthenticationConstants.AllowedSigningAlgorithms);

var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId);
var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfig.RequiredEndorsements);
if (identity == null)
{
// No valid identity. Not Authorized.
Expand Down Expand Up @@ -118,7 +144,29 @@ public static async Task<ClaimsIdentity> AuthenticateChannelToken(string authHea
/// <returns>ClaimsIdentity.</returns>
public static async Task<ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, string serviceUrl, HttpClient httpClient, string channelId)
{
var identity = await AuthenticateChannelToken(authHeader, credentials, httpClient, channelId);
return await AuthenticateChannelToken(authHeader, credentials, serviceUrl, httpClient, channelId, new AuthenticationConfiguration()).ConfigureAwait(false);
}

/// <summary>
/// Validate the incoming Auth Header as a token sent from the Bot Framework Service.
/// </summary>
/// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param>
/// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param>
/// <param name="serviceUrl">Service url.</param>
/// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The
/// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to
/// setup and teardown, so a shared HttpClient is recommended.</param>
/// <param name="channelId">The ID of the channel to validate.</param>
/// <param name="authConfig">The authentication configuration.</param>
/// <returns>ClaimsIdentity.</returns>
public static async Task<ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, string serviceUrl, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfig)
{
if (authConfig == null)
{
throw new ArgumentNullException(nameof(authConfig));
}

var identity = await AuthenticateChannelToken(authHeader, credentials, httpClient, channelId, authConfig);

var serviceUrlClaim = identity.Claims.FirstOrDefault(claim => claim.Type == AuthenticationConstants.ServiceUrlClaim)?.Value;
if (string.IsNullOrWhiteSpace(serviceUrlClaim))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,33 @@ public static bool IsTokenFromEmulator(string authHeader)
/// </remarks>
public static async Task<ClaimsIdentity> AuthenticateEmulatorToken(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, HttpClient httpClient, string channelId)
{
return await AuthenticateEmulatorToken(authHeader, credentials, channelProvider, httpClient, channelId, new AuthenticationConfiguration()).ConfigureAwait(false);
}

/// <summary>
/// Validate the incoming Auth Header as a token sent from the Bot Framework Emulator.
/// </summary>
/// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param>
/// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param>
/// <param name="channelProvider">The channelService value that distinguishes public Azure from US Government Azure.</param>
/// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The
/// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to
/// setup and teardown, so a shared HttpClient is recommended.</param>
/// <param name="channelId">The ID of the channel to validate.</param>
/// <param name="authConfig">The authentication configuration.</param>
/// <returns>
/// A valid ClaimsIdentity.
/// </returns>
/// <remarks>
/// A token issued by the Bot Framework will FAIL this check. Only Emulator tokens will pass.
/// </remarks>
public static async Task<ClaimsIdentity> AuthenticateEmulatorToken(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfig)
{
if (authConfig == null)
{
throw new ArgumentNullException(nameof(authConfig));
}

var openIdMetadataUrl = (channelProvider != null && channelProvider.IsGovernment()) ?
GovernmentAuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl :
AuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl;
Expand All @@ -121,7 +148,7 @@ public static async Task<ClaimsIdentity> AuthenticateEmulatorToken(string authHe
openIdMetadataUrl,
AuthenticationConstants.AllowedSigningAlgorithms);

var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId);
var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfig.RequiredEndorsements);
if (identity == null)
{
// No valid identity. Not Authorized.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,28 @@ namespace Microsoft.Bot.Connector.Authentication
public static class EndorsementsValidator
{
/// <summary>
/// Verify that a channel matches the endorsements found on the JWT token.
/// Verify that the specified endorsement exists on the JWT token. Call this method multiple times to validate multiple endorsements.
/// For example, if an <see cref="Schema.Activity"/> comes from WebChat, that activity's
/// <see cref="Schema.Activity.ChannelId"/> property is set to "webchat" and the signing party
/// of the JWT token must have a corresponding endorsement of “Webchat”.
/// </summary>
/// <param name="channelId">The ID of the channel to validate, typically extracted from the activity's
/// <see cref="Schema.Activity.ChannelId"/> property, that to which the Activity is affinitized.</param>
/// <remarks>
/// JWT token signing keys contain endorsements matching the IDs of the channels they are approved to sign for.
/// They also contain keywords representing compliance certifications. This code ensures that a channel ID or compliance
/// certification is present on the signing key used for the request's token.
/// </remarks>
/// <param name="expectedEndorsement">The expected endorsement. Generally the ID of the channel to validate, typically extracted from the activity's
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The right way to think about this is:

  • In nearly all cases, the channel ID is the required endorsement
  • In some cases, the developer may elect to require an additional endorsement, but this is always additive to the channel ID endorsement
  • In very rare cases, a developer will elect to remove the channel ID endorsement, but they are operating in a less secure / unsupported mode at this point.

/// <see cref="Schema.Activity.ChannelId"/> property, that to which the Activity is affinitized. Alternatively, it could represent a compliance certification that is required.</param>
/// <param name="endorsements">The JWT token’s signing party is permitted to send activities only for
/// specific channels. That list, the set of channels the service can sign for, is called the the endorsement list.
/// The activity’s <see cref="Schema.Activity.ChannelId"/> MUST be found in the endorsement list, or the incoming
/// activity is not considered valid.</param>
/// <returns>True if the channel ID is found in the endorsements list; otherwise, false.</returns>
public static bool Validate(string channelId, HashSet<string> endorsements)
public static bool Validate(string expectedEndorsement, HashSet<string> endorsements)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following the logic above, I expect that new endorsements are added to the channel ID endorsement.

We could have a mode where all endorsements are removed, but this is advanced and I'm not sure we have a use case for it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh, I see how the channel ID endorsement verification is enforced at the layer above. Seems OK to me. Maybe just comment that multiple endorsements are enforced by calling this method multiple times.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading more through the comment on this method, it should be rewritten to something more like:

    /// <summary>
    /// Verify that the specified endorsement exists on the JWT token. Call this method multiple times to validate multiple endorsements.
    /// </summary>
    /// <remarks>
    /// JWT token signing keys contain endorsements matching channel IDs they're approved to sign for. They also can contain keywords representing compliance certifications. This code ensures that a channel ID or compliance certification is present on the signing key used for the request's token.
    /// </remarks>

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, EndorsementsValidator.Validate is only a collection existence check which was somewhat underwhelming to find out.

{
// If the Activity came in and doesn't have a channel ID then it's making no
// assertions as to who endorses it. This means it should pass.
if (string.IsNullOrEmpty(channelId))
if (string.IsNullOrEmpty(expectedEndorsement))
{
return true;
}
Expand All @@ -48,7 +53,7 @@ public static bool Validate(string channelId, HashSet<string> endorsements)
// JWTTokenExtractor

// Does the set of endorsements match the channelId that was passed in?
var endorsementPresent = endorsements.Contains(channelId);
var endorsementPresent = endorsements.Contains(expectedEndorsement);
return endorsementPresent;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,29 @@ public sealed class EnterpriseChannelValidation
/// <returns>ClaimsIdentity.</returns>
public static async Task<ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string serviceUrl, HttpClient httpClient, string channelId)
{
return await AuthenticateChannelToken(authHeader, credentials, channelProvider, serviceUrl, httpClient, channelId, new AuthenticationConfiguration()).ConfigureAwait(false);
}

/// <summary>
/// Validate the incoming Auth Header as a token sent from a Bot Framework Channel Service.
/// </summary>
/// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param>
/// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param>
/// <param name="channelProvider">The user defined configuration for the channel.</param>
/// <param name="serviceUrl">The service url from the request.</param>
/// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The
/// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to
/// setup and teardown, so a shared HttpClient is recommended.</param>
/// <param name="channelId">The ID of the channel to validate.</param>
/// <param name="authConfig">The authentication configuration.</param>
/// <returns>ClaimsIdentity.</returns>
public static async Task<ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string serviceUrl, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfig)
{
if (authConfig == null)
{
throw new ArgumentNullException(nameof(authConfig));
}

var channelService = await channelProvider.GetChannelServiceAsync().ConfigureAwait(false);

var tokenExtractor = new JwtTokenExtractor(
Expand All @@ -50,7 +73,7 @@ public static async Task<ClaimsIdentity> AuthenticateChannelToken(string authHea
string.Format(AuthenticationConstants.ToBotFromEnterpriseChannelOpenIdMetadataUrlFormat, channelService),
AuthenticationConstants.AllowedSigningAlgorithms);

var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId).ConfigureAwait(false);
var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfig.RequiredEndorsements).ConfigureAwait(false);

await ValidateIdentity(identity, credentials, serviceUrl).ConfigureAwait(false);

Expand Down
Loading