Files
quantconnect--lean/Brokerages/Authentication/OAuthTokenRequest.cs
T
Roman Yavnikov 541682fa4e
Python Virtual Environments / build (push) Has been cancelled
Benchmarks / build (push) Has been cancelled
Build & Test Lean / build (push) Has been cancelled
Regression Tests / build (push) Has been cancelled
Research Regression Tests / build (push) Has been cancelled
Syntax Tests / build (push) Has been cancelled
Report Generator Tests / build (push) Has been cancelled
API Tests / build (push) Has been cancelled
feat: add CreateOAuthTokenHandler factory to Brokerage base class (#9330)
* feat: add CreateOAuthTokenHandler factory to Brokerage base class

Introduce AuthenticationFailed event on TokenHandler raised when all
retry attempts are exhausted. Add CreateOAuthTokenHandler<TRequest,TResponse>
protected factory method on Brokerage that wires the event to OnMessage
(BrokerageMessageType.Error), triggering graceful Lean shutdown on
OAuth token refresh failure without requiring per-brokerage error logic.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: token retry logic: move to OAuthTokenHandler

* refactor: replace generic OAuthTokenHandler with non-generic, require explicit token lifetime

- Remove generic type parameters <TRequest, TResponse> from OAuthTokenHandler and
  CreateOAuthTokenHandler; use LeanAccessTokenMetaDataRequest and
  AccessTokenMetaDataResponse directly
- Delete abstract AccessTokenMetaDataRequest; logic moved to LeanAccessTokenMetaDataRequest
- Make tokenLifetime a required constructor parameter — each brokerage must explicitly
  declare its OAuth token lifetime to prevent silent 1-hour fallback bugs
- Move expiry tracking into the handler via _tokenExpiresAt (written under lock before the
  volatile write of _tokenCredentials, ensuring correct visibility on the fast path)
- Simplify AccessTokenMetaDataResponse to a concrete class with { get; set; } properties

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: add unit tests for OAuthTokenHandler and AccessTokenMetaDataResponse

- Make ApiConnection.TryRequest<T>(HttpRequestMessage) virtual to allow
  test subclasses to intercept without real HTTP calls
- Add AccessTokenMetaDataResponseTests: two parameterized cases verify that
  TokenType defaults to Bearer when absent from JSON (CharlesSchwab pattern)
  and deserializes correctly when present (Tastytrade pattern)
- Add OAuthTokenHandlerTests with FakeApiConnection stub:
  CharlesSchwab-style response (no tokenType, 30-min lifetime) and
  Tastytrade-style response (explicit tokenType + expiresIn/tokenId, 15-min lifetime)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: backward-compatible OAuth auth with new LeanOAuthTokenHandler hierarchy

- Restore master API: OAuthTokenHandler<TReq,TRes>, AccessTokenMetaDataRequest,
  AccessTokenMetaDataResponse, and TokenHandler stay source-compatible for old consumers
- Extend TokenHandler with AuthenticationFailed event; simplify Send() (auth header only)
- Add LeanOAuthTokenHandler: non-generic, thread-safe double-checked locking, explicit
  tokenLifetime, retry logic in GetAccessToken, fires AuthenticationFailed on exhaustion
- Add OAuthTokenRequest / OAuthTokenResponse: concrete Lean platform request/response
- Brokerage.CreateOAuthTokenHandler wires AuthenticationFailed to graceful shutdown
- Update tests: OAuthTokenResponseTests, LeanOAuthTokenHandlerTests, TokenHandlerTests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Some tweaks

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2026-03-14 13:10:52 -03:00

88 lines
3.5 KiB
C#

/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed 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.
*/
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace QuantConnect.Brokerages.Authentication
{
/// <summary>
/// Represents a Lean platform token request, including all fields required by the
/// <c>live/auth0/refresh</c> endpoint. Optional fields are omitted from JSON when null.
/// </summary>
public class OAuthTokenRequest
{
/// <summary>
/// Gets the name of the brokerage associated with the access token request.
/// The value is normalized to lowercase.
/// </summary>
public string Brokerage { get; set; }
/// <summary>
/// Gets the account identifier associated with the brokerage.
/// </summary>
public string AccountId { get; set; }
/// <summary>
/// Gets the OAuth refresh token used to obtain a new access token.
/// Omitted from JSON when null.
/// </summary>
public string RefreshToken { get; set; }
/// <summary>
/// Gets the Lean deploy identifier for brokerages that require it.
/// Omitted from JSON when null.
/// </summary>
public string DeployId { get; set; }
/// <summary>
/// Initializes a new instance of <see cref="OAuthTokenRequest"/> with all fields.
/// Use named parameters to supply only the fields required by the target brokerage.
/// </summary>
/// <param name="brokerage">The brokerage name. Normalized to lowercase.</param>
/// <param name="accountId">The account number or identifier.</param>
/// <param name="refreshToken">OAuth refresh token; omitted from JSON when null.</param>
/// <param name="deployId">Lean deploy identifier; omitted from JSON when null.</param>
public OAuthTokenRequest(
string brokerage,
string accountId,
string refreshToken = null,
string deployId = null)
{
#pragma warning disable CA1308 // Normalize strings to uppercase
Brokerage = brokerage.ToLowerInvariant();
#pragma warning restore CA1308 // Normalize strings to uppercase
AccountId = accountId;
RefreshToken = refreshToken;
DeployId = deployId;
}
/// <summary>
/// Serializes the request into a compact camelCase JSON string.
/// Null properties are excluded from the output.
/// </summary>
/// <returns>A JSON string representing the current request.</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.None
});
}
}
}