diff --git a/.gitignore b/.gitignore index 9491a2f..29e5569 100644 --- a/.gitignore +++ b/.gitignore @@ -1,363 +1,364 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Mono auto generated files -mono_crash.* - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -[Ww][Ii][Nn]32/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ -bld/ -[Bb]in/ -[Oo]bj/ -[Oo]ut/ -[Ll]og/ -[Ll]ogs/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUnit -*.VisualState.xml -TestResult.xml -nunit-*.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# ASP.NET Scaffolding -ScaffoldingReadMe.txt - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Coverlet is a free, cross platform Code Coverage Tool -coverage*.json -coverage*.xml -coverage*.info - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# NuGet Symbol Packages -*.snupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx -*.appxbundle -*.appxupload - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!?*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser -*- [Bb]ackup.rdl -*- [Bb]ackup ([0-9]).rdl -*- [Bb]ackup ([0-9][0-9]).rdl - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ - -# Fody - auto-generated XML schema -FodyWeavers.xsd \ No newline at end of file +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd +/.claude/settings.local.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 266725a..63ff912 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.4.0] - 2025-09-08 + +### Added +- JWT Bearer Authentication with ES256 signatures replacing legacy HMAC +- Unified `CoinbaseClientConfig` for both API and WebSocket clients +- Dependency Injection support with `AddCoinbaseAdvancedTradeClient()` extension +- Enhanced security with JWT tokens (2-minute expiration and replay protection) + +### Changed +- Migrated from HMAC-SHA256 to JWT Bearer tokens with ECDSA ES256 signatures +- Configuration properties renamed: `ApiKey`/`ApiSecret` → `KeyName`/`KeySecret` +- Requires Coinbase Cloud API keys (EC P-256 private keys in PEM format) +- Constructor parameters now use `IOptions` + +### Removed +- Legacy `ApiKeyAuthenticator` and CB-ACCESS-* header authentication + ## [0.3.0] - 2025-08-25 ### Added diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs new file mode 100644 index 0000000..7ce03df --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs @@ -0,0 +1,47 @@ +using CoinbaseAdvancedTradeClient.Authentication; +using CoinbaseAdvancedTradeClient.UnitTests.TestHelpers; +using Xunit; + +namespace CoinbaseAdvancedTradeClient.UnitTests.Authentication +{ + public class SecretApiKeyAuthenticatorTests + { + [Fact] + public void GenerateBearerJWT_ValidParameters_ReturnsJWT() + { + // Arrange + var testKeySecret = TestConfigHelper.GenerateTestKeySecret(); + + // Act + var result = SecretApiKeyAuthenticator.GenerateBearerJWT( + "test-key-name", + testKeySecret, + "GET", + "api.coinbase.com", + "/v1/test" + ); + + // Assert + Assert.NotNull(result); + Assert.Contains(".", result); + var parts = result.Split('.'); + Assert.Equal(3, parts.Length); // header.payload.signature + } + + [Fact] + public void GenerateBearerJWT_InvalidKeySecret_ThrowsArgumentException() + { + // Act & Assert + Assert.Throws(() => + { + SecretApiKeyAuthenticator.GenerateBearerJWT( + "test-key-name", + "invalid-key-format", + "GET", + "api.coinbase.com", + "/v1/test" + ); + }); + } + } +} \ No newline at end of file diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs index 0faba69..28ed881 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs @@ -1,4 +1,5 @@ using CoinbaseAdvancedTradeClient.Models.Config; +using Microsoft.Extensions.Options; using Xunit; namespace CoinbaseAdvancedTradeClient.UnitTests @@ -9,7 +10,7 @@ public class CoinbaseAdvancedTradeApiClientTests public void Constructor_NullConfig_ThrowsArgumentNullException() { //Arrange - ApiClientConfig config = null; + IOptions config = null; //Act & Assert Assert.Throws(() => @@ -27,11 +28,12 @@ public void Constructor_NullConfig_ThrowsArgumentNullException() public void Constructor_EmptyConfigSetting_ThrowsArgumentException(string key, string secret) { //Arrange - ApiClientConfig config = new ApiClientConfig() + var configValue = new CoinbaseClientConfig() { - ApiKey = key, - ApiSecret = secret + KeyName = key, + KeySecret = secret }; + var config = Options.Create(configValue); //Act & Assert Assert.Throws(() => diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeClient.UnitTests.csproj b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeClient.UnitTests.csproj index 209fd69..d9efea3 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeClient.UnitTests.csproj +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeClient.UnitTests.csproj @@ -9,6 +9,7 @@ + diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs index ff7c831..600f20b 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs @@ -1,6 +1,7 @@ using CoinbaseAdvancedTradeClient.Constants; using CoinbaseAdvancedTradeClient.Interfaces; using CoinbaseAdvancedTradeClient.Models.Config; +using Microsoft.Extensions.Options; using System.Net.Sockets; using Xunit; @@ -12,7 +13,7 @@ public class CoinbaseAdvancedTradeWebSocketClientTests public void Constructor_NullConfig_ThrowsArgumentNullException() { //Arrange - WebSocketClientConfig config = null; + IOptions config = null; //Act & Assert Assert.Throws(() => @@ -30,11 +31,12 @@ public void Constructor_NullConfig_ThrowsArgumentNullException() public void Constructor_EmptyConfigSetting_ThrowsArgumentException(string key, string secret) { //Arrange - WebSocketClientConfig config = new WebSocketClientConfig() + var configValue = new CoinbaseClientConfig() { - ApiKey = key, - ApiSecret = secret + KeyName = key, + KeySecret = secret }; + var config = Options.Create(configValue); //Act & Assert Assert.Throws(() => @@ -164,11 +166,12 @@ public void Unsubscribe_EmptyProductIds_ThrowsArgumentNullException() private ICoinbaseAdvancedTradeWebSocketClient CreateTestClient() { - WebSocketClientConfig config = new WebSocketClientConfig() + var configValue = new CoinbaseClientConfig() { - ApiKey = "testKey", - ApiSecret = "testSecret" + KeyName = "testKey", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); return new CoinbaseAdvancedTradeWebSocketClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs index 6fa6ea5..b8267f5 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs @@ -5,6 +5,7 @@ using CoinbaseAdvancedTradeClient.Models.Pages; using Flurl.Http; using Flurl.Http.Testing; +using Microsoft.Extensions.Options; using System.Globalization; using Xunit; @@ -16,11 +17,12 @@ public class AccountsEndpointTests public AccountsEndpointTests() { - var config = new ApiClientConfig() + var configValue = new CoinbaseClientConfig() { - ApiKey = "key", - ApiSecret = "secret" + KeyName = "key", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); _testClient = new CoinbaseAdvancedTradeApiClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs index c20f935..18d699a 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs @@ -7,6 +7,7 @@ using FakeItEasy; using Flurl.Http; using Flurl.Http.Testing; +using Microsoft.Extensions.Options; using Xunit; namespace CoinbaseAdvancedTradeClient.UnitTests.Endpoints @@ -17,11 +18,12 @@ public class OrdersEndpointTests public OrdersEndpointTests() { - var config = new ApiClientConfig() + var configValue = new CoinbaseClientConfig() { - ApiKey = "key", - ApiSecret = "secret" + KeyName = "key", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); _testClient = new CoinbaseAdvancedTradeApiClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs index 89ce47e..1bd6bd2 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs @@ -7,6 +7,7 @@ using CoinbaseAdvancedTradeClient.Resources; using Flurl.Http; using Flurl.Http.Testing; +using Microsoft.Extensions.Options; using Xunit; namespace CoinbaseAdvancedTradeClient.UnitTests.Endpoints @@ -17,11 +18,12 @@ public class ProductsEndpointTests public ProductsEndpointTests() { - var config = new ApiClientConfig() + var configValue = new CoinbaseClientConfig() { - ApiKey = "key", - ApiSecret = "secret" + KeyName = "key", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); _testClient = new CoinbaseAdvancedTradeApiClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs index aeb81de..4a41898 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs @@ -6,6 +6,7 @@ using CoinbaseAdvancedTradeClient.Models.Config; using Flurl.Http; using Flurl.Http.Testing; +using Microsoft.Extensions.Options; using Xunit; namespace CoinbaseAdvancedTradeClient.UnitTests.Endpoints @@ -16,11 +17,12 @@ public class TransactionSummaryEndpointTests public TransactionSummaryEndpointTests() { - var config = new ApiClientConfig() + var configValue = new CoinbaseClientConfig() { - ApiKey = "key", - ApiSecret = "secret" + KeyName = "key", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); _testClient = new CoinbaseAdvancedTradeApiClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs new file mode 100644 index 0000000..08782f4 --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs @@ -0,0 +1,31 @@ +using Org.BouncyCastle.Asn1.Sec; +using Org.BouncyCastle.Crypto.Generators; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.OpenSsl; +using Org.BouncyCastle.Security; + +namespace CoinbaseAdvancedTradeClient.UnitTests.TestHelpers +{ + public static class TestConfigHelper + { + // Generate a valid EC P-256 private key for testing purposes + public static string GenerateTestKeySecret() + { + // Generate P-256 (secp256r1) key pair + var keyGen = new ECKeyPairGenerator(); + var curveParams = SecNamedCurves.GetByName("secp256r1"); + var domainParams = new ECDomainParameters(curveParams.Curve, curveParams.G, curveParams.N, curveParams.H); + keyGen.Init(new ECKeyGenerationParameters(domainParams, new SecureRandom())); + + var keyPair = keyGen.GenerateKeyPair(); + var privateKey = (ECPrivateKeyParameters)keyPair.Private; + + // Convert to PEM format + using var stringWriter = new StringWriter(); + var pemWriter = new PemWriter(stringWriter); + pemWriter.WriteObject(privateKey); + + return stringWriter.ToString(); + } + } +} \ No newline at end of file diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/ApiKeyAuthenticator.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/ApiKeyAuthenticator.cs deleted file mode 100644 index 98cba85..0000000 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/ApiKeyAuthenticator.cs +++ /dev/null @@ -1,47 +0,0 @@ -using CoinbaseAdvancedTradeClient.Resources; -using System.Globalization; -using System.Security.Cryptography; -using System.Text; - -namespace CoinbaseAdvancedTradeClient.Authentication -{ - public static class ApiKeyAuthenticator - { - public static string GenerateTimestamp() - { - var unixTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - var timestamp = unixTime.ToString(CultureInfo.InvariantCulture); - - return timestamp; - } - - public static string GenerateApiSignature(string apiSecret, string timestamp, string method, string requestPath, string body) - { - return Sign(apiSecret, timestamp + method + requestPath + body); - } - - public static string GenerateWebSocketSignature(string apiSecret, string timestamp, string channel, ICollection productIds) - { - if (string.IsNullOrWhiteSpace(channel)) throw new ArgumentNullException(nameof(channel), ErrorMessages.ChannelRequired); - if (productIds == null || !productIds.Any()) throw new ArgumentNullException(nameof(productIds), ErrorMessages.ProductIdRequired); - - var products = string.Join(",", productIds); - - return Sign(apiSecret, timestamp + channel + products); - } - - private static string Sign(string apiSecret, string data) - { - var apiSecretBytes = Encoding.UTF8.GetBytes(apiSecret); - var dataBytes = Encoding.UTF8.GetBytes(data); - - using (var hmac = new HMACSHA256(apiSecretBytes)) - { - var hash = hmac.ComputeHash(dataBytes); - var signature = Convert.ToHexString(hash).ToLowerInvariant(); - - return signature; - } - } - } -} diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs new file mode 100644 index 0000000..1b3d0ef --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs @@ -0,0 +1,135 @@ +using CoinbaseAdvancedTradeClient.Resources; +using Newtonsoft.Json; +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Crypto.Signers; +using Org.BouncyCastle.OpenSsl; +using Org.BouncyCastle.Security; +using System.Text; + +namespace CoinbaseAdvancedTradeClient.Authentication +{ + public static class SecretApiKeyAuthenticator + { + public static string GenerateBearerJWT(string keyName, string keySecret, string requestMethod, string requestHost, string requestPath) + { + if (string.IsNullOrWhiteSpace(keyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(keyName)); + if (string.IsNullOrWhiteSpace(keySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(keySecret)); + if (string.IsNullOrWhiteSpace(requestMethod)) throw new ArgumentException(ErrorMessages.RequestMethodRequired, nameof(requestMethod)); + if (string.IsNullOrWhiteSpace(requestHost)) throw new ArgumentException(ErrorMessages.RequestHostRequired, nameof(requestHost)); + if (string.IsNullOrWhiteSpace(requestPath)) throw new ArgumentException(ErrorMessages.RequestPathRequired, nameof(requestPath)); + + // Parse the EC private key from PEM format + ECPrivateKeyParameters privateKey; + try + { + using var stringReader = new StringReader(keySecret); + var pemReader = new PemReader(stringReader); + var keyObject = pemReader.ReadObject(); + + if (keyObject is ECPrivateKeyParameters ecKey) + { + privateKey = ecKey; + } + else if (keyObject is AsymmetricCipherKeyPair keyPair && keyPair.Private is ECPrivateKeyParameters ecPrivateKey) + { + privateKey = ecPrivateKey; + } + else + { + throw new ArgumentException(ErrorMessages.InvalidECKeyFormat, nameof(keySecret)); + } + } + catch (Exception ex) when (!(ex is ArgumentException)) + { + throw new ArgumentException(ErrorMessages.InvalidECKeyFormat, nameof(keySecret), ex); + } + + // Create the URI + string uri = $"{requestMethod.ToUpperInvariant()} {requestHost}{requestPath}"; + + // Create header + var header = new Dictionary + { + { "alg", "ES256" }, + { "typ", "JWT" }, + { "kid", keyName }, + { "nonce", GenerateNonce() } + }; + + // Create payload with timing + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var payload = new Dictionary + { + { "sub", keyName }, + { "iss", "cdp" }, + { "aud", new[] { "cdp_service" } }, + { "nbf", now }, + { "exp", now + 120 }, // 2 minutes expiration + { "uri", uri } + }; + + // Encode header and payload + string headerJson = JsonConvert.SerializeObject(header); + string payloadJson = JsonConvert.SerializeObject(payload); + + string encodedHeader = Base64UrlEncode(Encoding.UTF8.GetBytes(headerJson)); + string encodedPayload = Base64UrlEncode(Encoding.UTF8.GetBytes(payloadJson)); + + string message = $"{encodedHeader}.{encodedPayload}"; + + // Sign with ECDSA (ES256) + var signer = new ECDsaSigner(); + signer.Init(true, privateKey); + byte[] messageBytes = Encoding.UTF8.GetBytes(message); + byte[] hash = DigestUtilities.CalculateDigest("SHA-256", messageBytes); + var signature = signer.GenerateSignature(hash); + + // Convert DER signature to IEEE P1363 format (r|s) + var r = signature[0].ToByteArrayUnsigned(); + var s = signature[1].ToByteArrayUnsigned(); + + // Ensure both r and s are 32 bytes (pad with leading zeros if needed) + if (r.Length < 32) + { + var padded = new byte[32]; + Array.Copy(r, 0, padded, 32 - r.Length, r.Length); + r = padded; + } + if (s.Length < 32) + { + var padded = new byte[32]; + Array.Copy(s, 0, padded, 32 - s.Length, s.Length); + s = padded; + } + + // Combine r and s + var signatureBytes = new byte[64]; + Array.Copy(r, 0, signatureBytes, 0, 32); + Array.Copy(s, 0, signatureBytes, 32, 32); + + string encodedSignature = Base64UrlEncode(signatureBytes); + + return $"{message}.{encodedSignature}"; + } + + private static string GenerateNonce() + { + var random = new Random(); + var nonce = new char[16]; + for (int i = 0; i < 16; i++) + { + nonce[i] = (char)('0' + random.Next(10)); + } + return new string(nonce); + } + + private static string Base64UrlEncode(byte[] input) + { + return Convert.ToBase64String(input) + .Replace("+", "-") + .Replace("/", "_") + .Replace("=", ""); + } + } +} \ No newline at end of file diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs index 1bcf829..70a594d 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs @@ -6,40 +6,42 @@ using CoinbaseAdvancedTradeClient.Resources; using Flurl.Http; using Flurl.Http.Configuration; +using Microsoft.Extensions.Options; namespace CoinbaseAdvancedTradeClient { public partial class CoinbaseAdvancedTradeApiClient : FlurlClient, ICoinbaseAdvancedTradeApiClient { - private ApiClientConfig _config; + private IOptions _config; - public CoinbaseAdvancedTradeApiClient(ApiClientConfig config) + public CoinbaseAdvancedTradeApiClient(IOptions config) { if (config == null) throw new ArgumentNullException(nameof(config), ErrorMessages.ApiConfigRequired); - if (string.IsNullOrWhiteSpace(config.ApiKey)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.ApiKey)); - if (string.IsNullOrWhiteSpace(config.ApiSecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.ApiSecret)); + if (string.IsNullOrWhiteSpace(config.Value.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.Value.KeyName)); + if (string.IsNullOrWhiteSpace(config.Value.KeySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.Value.KeySecret)); _config = config; - this.Configure(ApiKeyAuthentication); + this.Configure(SecretApiKeyAuthentication); } #region Authentication - private void ApiKeyAuthentication(ClientFlurlHttpSettings settings) + private void SecretApiKeyAuthentication(ClientFlurlHttpSettings settings) { async Task SetHeaders(FlurlCall http) { - var body = http.RequestBody; var method = http.Request.Verb.Method.ToUpperInvariant(); var url = http.Request.Url.ToUri().AbsolutePath; - var timestamp = ApiKeyAuthenticator.GenerateTimestamp(); - var signature = ApiKeyAuthenticator.GenerateApiSignature(_config.ApiSecret, timestamp, method, url, body); - - http.Request - .WithHeader(RequestHeaders.AccessKey, _config.ApiKey) - .WithHeader(RequestHeaders.AccessSign, signature) - .WithHeader(RequestHeaders.AccessTimestamp, timestamp); + var host = http.Request.Url.ToUri().Host; + var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( + _config.Value.KeyName, + _config.Value.KeySecret, + method, + host, + url); + + http.Request.WithHeader(RequestHeaders.Authorization, string.Format(ErrorMessages.BearerTokenFormat, jwt)); } settings.BeforeCallAsync = SetHeaders; diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj index cc63c12..819fc66 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj @@ -12,8 +12,12 @@ + + + + diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs index 7ca4fc9..c8e1f9c 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs @@ -6,6 +6,7 @@ using CoinbaseAdvancedTradeClient.Models.WebSocket; using CoinbaseAdvancedTradeClient.Models.WebSocket.Events; using CoinbaseAdvancedTradeClient.Resources; +using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Security.Authentication; @@ -15,7 +16,7 @@ namespace CoinbaseAdvancedTradeClient { public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSocketClient, IDisposable { - private WebSocketClientConfig _config; + private IOptions _config; private WebSocket _socket; private Action _messageReceivedCallback; @@ -25,11 +26,11 @@ public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSoc public bool IsConnected => _socket?.State == WebSocketState.Open; - public CoinbaseAdvancedTradeWebSocketClient(WebSocketClientConfig config) + public CoinbaseAdvancedTradeWebSocketClient(IOptions config) { if (config == null) throw new ArgumentNullException(nameof(config), ErrorMessages.ApiConfigRequired); - if (string.IsNullOrWhiteSpace(config.ApiKey)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.ApiKey)); - if (string.IsNullOrWhiteSpace(config.ApiSecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.ApiSecret)); + if (string.IsNullOrWhiteSpace(config.Value.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.Value.KeyName)); + if (string.IsNullOrWhiteSpace(config.Value.KeySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.Value.KeySecret)); _config = config; } @@ -50,7 +51,7 @@ public async Task ConnectAsync(Action messageReceivedCallba Disconnect(); } - _socket = new WebSocket(_config.WebSocketUrl); + _socket = new WebSocket(_config.Value.WebSocketUrl); _socket.Security.EnabledSslProtocols = SslProtocols.Tls12; _socket.Opened += Socket_Opened; @@ -80,17 +81,19 @@ public void Subscribe(string channel, List productIds) if (!IsConnected) throw new InvalidOperationException(ErrorMessages.WebSocketMustBeConnected); - var timestamp = ApiKeyAuthenticator.GenerateTimestamp(); - var signature = ApiKeyAuthenticator.GenerateWebSocketSignature(_config.ApiSecret, timestamp, channel, productIds); + var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( + _config.Value.KeyName, + _config.Value.KeySecret, + "GET", + _config.Value.WebSocketUrl, + "/"); var subscriptionMessage = new SubscriptionMessage { - ApiKey = _config.ApiKey, + Type = SubscriptionType.Subscribe, Channel = channel, ProductIds = productIds, - Signature = signature, - Timestamp = timestamp, - Type = SubscriptionType.Subscribe, + Jwt = jwt }; var subscribe = JsonConvert.SerializeObject(subscriptionMessage); @@ -105,17 +108,19 @@ public void Unsubscribe(string channel, List productIds) if (!IsConnected) throw new InvalidOperationException(ErrorMessages.WebSocketMustBeConnected); - var timestamp = ApiKeyAuthenticator.GenerateTimestamp(); - var signature = ApiKeyAuthenticator.GenerateWebSocketSignature(_config.ApiSecret, timestamp, channel, productIds); + var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( + _config.Value.KeyName, + _config.Value.KeySecret, + "GET", + _config.Value.WebSocketUrl, + "/"); var unsubscribeMessage = new SubscriptionMessage { - ApiKey = _config.ApiKey, + Type = SubscriptionType.Unsubscribe, Channel = channel, ProductIds = productIds, - Signature = signature, - Timestamp = timestamp, - Type = SubscriptionType.Unsubscribe + Jwt = jwt }; var unsubscribe = JsonConvert.SerializeObject(unsubscribeMessage); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Constants/RequestHeaders.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Constants/RequestHeaders.cs index 3671601..5fbd44e 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Constants/RequestHeaders.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Constants/RequestHeaders.cs @@ -2,6 +2,7 @@ { public sealed class RequestHeaders { + public const string Authorization = "Authorization"; public const string AccessKey = "CB-ACCESS-KEY"; public const string AccessSign = "CB-ACCESS-SIGN"; public const string AccessTimestamp = "CB-ACCESS-TIMESTAMP"; diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs index d96c900..0996200 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs @@ -21,7 +21,7 @@ async Task> IAccountsEndpoint.GetListAccountsAsync(int { if (limit != null && (limit < 1 || limit > 250)) throw new ArgumentException(ErrorMessages.LimitParameterRange, nameof(limit)); - var accountsPage = await _config.ApiUrl + var accountsPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.AccountsEndpoint) .SetQueryParam(RequestParameters.Limit, limit) @@ -47,7 +47,7 @@ async Task> IAccountsEndpoint.GetAccountAsync(string accoun { if (string.IsNullOrWhiteSpace(accountId)) throw new ArgumentNullException(nameof(accountId), ErrorMessages.AccountIdRequired); - var accountsPage = await _config.ApiUrl + var accountsPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.AccountsEndpoint) .AppendPathSegment(accountId) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs index 23edaaa..5a198b7 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs @@ -28,7 +28,7 @@ async Task> IOrdersEndpoint.GetListFillsAsync(string? ord if (start.Equals(DateTimeOffset.MinValue)) start = null; if (end.Equals(DateTimeOffset.MinValue)) end = null; - var fillsPage = await _config.ApiUrl + var fillsPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersHistoricalFillsEndpoint) .SetQueryParam(RequestParameters.OrderId, orderId) @@ -64,7 +64,7 @@ async Task> IOrdersEndpoint.GetListOrdersAsync(string? p if (startDate.Equals(DateTimeOffset.MinValue)) startDate = null; if (endDate.Equals(DateTimeOffset.MinValue)) endDate = null; - var ordersPage = await _config.ApiUrl + var ordersPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersHistoricalBatchEndpoint) .SetQueryParam(RequestParameters.ProductId, productId) @@ -99,7 +99,7 @@ async Task> IOrdersEndpoint.GetOrderAsync(string orderId) { if (string.IsNullOrWhiteSpace(orderId)) throw new ArgumentNullException(nameof(orderId), ErrorMessages.OrderIdRequired); - var ordersPage = await _config.ApiUrl + var ordersPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersHistoricalEndpoint) .AppendPathSegment(orderId) @@ -135,7 +135,7 @@ async Task> IOrdersEndpoint.PostCreateOrderAsyn createOrder.ClientOrderId = Guid.NewGuid().ToString(); } - var createOrderResponse = await _config.ApiUrl + var createOrderResponse = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersEndpoint) .PostJsonAsync(createOrder, cancellationToken) @@ -161,7 +161,7 @@ async Task> IOrdersEndpoint.PostCancelOrdersAs if (cancelOrders == null) throw new ArgumentNullException(nameof(cancelOrders), ErrorMessages.OrderParametersRequired); if (cancelOrders.OrderIds == null || !cancelOrders.OrderIds.Any()) throw new ArgumentNullException(nameof(cancelOrders), ErrorMessages.OrderIdRequired); - var cancelOrderResponse = await _config.ApiUrl + var cancelOrderResponse = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersBatchCancelEndpoint) .PostJsonAsync(cancelOrders, cancellationToken) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs index 3eabec9..2040fea 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs @@ -23,7 +23,7 @@ async Task> IProductsEndpoint.GetListProductsAsync(int if (limit != null && (limit < 1 || limit > 250)) throw new ArgumentException(ErrorMessages.LimitParameterRange, nameof(limit)); if (offset != null && (offset < 0)) throw new ArgumentException(ErrorMessages.OffsetParameterRange, nameof(offset)); - var productsPage = await _config.ApiUrl + var productsPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .SetQueryParam(RequestParameters.Limit, limit) @@ -50,7 +50,7 @@ async Task> IProductsEndpoint.GetProductAsync(string produc { if (string.IsNullOrWhiteSpace(productId)) throw new ArgumentNullException(nameof(productId), ErrorMessages.ProductIdRequired); - var product = await _config.ApiUrl + var product = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .AppendPathSegment(productId) @@ -77,7 +77,7 @@ async Task> IProductsEndpoint.GetProductCandlesAsync(st if (start.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.StartDateRequired, nameof(start)); if (end.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.EndDateRequired, nameof(end)); - var candlesPage = await _config.ApiUrl + var candlesPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .AppendPathSegment(productId) @@ -107,7 +107,7 @@ async Task> IProductsEndpoint.GetMarketTradesAsync(strin if (string.IsNullOrWhiteSpace(productId)) throw new ArgumentNullException(nameof(productId), ErrorMessages.ProductIdRequired); if (limit < 1 || limit > 250) throw new ArgumentException(ErrorMessages.LimitParameterRange, nameof(limit)); - var tradesPage = await _config.ApiUrl + var tradesPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .AppendPathSegment(productId) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs index 5f0e7c6..9f486e4 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs @@ -22,7 +22,7 @@ async Task> ITransactionSummaryEndpoint.GetTrans if (startDate.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.StartDateRequired, nameof(startDate)); if (endDate.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.EndDateRequired, nameof(endDate)); - var transactionSummary = await _config.ApiUrl + var transactionSummary = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.TransactionSummaryEndpoint) .SetQueryParam(RequestParameters.StartDate, startDate.ToUniversalTime()) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..7bb240c --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,32 @@ +using CoinbaseAdvancedTradeClient.Interfaces; +using CoinbaseAdvancedTradeClient.Models.Config; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace CoinbaseAdvancedTradeClient.Extensions +{ + public static class ServiceCollectionExtensions + { + /// + /// Adds CoinbaseAdvancedTradeClient services to the service collection. + /// Automatically resolves configuration from the CoinbaseClientConfig section in appsettings.json. + /// + /// The service collection to add services to + /// The service collection for method chaining + public static IServiceCollection AddCoinbaseAdvancedTradeClient(this IServiceCollection services) + { + if (services == null) throw new ArgumentNullException(nameof(services)); + + services.AddOptions() + .Configure((config, configuration) => + { + configuration.GetSection(nameof(CoinbaseClientConfig)).Bind(config); + }); + + services.AddScoped(); + services.AddScoped(); + + return services; + } + } +} diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Interfaces/ICoinbaseAdvancedTradeWebsocketClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Interfaces/ICoinbaseAdvancedTradeWebsocketClient.cs index eb60b2a..9e3cdc0 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Interfaces/ICoinbaseAdvancedTradeWebsocketClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Interfaces/ICoinbaseAdvancedTradeWebsocketClient.cs @@ -2,7 +2,7 @@ namespace CoinbaseAdvancedTradeClient.Interfaces { - public interface ICoinbaseAdvancedTradeWebSocketClient + public interface ICoinbaseAdvancedTradeWebSocketClient : IDisposable { public bool IsConnected { get; } Task ConnectAsync(Action messageReceivedCallback, Action? openedCallback = null, Action? closedCallback = null, Action? errorCallback = null); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs deleted file mode 100644 index b38435f..0000000 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CoinbaseAdvancedTradeClient.Constants; - -namespace CoinbaseAdvancedTradeClient.Models.Config -{ - public class ApiClientConfig - { - public string ApiKey { get; set; } - public string ApiSecret { get; set; } - public string ApiUrl { get; set; } = ApiEndpoints.ApiEndpointBase; - } -} diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/CoinbaseClientConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/CoinbaseClientConfig.cs new file mode 100644 index 0000000..a9525ab --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/CoinbaseClientConfig.cs @@ -0,0 +1,12 @@ +using CoinbaseAdvancedTradeClient.Constants; + +namespace CoinbaseAdvancedTradeClient.Models.Config +{ + public class CoinbaseClientConfig + { + public string KeyName { get; set; } + public string KeySecret { get; set; } + public string ApiBaseUrl { get; set; } = ApiEndpoints.ApiEndpointBase; + public string WebSocketUrl { get; set; } = ApiEndpoints.WebSocketEndpoint; + } +} diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs deleted file mode 100644 index d65f90e..0000000 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CoinbaseAdvancedTradeClient.Constants; - -namespace CoinbaseAdvancedTradeClient.Models.Config -{ - public class WebSocketClientConfig - { - public string ApiKey { get; set; } - public string ApiSecret { get; set; } - public string WebSocketUrl { get; set; } = ApiEndpoints.WebSocketEndpoint; - } -} diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/WebSocket/SubscriptionMessage.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/WebSocket/SubscriptionMessage.cs index f2e2c61..785bb2a 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/WebSocket/SubscriptionMessage.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/WebSocket/SubscriptionMessage.cs @@ -14,13 +14,7 @@ public class SubscriptionMessage [JsonProperty("product_ids")] public List ProductIds { get; set; } - [JsonProperty("api_key")] - public string ApiKey { get; set; } - - [JsonProperty("timestamp")] - public string Timestamp { get; set; } - - [JsonProperty("signature")] - public string Signature { get; set; } + [JsonProperty("jwt")] + public string Jwt { get; set; } } } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs index 367ebf6..2682086 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs @@ -275,5 +275,59 @@ public static string WebSocketMustBeConnected { return ResourceManager.GetString("WebSocketMustBeConnected", resourceCulture); } } + + /// + /// Looks up a localized string similar to A request method is required.. + /// + public static string RequestMethodRequired { + get { + return ResourceManager.GetString("RequestMethodRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A request host is required.. + /// + public static string RequestHostRequired { + get { + return ResourceManager.GetString("RequestHostRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A request path is required.. + /// + public static string RequestPathRequired { + get { + return ResourceManager.GetString("RequestPathRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid base64 key format.. + /// + public static string InvalidBase64KeyFormat { + get { + return ResourceManager.GetString("InvalidBase64KeyFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid EC private key format. Expected PEM format.. + /// + public static string InvalidECKeyFormat { + get { + return ResourceManager.GetString("InvalidECKeyFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Bearer {0}. + /// + public static string BearerTokenFormat { + get { + return ResourceManager.GetString("BearerTokenFormat", resourceCulture); + } + } } } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx index ff49964..ca074b7 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx @@ -189,4 +189,22 @@ Web Socket must be connected. + + A request method is required. + + + A request host is required. + + + A request path is required. + + + Invalid base64 key format. + + + Invalid EC private key format. Expected PEM format. + + + Bearer {0} + \ No newline at end of file diff --git a/README.md b/README.md index aacd2ec..ff9eac6 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ We are actively working toward a 1.0.0 stable release. Check the [CHANGELOG.md]( - **Complete API Coverage**: Support for all Coinbase Advanced Trade endpoints including accounts, orders, products, and transaction summaries - **WebSocket Support**: Real-time market data streaming with support for multiple channels -- **Authentication**: Secure API key-based authentication with HMAC signature generation +- **Authentication**: Secure JWT Bearer token authentication with ECDSA ES256 signatures - **Type Safety**: Strongly-typed models for all API requests and responses - **Testing**: Comprehensive unit test suite with 142+ passing tests - **Modern .NET**: Built for .NET 9.0 with nullable reference types and implicit usings @@ -41,46 +41,74 @@ Or add to your `.csproj` file: ## Quick Start -### API Client Setup +### Configuration -```csharp -using CoinbaseAdvancedTradeClient; -using CoinbaseAdvancedTradeClient.Models.Config; +⚠️ **Security Warning**: Never commit your API key names or secrets to version control. Use secure configuration methods: +- User secrets for development: `dotnet user-secrets set "CoinbaseClientConfig:KeyName" "your-key-name"` +- Azure Key Vault or AWS Secrets Manager for production +- Environment variables with proper access controls +- Kubernetes secrets or similar container orchestration secrets + +Add your Coinbase Cloud API credentials to `appsettings.json`: -var config = new ApiClientConfig +```json { - ApiKey = "your-api-key", - ApiSecret = "your-api-secret" -}; + "CoinbaseClientConfig": { + "KeyName": "your-key-name", + "KeySecret": "-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----", + "ApiBaseUrl": "https://api.coinbase.com", // Optional, defaults to production + "WebSocketUrl": "wss://advanced-trade-ws.coinbase.com" // Optional, defaults to production + } +} +``` + +### API Client Setup -using var client = new CoinbaseAdvancedTradeApiClient(config); +```csharp +using CoinbaseAdvancedTradeClient.Extensions; -// Get account information -var accounts = await client.GetAccountsAsync(); +// Register during startup +builder.Services.AddCoinbaseAdvancedTradeClient(); -// Place a market order -var orderResponse = await client.CreateOrderAsync(new CreateOrderParameters +// Use in your services +public class TradingService { - // Order configuration here -}); + private readonly ICoinbaseAdvancedTradeApiClient _client; + + public TradingService(ICoinbaseAdvancedTradeApiClient client) + { + _client = client; + } + + public async Task> GetAccountsAsync() + { + return await _client.GetAccountsAsync(); + } +} ``` ### WebSocket Client Setup ```csharp -using CoinbaseAdvancedTradeClient; -using CoinbaseAdvancedTradeClient.Models.Config; - -var config = new WebsocketClientConfig +// WebSocket client is automatically registered with the API client +public class MarketDataService { - ApiKey = "your-api-key", - ApiSecret = "your-api-secret" -}; - -using var wsClient = new CoinbaseAdvancedTradeWebsocketClient(config); - -// Subscribe to market data -await wsClient.SubscribeAsync("BTC-USD", SubscriptionType.Ticker); + private readonly ICoinbaseAdvancedTradeWebSocketClient _wsClient; + + public MarketDataService(ICoinbaseAdvancedTradeWebSocketClient wsClient) + { + _wsClient = wsClient; + } + + public async Task SubscribeToTicker(string productId) + { + // Connect to WebSocket first + await _wsClient.ConnectAsync(); + + // Then subscribe to market data + await _wsClient.SubscribeAsync(productId, SubscriptionType.Ticker); + } +} ``` ## API Reference