diff --git a/WindowsAppRuntime.sln b/WindowsAppRuntime.sln index c1cf5c074e..0910c03970 100644 --- a/WindowsAppRuntime.sln +++ b/WindowsAppRuntime.sln @@ -246,17 +246,6 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Framework.Widgets", "test\D EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicDependencyLifetimeManagerShadow", "dev\DynamicDependency\DynamicDependencyLifetimeManagerShadow\DynamicDependencyLifetimeManagerShadow.vcxproj", "{6539E9E1-BF36-40E5-86BC-070E99DB7B7B}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ToastNotificationTests", "test\ToastNotificationTests\ToastNotificationTests.vcxproj", "{E977B1BD-00DC-4085-A105-E0A18E0183D7}" - ProjectSection(ProjectDependencies) = postProject - {4B30C685-8490-440F-9879-A75D45DAA361} = {4B30C685-8490-440F-9879-A75D45DAA361} - {9C1A6C58-52D6-4514-9120-5C339C5DF4BE} = {9C1A6C58-52D6-4514-9120-5C339C5DF4BE} - {A7391725-4EF5-438F-8DE1-645423E46955} = {A7391725-4EF5-438F-8DE1-645423E46955} - {B71E818A-882E-456A-87E5-4DE4A6602B99} = {B71E818A-882E-456A-87E5-4DE4A6602B99} - {B73AD907-6164-4294-88FB-F3C9C10DA1F1} = {B73AD907-6164-4294-88FB-F3C9C10DA1F1} - {D6A64926-4988-4C64-A5A8-2C14B1388696} = {D6A64926-4988-4C64-A5A8-2C14B1388696} - {F76B776E-86F5-48C5-8FC7-D2795ECC9746} = {F76B776E-86F5-48C5-8FC7-D2795ECC9746} - EndProjectSection -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ToastNotificationsTestApp", "test\TestApps\ToastNotificationsTestApp\ToastNotificationsTestApp.vcxproj", "{4B30C685-8490-440F-9879-A75D45DAA361}" ProjectSection(ProjectDependencies) = postProject {9C1A6C58-52D6-4514-9120-5C339C5DF4BE} = {9C1A6C58-52D6-4514-9120-5C339C5DF4BE} @@ -406,6 +395,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test_DeploymentManagerAutoI EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Windows.AppNotifications.Builder.Projection", "dev\Projections\CS\Microsoft.Windows.AppNotifications.Builder.Projection\Microsoft.Windows.AppNotifications.Builder.Projection.csproj", "{50BF3E96-3050-4053-B012-BF6993483DA5}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OAuth", "OAuth", "{4A3ACD67-5C57-474D-87BF-675676D7451A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OAuth", "dev\OAuth\OAuth.vcxitems", "{3E7FD510-8B66-40E7-A80B-780CB8972F83}" +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NotificationTests", "NotificationTests", "{1FDC307C-2DB7-4B40-8F18-F1057E9E0969}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LRPTests", "test\LRPTests\LRPTests.vcxproj", "{978B013F-9B68-4B3E-8DA4-6F3BE4EB22B4}" @@ -422,6 +415,17 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "VersionInfoTests", "test\Ve {5E2CC9D5-7C05-41D9-9DB5-EC5DF64BA1DC} = {5E2CC9D5-7C05-41D9-9DB5-EC5DF64BA1DC} EndProjectSection EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OAuthTests", "test\OAuthTests\OAuthTests.vcxproj", "{21651459-648E-475C-91DB-2BDE359C75A4}" + ProjectSection(ProjectDependencies) = postProject + {C4454D2C-8024-41B8-BAC1-FC2E544C810F} = {C4454D2C-8024-41B8-BAC1-FC2E544C810F} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OAuthTestApp", "test\TestApps\OAuthTestApp\OAuthTestApp.vcxproj", "{077BDBFD-C1AA-49C8-BD62-7C14221C45F2}" +EndProject +Project("{C7167F0D-BC9F-4E6E-AFE1-012C56B48DB5}") = "OAuthTestAppPackage", "test\TestApps\OAuthTestAppPackage\OAuthTestAppPackage.wapproj", "{C4454D2C-8024-41B8-BAC1-FC2E544C810F}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Windows.Security.Authentication.OAuth.Projection", "dev\Projections\CS\Microsoft.Windows.Security.Authentication.OAuth\Microsoft.Windows.Security.Authentication.OAuth.Projection.csproj", "{E7283533-E1C6-4843-B988-13D95BAB2B9A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1570,6 +1574,78 @@ Global {442FB943-1197-48FE-B3B6-8C1BCA1E81E4}.Release|x64.Build.0 = Release|x64 {442FB943-1197-48FE-B3B6-8C1BCA1E81E4}.Release|x86.ActiveCfg = Release|Win32 {442FB943-1197-48FE-B3B6-8C1BCA1E81E4}.Release|x86.Build.0 = Release|Win32 + {21651459-648E-475C-91DB-2BDE359C75A4}.Debug|Any CPU.ActiveCfg = Debug|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Debug|Any CPU.Build.0 = Debug|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Debug|ARM64.ActiveCfg = Debug|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Debug|ARM64.Build.0 = Debug|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Debug|x64.ActiveCfg = Debug|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Debug|x64.Build.0 = Debug|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Debug|x86.ActiveCfg = Debug|Win32 + {21651459-648E-475C-91DB-2BDE359C75A4}.Debug|x86.Build.0 = Debug|Win32 + {21651459-648E-475C-91DB-2BDE359C75A4}.Release|Any CPU.ActiveCfg = Release|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Release|Any CPU.Build.0 = Release|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Release|ARM64.ActiveCfg = Release|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Release|ARM64.Build.0 = Release|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Release|x64.ActiveCfg = Release|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Release|x64.Build.0 = Release|x64 + {21651459-648E-475C-91DB-2BDE359C75A4}.Release|x86.ActiveCfg = Release|Win32 + {21651459-648E-475C-91DB-2BDE359C75A4}.Release|x86.Build.0 = Release|Win32 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Debug|Any CPU.ActiveCfg = Debug|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Debug|Any CPU.Build.0 = Debug|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Debug|ARM64.ActiveCfg = Debug|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Debug|ARM64.Build.0 = Debug|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Debug|x64.ActiveCfg = Debug|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Debug|x64.Build.0 = Debug|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Debug|x86.ActiveCfg = Debug|Win32 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Debug|x86.Build.0 = Debug|Win32 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Release|Any CPU.ActiveCfg = Release|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Release|Any CPU.Build.0 = Release|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Release|ARM64.ActiveCfg = Release|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Release|ARM64.Build.0 = Release|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Release|x64.ActiveCfg = Release|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Release|x64.Build.0 = Release|x64 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Release|x86.ActiveCfg = Release|Win32 + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2}.Release|x86.Build.0 = Release|Win32 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|ARM64.Build.0 = Debug|ARM64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|x64.ActiveCfg = Debug|x64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|x64.Build.0 = Debug|x64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|x64.Deploy.0 = Debug|x64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|x86.ActiveCfg = Debug|x86 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|x86.Build.0 = Debug|x86 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Debug|x86.Deploy.0 = Debug|x86 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|Any CPU.Build.0 = Release|Any CPU + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|Any CPU.Deploy.0 = Release|Any CPU + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|ARM64.ActiveCfg = Release|ARM64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|ARM64.Build.0 = Release|ARM64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|ARM64.Deploy.0 = Release|ARM64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|x64.ActiveCfg = Release|x64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|x64.Build.0 = Release|x64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|x64.Deploy.0 = Release|x64 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|x86.ActiveCfg = Release|x86 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|x86.Build.0 = Release|x86 + {C4454D2C-8024-41B8-BAC1-FC2E544C810F}.Release|x86.Deploy.0 = Release|x86 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Debug|Any CPU.ActiveCfg = Debug|x64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Debug|Any CPU.Build.0 = Debug|x64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Debug|ARM64.ActiveCfg = Debug|arm64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Debug|ARM64.Build.0 = Debug|arm64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Debug|x64.ActiveCfg = Debug|x64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Debug|x64.Build.0 = Debug|x64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Debug|x86.ActiveCfg = Debug|x86 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Debug|x86.Build.0 = Debug|x86 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Release|Any CPU.ActiveCfg = Release|x64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Release|Any CPU.Build.0 = Release|x64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Release|ARM64.ActiveCfg = Release|arm64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Release|ARM64.Build.0 = Release|arm64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Release|x64.ActiveCfg = Release|x64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Release|x64.Build.0 = Release|x64 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Release|x86.ActiveCfg = Release|x86 + {E7283533-E1C6-4843-B988-13D95BAB2B9A}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1699,11 +1775,17 @@ Global {676BA502-4220-465A-A9ED-ED22CDE4A24B} = {3A37083C-AA67-461E-BA78-0E0A65FE0C22} {5A4FBF6D-04A2-4061-B11F-1A0E64129610} = {3A37083C-AA67-461E-BA78-0E0A65FE0C22} {50BF3E96-3050-4053-B012-BF6993483DA5} = {716C26A0-E6B0-4981-8412-D14A4D410531} + {4A3ACD67-5C57-474D-87BF-675676D7451A} = {448ED2E5-0B37-4D97-9E6B-8C10A507976A} + {3E7FD510-8B66-40E7-A80B-780CB8972F83} = {4A3ACD67-5C57-474D-87BF-675676D7451A} {1FDC307C-2DB7-4B40-8F18-F1057E9E0969} = {8630F7AA-2969-4DC9-8700-9B468C1DC21D} {978B013F-9B68-4B3E-8DA4-6F3BE4EB22B4} = {1FDC307C-2DB7-4B40-8F18-F1057E9E0969} {2A2D1131-273C-4E17-BCD3-8812170A4B95} = {448ED2E5-0B37-4D97-9E6B-8C10A507976A} {E3EDEC7F-A24E-4766-BB1D-6BDFBA157C51} = {2A2D1131-273C-4E17-BCD3-8812170A4B95} {442FB943-1197-48FE-B3B6-8C1BCA1E81E4} = {8630F7AA-2969-4DC9-8700-9B468C1DC21D} + {21651459-648E-475C-91DB-2BDE359C75A4} = {8630F7AA-2969-4DC9-8700-9B468C1DC21D} + {077BDBFD-C1AA-49C8-BD62-7C14221C45F2} = {AC5FFC80-92FE-4933-BED2-EC5519AC4440} + {C4454D2C-8024-41B8-BAC1-FC2E544C810F} = {AC5FFC80-92FE-4933-BED2-EC5519AC4440} + {E7283533-E1C6-4843-B988-13D95BAB2B9A} = {716C26A0-E6B0-4981-8412-D14A4D410531} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4B3D7591-CFEC-4762-9A07-ABE99938FB77} @@ -1711,7 +1793,9 @@ Global GlobalSection(SharedMSBuildProjectFiles) = preSolution test\inc\inc.vcxitems*{08bc78e0-63c6-49a7-81b3-6afc3deac4de}*SharedItemsImports = 4 dev\PushNotifications\PushNotifications.vcxitems*{103c0c23-7ba8-4d44-a63c-83488e2e3a81}*SharedItemsImports = 9 + test\inc\inc.vcxitems*{21651459-648e-475c-91db-2bde359c75a4}*SharedItemsImports = 4 dev\EnvironmentManager\API\Microsoft.Process.Environment.vcxitems*{2f3fad1b-d3df-4866-a3a3-c2c777d55638}*SharedItemsImports = 9 + dev\OAuth\OAuth.vcxitems*{3e7fd510-8b66-40e7-a80b-780cb8972f83}*SharedItemsImports = 9 test\inc\inc.vcxitems*{412d023e-8635-4ad2-a0ea-e19e08d36915}*SharedItemsImports = 4 test\inc\inc.vcxitems*{4b30c685-8490-440f-9879-a75d45daa361}*SharedItemsImports = 4 dev\UndockedRegFreeWinRT\UndockedRegFreeWinRT.vcxitems*{56371ca6-144b-4989-a4e9-391ad4fa7651}*SharedItemsImports = 9 diff --git a/build/AzurePipelinesTemplates/WindowsAppSDK-SetupBuildEnvironment-Steps.yml b/build/AzurePipelinesTemplates/WindowsAppSDK-SetupBuildEnvironment-Steps.yml index 85e9686094..5610d8602b 100644 --- a/build/AzurePipelinesTemplates/WindowsAppSDK-SetupBuildEnvironment-Steps.yml +++ b/build/AzurePipelinesTemplates/WindowsAppSDK-SetupBuildEnvironment-Steps.yml @@ -70,6 +70,14 @@ steps: arguments: -Path $(Build.SourcesDirectory)\dev\common\TerminalVelocityFeatures-EnvironmentManager.xml -Channel $(channel) -Language C++ -Namespace Microsoft.Windows.System -Output $(Build.SourcesDirectory)\dev\common\TerminalVelocityFeatures-EnvironmentManager.h workingDirectory: '$(Build.SourcesDirectory)' +- task: powershell@2 + displayName: 'Create OAuth TerminalVelocity features' + inputs: + targetType: filePath + filePath: tools\TerminalVelocity\Generate-TerminalVelocityFeatures.ps1 + arguments: -Path $(Build.SourcesDirectory)\dev\common\TerminalVelocityFeatures-OAuth.xml -Channel ${{ parameters.channel }} -Language C++ -Namespace Microsoft.Windows.Security.Authentication.OAuth -Output $(Build.SourcesDirectory)\dev\common\TerminalVelocityFeatures-OAuth.h + workingDirectory: '$(Build.SourcesDirectory)' + - task: powershell@2 name: UpdateTraceloggingConfig inputs: diff --git a/build/CopyFilesToStagingDir.ps1 b/build/CopyFilesToStagingDir.ps1 index 73d84a35b4..ec091ce75e 100644 --- a/build/CopyFilesToStagingDir.ps1 +++ b/build/CopyFilesToStagingDir.ps1 @@ -48,6 +48,7 @@ PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windo PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windows.System.winmd $FullPublishDir\Microsoft.WindowsAppRuntime\ PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windows.System.Power.winmd $FullPublishDir\Microsoft.WindowsAppRuntime\ PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windows.Security.AccessControl.winmd $FullPublishDir\Microsoft.WindowsAppRuntime\ +PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windows.Security.Authentication.OAuth.winmd $FullPublishDir\Microsoft.WindowsAppRuntime\ PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\MsixDynamicDependency.h $FullPublishDir\Microsoft.WindowsAppRuntime\ PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\wil_msixdynamicdependency.h $FullPublishDir\Microsoft.WindowsAppRuntime\ PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\Security.AccessControl.h $FullPublishDir\Microsoft.WindowsAppRuntime\ @@ -116,6 +117,8 @@ PublishFile $FullBuildOutput\Microsoft.Windows.System.Power.Projection\Microsoft PublishFile $FullBuildOutput\Microsoft.Windows.System.Power.Projection\Microsoft.Windows.System.Power.Projection.pdb $NugetDir\lib\net6.0-windows10.0.17763.0 PublishFile $FullBuildOutput\Microsoft.Windows.Security.AccessControl.Projection\Microsoft.Windows.Security.AccessControl.Projection.dll $NugetDir\lib\net6.0-windows10.0.17763.0 PublishFile $FullBuildOutput\Microsoft.Windows.Security.AccessControl.Projection\Microsoft.Windows.Security.AccessControl.Projection.pdb $NugetDir\lib\net6.0-windows10.0.17763.0 +PublishFile $FullBuildOutput\Microsoft.Windows.Security.Authentication.OAuth.Projection\Microsoft.Windows.Security.Authentication.OAuth.Projection.dll $NugetDir\lib\net6.0-windows10.0.17763.0 +PublishFile $FullBuildOutput\Microsoft.Windows.Security.Authentication.OAuth.Projection\Microsoft.Windows.Security.Authentication.OAuth.Projection.pdb $NugetDir\lib\net6.0-windows10.0.17763.0 # # Dynamic Dependency build overrides @@ -183,6 +186,7 @@ PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windo PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windows.System.winmd $NugetDir\lib\uap10.0 PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windows.System.Power.winmd $NugetDir\lib\uap10.0 PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windows.Security.AccessControl.winmd $NugetDir\lib\uap10.0 +PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windows.Security.Authentication.OAuth.winmd $NugetDir\lib\uap10.0 # # Bootstrap Auto-Initializer Files PublishFile $FullBuildOutput\WindowsAppRuntime_BootstrapDLL\MddBootstrapAutoInitializer.cpp $NugetDir\include diff --git a/build/NuSpecs/AppxManifest.xml b/build/NuSpecs/AppxManifest.xml index 65e3d8f7e3..10a791889d 100644 --- a/build/NuSpecs/AppxManifest.xml +++ b/build/NuSpecs/AppxManifest.xml @@ -58,6 +58,12 @@ + + + + + + diff --git a/build/NuSpecs/WindowsAppSDK-Nuget-Native.WinRt.props b/build/NuSpecs/WindowsAppSDK-Nuget-Native.WinRt.props index 9b721a7abc..6b55c4af5b 100644 --- a/build/NuSpecs/WindowsAppSDK-Nuget-Native.WinRt.props +++ b/build/NuSpecs/WindowsAppSDK-Nuget-Native.WinRt.props @@ -36,7 +36,7 @@ true - $(MSBuildThisFileDirectory)..\..\lib\uap10.0\Microsoft.Windows.System.winmd $(MSBuildThisFileDirectory)..\..\runtimes\win10-$(_WindowsAppSDKFoundationPlatform)\native\Microsoft.WindowsAppRuntime.dll @@ -48,6 +48,12 @@ $(MSBuildThisFileDirectory)..\..\runtimes\win10-$(_WindowsAppSDKFoundationPlatform)\native\Microsoft.WindowsAppRuntime.dll true + + $(MSBuildThisFileDirectory)..\..\lib\uap10.0\Microsoft.Windows.Security.Authentication.OAuth.winmd + $(MSBuildThisFileDirectory)..\..\runtimes\win10-$(_WindowsAppSDKFoundationPlatform)\native\Microsoft.WindowsAppRuntime.dll + true + diff --git a/build/NuSpecs/WindowsAppSDK-Nuget-Native.targets b/build/NuSpecs/WindowsAppSDK-Nuget-Native.targets index cc8c36d467..e963e26a04 100644 --- a/build/NuSpecs/WindowsAppSDK-Nuget-Native.targets +++ b/build/NuSpecs/WindowsAppSDK-Nuget-Native.targets @@ -68,6 +68,14 @@ + + + false + Microsoft.WindowsAppRuntime.dll + + + diff --git a/dev/Common/TerminalVelocityFeatures-OAuth.h b/dev/Common/TerminalVelocityFeatures-OAuth.h new file mode 100644 index 0000000000..21b805d2b3 --- /dev/null +++ b/dev/Common/TerminalVelocityFeatures-OAuth.h @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +// THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT IT + +// INPUT FILE: dev\common\TerminalVelocityFeatures-OAuth.xml +// OPTIONS: -Channel Experimental -Language C++ -Namespace Microsoft.Windows.Security.Authentication.OAuth -Path dev\common\TerminalVelocityFeatures-OAuth.xml -Output dev\common\TerminalVelocityFeatures-OAuth.h + +#if defined(__midlrt) +namespace features +{ + feature_name Feature_OAuth = { DisabledByDefault, FALSE }; +} +#endif // defined(__midlrt) + +// Feature constants +#define WINDOWSAPPRUNTIME_MICROSOFT_WINDOWS_SECURITY_AUTHENTICATION_OAUTH_FEATURE_OAUTH_ENABLED 1 + +#if defined(__cplusplus) + +namespace Microsoft::Windows::Security::Authentication::OAuth +{ + +__pragma(detect_mismatch("ODR_violation_WINDOWSAPPRUNTIME_MICROSOFT_WINDOWS_SECURITY_AUTHENTICATION_OAUTH_FEATURE_OAUTH_ENABLED_mismatch", "AlwaysEnabled")) +struct Feature_OAuth +{ + static constexpr bool IsEnabled() { return WINDOWSAPPRUNTIME_MICROSOFT_WINDOWS_SECURITY_AUTHENTICATION_OAUTH_FEATURE_OAUTH_ENABLED == 1; } +}; + +} // namespace Microsoft.Windows.Security.Authentication.OAuth + +#endif // defined(__cplusplus) diff --git a/dev/Common/TerminalVelocityFeatures-OAuth.xml b/dev/Common/TerminalVelocityFeatures-OAuth.xml new file mode 100644 index 0000000000..f4bc3578cc --- /dev/null +++ b/dev/Common/TerminalVelocityFeatures-OAuth.xml @@ -0,0 +1,20 @@ + + + + + + + + + + Feature_OAuth + OAuth for the WindowsAppRuntime + AlwaysEnabled + + Preview + Stable + + + \ No newline at end of file diff --git a/dev/OAuth/AuthFailure.cpp b/dev/OAuth/AuthFailure.cpp new file mode 100644 index 0000000000..293da5993f --- /dev/null +++ b/dev/OAuth/AuthFailure.cpp @@ -0,0 +1,81 @@ +#include +#include "common.h" + +#include "AuthFailure.h" + +#include + +using namespace std::literals; +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + AuthFailure::AuthFailure(const Uri& responseUri) + { + std::map additionalParams; + + auto parseComponents = [&](const winrt::hstring& str) { + if (str.empty()) + { + return; // Avoid unnecessary construction/activation + } + + for (auto&& entry : WwwFormUrlDecoder(str)) + { + auto name = entry.Name(); + if (name == L"error"sv) + { + m_error = entry.Value(); + } + else if (name == L"error_description"sv) + { + m_errorDescription = entry.Value(); + } + else if (name == L"error_uri"sv) + { + m_errorUri = Uri(entry.Value()); + } + else if (name == L"state"sv) + { + m_state = entry.Value(); + } + else + { + additionalParams.emplace(std::move(name), entry.Value()); + } + } + }; + + parseComponents(responseUri.Query()); + parseComponents(fragment_component(responseUri)); + + m_additionalParams = winrt::single_threaded_map(std::move(additionalParams)).GetView(); + } + + winrt::hstring AuthFailure::Error() + { + return m_error; + } + + winrt::hstring AuthFailure::ErrorDescription() + { + return m_errorDescription; + } + + Uri AuthFailure::ErrorUri() + { + return m_errorUri; + } + + winrt::hstring AuthFailure::State() + { + return m_state; + } + + IMapView AuthFailure::AdditionalParams() + { + return m_additionalParams; + } +} diff --git a/dev/OAuth/AuthFailure.h b/dev/OAuth/AuthFailure.h new file mode 100644 index 0000000000..e78fcf0cb1 --- /dev/null +++ b/dev/OAuth/AuthFailure.h @@ -0,0 +1,23 @@ +#pragma once +#include + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct AuthFailure : AuthFailureT + { + AuthFailure(const foundation::Uri& responseUri); + + winrt::hstring Error(); + winrt::hstring ErrorDescription(); + foundation::Uri ErrorUri(); + winrt::hstring State(); + collections::IMapView AdditionalParams(); + + private: + winrt::hstring m_error; + winrt::hstring m_errorDescription; + foundation::Uri m_errorUri{ nullptr }; + winrt::hstring m_state; + collections::IMapView m_additionalParams; + }; +} diff --git a/dev/OAuth/AuthManager.cpp b/dev/OAuth/AuthManager.cpp new file mode 100644 index 0000000000..8160d5f590 --- /dev/null +++ b/dev/OAuth/AuthManager.cpp @@ -0,0 +1,325 @@ +#include +#include "common.h" + +#include "AuthManager.h" +#include "AuthRequestParams.h" +#include "TokenFailure.h" +#include "TokenRequestParams.h" +#include "TokenRequestResult.h" +#include "TokenResponse.h" + +#include + +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Data::Json; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; +using namespace winrt::Windows::Web::Http; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::factory_implementation +{ + IAsyncOperation AuthManager::InitiateAuthRequestAsync(const Uri& authEndpoint, + const oauth::AuthRequestParams& params) + { + THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::Security::Authentication::OAuth::Feature_OAuth::IsEnabled()); + + auto paramsImpl = winrt::get_self(params); + auto asyncOp = winrt::make_self(paramsImpl); + + { + std::lock_guard guard{ m_mutex }; + m_pendingAuthRequests.push_back(AuthRequestState{ params.State(), asyncOp }); + } + + try + { + // Pipe server has been successfully set up. Initiate the launch + auto url = paramsImpl->create_url(authEndpoint); + + auto launchResult = ::ShellExecuteW(nullptr, L"open", url.c_str(), nullptr, nullptr, SW_SHOWDEFAULT); + if (auto code = reinterpret_cast(launchResult); code < 32) + { + throw winrt::hresult_error(HRESULT_FROM_WIN32(::GetLastError()), L"Failed to launch browser"); + } + } + catch (...) + { + try_remove(asyncOp.get()); + throw; + } + + return *asyncOp; + } + + bool AuthManager::CompleteAuthRequest(const Uri& responseUri) + { + THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::Security::Authentication::OAuth::Feature_OAuth::IsEnabled()); + + // We need to extract the state in order to find the original request + winrt::hstring state; + auto tryFindState = [&](const winrt::hstring& str) + { + if (str.empty()) + { + return; // Avoid unnecessary construction/activation + } + + for (auto&& entry : WwwFormUrlDecoder(str)) + { + if (entry.Name() == L"state") + { + state = entry.Value(); + break; + } + } + }; + + tryFindState(responseUri.Query()); + if (state.empty()) + { + tryFindState(fragment_component(responseUri)); + + // Don't throw an error. It could be the case that the application just blindly calls this function first + if (state.empty()) + { + return false; + } + } + + // First check in our local pending list + if (try_complete_local(state, responseUri)) + { + return true; + } + + // Not found locally; we need to check to see if the request originated in another process + auto pipeName = request_pipe_name(state); + + // We encrypt the URI using the state as the key. This accomplishes a couple things: (1) it helps protect the + // server from another process attaching and sending bogus data, and (2) it helps protect against sending the + // authorization grant information to the wrong client. Both of these points of course become moot if the bad + // party intercepts the state value, and because the state value is somewhat exposed through the browser launch/ + // URL, these steps are intended more as a defense in depth. Other features such as PKCE should be used to + // ensure that codes/tokens are safe in the event that the state is compromised. + auto encryptedUri = encrypt(responseUri.RawUri(), state); + + // When we create the named pipe, we only allow a single pipe instance. This should be fine under normal + // circumstances, however it might be the case that another process attaches to the pipe. This may be + // innocuous - e.g. the browser did multiple redirects - or it could be a bad actor - e.g. a process sending + // random garbage to any pipe it can open or another process specifically targeting oauth. Therefore we make + // multiple attempts to connect to the pipe + HANDLE pipe = INVALID_HANDLE_VALUE; + while (true) // TODO: Bound this? Need to remember to return false if we do + { + pipe = ::CreateFileW(pipeName.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); + if (pipe != INVALID_HANDLE_VALUE) break; + + if (auto err = ::GetLastError(); err != ERROR_PIPE_BUSY) + { + // The pipe no longer exist; e.g. flow already completed, client cancelled, etc. + return false; + } + + if (!::WaitNamedPipeW(pipeName.c_str(), 100)) + { + // 100ms should be enough time to wrap up any business. So either the system is bogged down (perhaps too + // many requests to open the pipe), the pipe was closed, or the pipe was closed and opened by another + // process who isn't being responsive. + return false; + } + } + + ULONG serverPid = 0; + if (::GetNamedPipeServerProcessId(pipe, &serverPid)) + { + ::AllowSetForegroundWindow(serverPid); + + // TODO: We can also possibly verify other things about the server process (exe path, etc.) + } + + DWORD bytesToWrite = encryptedUri.Length(); + DWORD bytesWritten = 0; + if (!::WriteFile(pipe, encryptedUri.data(), bytesToWrite, &bytesWritten, nullptr) || + (bytesWritten != bytesToWrite)) + { + // TODO: Actual error? This could be because the server timed us out... + ::CloseHandle(pipe); + return false; + } + + // The client should have the URI and the operation should be considered handled + ::CloseHandle(pipe); + return true; + } + + IAsyncOperation AuthManager::RequestTokenAsync(Uri tokenEndpoint, + oauth::TokenRequestParams params) + { + return RequestTokenAsync(std::move(tokenEndpoint), std::move(params), nullptr); + } + + IAsyncOperation AuthManager::RequestTokenAsync(Uri tokenEndpoint, + oauth::TokenRequestParams params, oauth::ClientAuthentication clientAuth) + { + THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::Security::Authentication::OAuth::Feature_OAuth::IsEnabled()); + + auto paramsImpl = winrt::get_self(params); + paramsImpl->finalize(); + + HttpResponseMessage response{ nullptr }; + winrt::hstring responseString; + try + { + HttpClient httpClient; + HttpFormUrlEncodedContent content(winrt::single_threaded_map(paramsImpl->params())); + HttpRequestMessage request(HttpMethod::Post(), tokenEndpoint); + request.Content(HttpFormUrlEncodedContent(winrt::single_threaded_map(paramsImpl->params()))); + + auto headers = request.Headers(); + headers.Accept().ParseAdd(L"application/json"); + + if (clientAuth) + { + if (auto auth = clientAuth.Authorization()) + { + headers.Authorization(auth); + } + + if (auto proxyAuth = clientAuth.ProxyAuthorization()) + { + headers.ProxyAuthorization(proxyAuth); + } + + if (auto map = clientAuth.AdditionalHeaders()) + { + for (auto&& pair : map) + { + if (!headers.TryAppendWithoutValidation(pair.Key(), pair.Value())) + { + // TODO? Why might this fail? Throw? + } + } + } + } + + auto cancellation = co_await winrt::get_cancellation_token(); + cancellation.enable_propagation(); + + response = co_await httpClient.SendRequestAsync(request); + // TODO: Check status code? + if (!response.IsSuccessStatusCode()) + { + auto status = response.StatusCode(); + HRESULT hr = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_HTTP, static_cast(status)); + co_return implementation::TokenRequestResult::MakeFailure(std::move(response), + TokenFailureKind::HttpFailure, hr); + } + + auto responseContentType = response.Content().Headers().ContentType().MediaType(); + if (responseContentType != L"application/json") + { + co_return implementation::TokenRequestResult::MakeFailure(std::move(response), + TokenFailureKind::InvalidResponse, WEB_E_UNSUPPORTED_FORMAT); + } + + responseString = co_await response.Content().ReadAsStringAsync(); + } + catch (...) + { + co_return implementation::TokenRequestResult::MakeFailure(std::move(response), + TokenFailureKind::HttpFailure, winrt::to_hresult()); + } + + JsonObject jsonObject{ nullptr }; + if (!JsonObject::TryParse(responseString, jsonObject)) + { + co_return implementation::TokenRequestResult::MakeFailure(std::move(response), + TokenFailureKind::InvalidResponse, WEB_E_INVALID_JSON_STRING); + } + else + { + try + { + // Determine if it's a success or error response based on the presence of 'error' + if (jsonObject.HasKey(L"error")) + { + auto failure = winrt::make(jsonObject); + co_return winrt::make(std::move(response), nullptr, + std::move(failure)); + } + else + { + auto success = winrt::make(jsonObject); + co_return winrt::make(std::move(response), std::move(success), + nullptr); + } + } + catch (...) + { + co_return implementation::TokenRequestResult::MakeFailure(std::move(response), + TokenFailureKind::InvalidResponse, winrt::to_hresult()); + } + } + } + + bool AuthManager::try_complete_local(const winrt::hstring& state, const foundation::Uri& responseUri) + { + AuthRequestState requestState; + { + std::lock_guard guard{ m_mutex }; + auto itr = std::find_if(m_pendingAuthRequests.begin(), m_pendingAuthRequests.end(), + [&](auto&& entry) { return entry.state == state; }); + + if (itr != m_pendingAuthRequests.end()) + { + requestState = std::move(*itr); + *itr = std::move(m_pendingAuthRequests.back()); + m_pendingAuthRequests.pop_back(); + } + } + + if (requestState.async_op) + { + // Found locally + requestState.async_op->complete(responseUri); + return true; + } + + return false; + } + + void AuthManager::cancel(AuthRequestAsyncOperation* op) + { + auto requestState = try_remove(op); + if (requestState.async_op) + { + requestState.async_op->cancel(); + } + } + + void AuthManager::error(AuthRequestAsyncOperation* op, winrt::hresult hr) + { + auto requestState = try_remove(op); + if (requestState.async_op) + { + requestState.async_op->error(hr); + } + } + + AuthRequestState AuthManager::try_remove(AuthRequestAsyncOperation* op) + { + std::lock_guard guard{ m_mutex }; + auto itr = std::find_if(m_pendingAuthRequests.begin(), m_pendingAuthRequests.end(), + [&](auto&& entry) { return entry.async_op.get() == op; }); + + AuthRequestState result; + if (itr != m_pendingAuthRequests.end()) + { + result = std::move(*itr); + *itr = std::move(m_pendingAuthRequests.back()); + m_pendingAuthRequests.pop_back(); + } + + return result; + } +} diff --git a/dev/OAuth/AuthManager.h b/dev/OAuth/AuthManager.h new file mode 100644 index 0000000000..42bbdd2b8e --- /dev/null +++ b/dev/OAuth/AuthManager.h @@ -0,0 +1,72 @@ +#pragma once +#include + +#include "AuthRequestAsyncOperation.h" + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct AuthManager; +} + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::factory_implementation +{ + struct AuthRequestState + { + winrt::hstring state; + winrt::com_ptr async_op; + }; + + struct AuthManager : AuthManagerT + { + foundation::IAsyncOperation InitiateAuthRequestAsync( + const foundation::Uri& authEndpoint, const oauth::AuthRequestParams& params); + bool CompleteAuthRequest(const foundation::Uri& responseUri); + foundation::IAsyncOperation RequestTokenAsync(foundation::Uri tokenEndpoint, + oauth::TokenRequestParams params); + foundation::IAsyncOperation RequestTokenAsync(foundation::Uri tokenEndpoint, + oauth::TokenRequestParams params, oauth::ClientAuthentication clientAuth); + + // Implementation functions + bool try_complete_local(const winrt::hstring& state, const foundation::Uri& responseUri); + void cancel(AuthRequestAsyncOperation* op); + void error(AuthRequestAsyncOperation* op, winrt::hresult hr); + + private: + AuthRequestState try_remove(AuthRequestAsyncOperation* op); + + std::shared_mutex m_mutex; + std::vector m_pendingAuthRequests; + }; +} + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct AuthManager + { + static foundation::IAsyncOperation InitiateAuthRequestAsync( + foundation::Uri authEndpoint, oauth::AuthRequestParams params) + { + return winrt::make_self()->InitiateAuthRequestAsync(authEndpoint, + params); + } + + static bool CompleteAuthRequest(const foundation::Uri& responseUri) + { + return winrt::make_self()->CompleteAuthRequest(responseUri); + } + + static foundation::IAsyncOperation RequestTokenAsync(foundation::Uri tokenEndpoint, + oauth::TokenRequestParams params) + { + return winrt::make_self()->RequestTokenAsync(std::move(tokenEndpoint), + std::move(params)); + } + + static foundation::IAsyncOperation RequestTokenAsync(foundation::Uri tokenEndpoint, + oauth::TokenRequestParams params, oauth::ClientAuthentication clientAuth) + { + return winrt::make_self()->RequestTokenAsync(std::move(tokenEndpoint), + std::move(params), std::move(clientAuth)); + } + }; +} diff --git a/dev/OAuth/AuthRequestAsyncOperation.cpp b/dev/OAuth/AuthRequestAsyncOperation.cpp new file mode 100644 index 0000000000..81c4190a72 --- /dev/null +++ b/dev/OAuth/AuthRequestAsyncOperation.cpp @@ -0,0 +1,541 @@ +#include +#include "common.h" + +#include "AuthManager.h" +#include "AuthRequestAsyncOperation.h" +#include "AuthRequestResult.h" + +#include + +using namespace std::literals; +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; +using namespace winrt::Windows::Security::Cryptography; + +AuthRequestAsyncOperation::AuthRequestAsyncOperation(implementation::AuthRequestParams* params) : + m_params(params->get_strong()) +{ + try + { + // Calling 'finalize' will (1) prevent subsequent changes from being made to the params, (2) validate + // consistency in the parameters that are set, and (3) throw an exception if 'finalize' was previously called by + // someone else. If no exception is thrown, it signals that this object effectively owns the request parameters + // and is able to read and set necessary properties without fear of them being modified by another call + m_params->finalize(); + + if ((m_params->CodeChallengeMethod() != CodeChallengeMethodKind::None) && m_params->CodeVerifier().empty()) + { + m_params->set_code_verifier(winrt::hstring{ random_base64urlencoded_string(32) }); + } + + if (m_params->State().empty()) + { + while (true) + { + winrt::hstring state{ random_base64urlencoded_string(32) }; + if (try_create_pipe(state)) + { + m_params->set_state(state); + break; + } + + // 'FILE_FLAG_FIRST_PIPE_INSTANCE' is documented as failing with 'ERROR_ACCESS_DENIED' if a pipe + // with the same name has already been created. + if (auto err = ::GetLastError(); err != ERROR_ACCESS_DENIED) + { + throw winrt::hresult_error(HRESULT_FROM_WIN32(err), + L"Generation of a unique state value unexpectedly failed"); + } + } + } + else if (!try_create_pipe(m_params->State())) + { + auto err = ::GetLastError(); + auto msg = + (err == ERROR_ACCESS_DENIED) ? L"Provided state value is not unique" : L"Failed to create named pipe"; + throw winrt::hresult_error(HRESULT_FROM_WIN32(err), msg); + } + + m_overlapped.hEvent = ::CreateEventW(nullptr, true, false, nullptr); + if (!m_overlapped.hEvent) + { + throw winrt::hresult_error(HRESULT_FROM_WIN32(::GetLastError()), L"Failed to create an event"); + } + + m_ptp = ::CreateThreadpoolWait(async_callback, this, nullptr); + connect_to_new_client(); + } + catch (...) + { + // Throwing in a constructor will cause the destructor not to run... + destroy(); + throw; + } +} + +AuthRequestAsyncOperation::~AuthRequestAsyncOperation() +{ + destroy(); +} + +void AuthRequestAsyncOperation::destroy() +{ + { + // Expects lock to be held and is required since we haven't ensured all callbacks have completed + std::unique_lock guard{ m_mutex }; + close_pipe(); + } + + // Note that we don't hold the lock here for two reasons. The big reason is that 'WaitForThreadpoolWaitCallbacks may + // wait on a callback trying to acquire the lock. The second reason - and the reason we get away with this - is that + // this code path only gets called on destruction, meaning nothing except callbacks (which we wait for) will access + // or modify object state + if (m_ptp) + { + if (!::SetThreadpoolWaitEx(m_ptp, nullptr, nullptr, nullptr)) + { + // False here means that there's a callback in progress. This would realistically only happen if there was + // a race between the client calling 'Cancel' and someone connecting to the pipe + ::WaitForThreadpoolWaitCallbacks(m_ptp, true); + } + + ::CloseThreadpoolWait(m_ptp); + m_ptp = nullptr; + } + + if (m_overlapped.hEvent) + { + ::CloseHandle(m_overlapped.hEvent); + m_overlapped.hEvent = nullptr; + } +} + +void AuthRequestAsyncOperation::close_pipe() +{ + auto lastState = std::exchange(m_state, state::closed); + if (lastState == state::closed) + { + return; + } + + if (m_pipe != INVALID_HANDLE_VALUE) + { + ::CancelIoEx(m_pipe, &m_overlapped); + ::CloseHandle(m_pipe); + m_pipe = INVALID_HANDLE_VALUE; + } +} + +winrt::hresult AuthRequestAsyncOperation::ErrorCode() +{ + std::shared_lock guard{ m_mutex }; + return m_error; +} + +uint32_t AuthRequestAsyncOperation::Id() +{ + return 1; // NOTE: This is copying the C++/WinRT implementation +} + +winrt::Windows::Foundation::AsyncStatus AuthRequestAsyncOperation::Status() +{ + std::shared_lock guard{ m_mutex }; + return m_status; +} + +void AuthRequestAsyncOperation::Cancel() +{ + winrt::make_self()->cancel(this); +} + +void AuthRequestAsyncOperation::Close() +{ + // TODO? C++/WinRT does a noop here +} + +AsyncOperationCompletedHandler AuthRequestAsyncOperation::Completed() +{ + std::shared_lock guard{ m_mutex }; + return m_handler; +} + +void AuthRequestAsyncOperation::Completed(const AsyncOperationCompletedHandler& handler) +{ + bool shouldInvoke = false; + { + std::lock_guard guard{ m_mutex }; + if (m_handlerSet) + { + throw winrt::hresult_illegal_delegate_assignment(); + } + + m_handlerSet = true; + if (!handler) + { + WINRT_ASSERT(!m_handler); + return; + } + + if (m_status != AsyncStatus::Started) + { + shouldInvoke = true; + } + else if (handler.try_as<::IAgileObject>()) + { + m_handler = handler; + } + else + { + try + { + auto ref = winrt::make_agile(handler); + m_handler = [ref = std::move(ref)](const IAsyncOperation& op, AsyncStatus status) { + ref.get()(op, status); + }; + } + catch (...) + { + m_handler = handler; + } + } + } + + if (shouldInvoke) + { + invoke_handler(handler); + } +} + +AuthRequestResult AuthRequestAsyncOperation::GetResults() +{ + std::shared_lock guard{ m_mutex }; + if (m_status == AsyncStatus::Completed) + { + return m_result; + } + else if (m_error < 0) + { + throw winrt::hresult_error(m_error); + } + + WINRT_ASSERT(m_status == AsyncStatus::Started); + throw winrt::hresult_illegal_method_call(); +} + +void AuthRequestAsyncOperation::complete(const Uri& responseUri) +{ + transition_state(AsyncStatus::Completed, responseUri); +} + +void AuthRequestAsyncOperation::cancel() +{ + transition_state(AsyncStatus::Canceled, nullptr, HRESULT_FROM_WIN32(ERROR_CANCELLED)); +} + +void AuthRequestAsyncOperation::error(winrt::hresult hr) +{ + transition_state(AsyncStatus::Error, nullptr, hr); +} + +void AuthRequestAsyncOperation::transition_state(AsyncStatus status, const Uri& responseUri, winrt::hresult hr) +{ + AsyncOperationCompletedHandler handler; + { + std::lock_guard guard{ m_mutex }; + close_pipe(); + + // State change is initiated by AuthManager and should never happen twice + WINRT_ASSERT(m_status == AsyncStatus::Started); + m_status = status; + m_error = hr; + + if (responseUri) + { + WINRT_ASSERT(hr >= 0); + m_result = winrt::make(m_params.get(), responseUri); + } + else + { + WINRT_ASSERT(hr < 0); + } + + handler = m_handler; + } + + if (handler) + { + invoke_handler(handler); + } +} + +void CALLBACK AuthRequestAsyncOperation::async_callback(PTP_CALLBACK_INSTANCE, PVOID context, PTP_WAIT, + TP_WAIT_RESULT waitResult) +{ + auto pThis = static_cast(context); + pThis->callback(waitResult); +} + +void AuthRequestAsyncOperation::callback(TP_WAIT_RESULT waitResult) +{ + try + { + state currentState; + DWORD bytes = 0; + DWORD overlappedError = ERROR_SUCCESS; + { + std::shared_lock guard{ m_mutex }; + currentState = m_state; + if (currentState == state::closed) + { + // Nothing productive we can do if the pipe was closed. This also likely means the result was an error + return; + } + + if (waitResult == WAIT_OBJECT_0) + { + if (!::GetOverlappedResult(m_pipe, &m_overlapped, &bytes, false)) + { + overlappedError = ::GetLastError(); + } + } + } + + switch (currentState) + { + case state::connecting: { + WINRT_ASSERT(waitResult == WAIT_OBJECT_0); // TODO: Is this valid? Maybe when we cancelled? Error? + if (waitResult != WAIT_OBJECT_0) + { + WINRT_ASSERT(waitResult == WAIT_TIMEOUT); + throw winrt::hresult_error(HRESULT_FROM_WIN32(ERROR_TIMEOUT), + L"Timed out waiting for a client to connect to the pipe"); + } + else if (overlappedError != ERROR_SUCCESS) + { + // If ConnectNamedClient failed, assume we hit an unrecoverable failure + throw winrt::hresult_error(HRESULT_FROM_WIN32(overlappedError), + L"Failed waiting for a client to connect to the pipe"); + } + + initiate_read(); + } + break; + + case state::reading: { + if (overlappedError == ERROR_MORE_DATA) + { + // NOTE: Pipe server is effectively single threaded, hence no synchronization needed here + m_pipeReadData.insert(m_pipeReadData.end(), m_pipeReadBuffer, + m_pipeReadBuffer + m_overlapped.InternalHigh); + initiate_read(); // Need more data before we can complete + } + else if ((waitResult != WAIT_OBJECT_0) || (overlappedError != ERROR_SUCCESS)) + { + // Ideally we could assume that read timeouts/failures are fatal, however we don't know if the client is + // trustworthy and we don't want some arbitrary process to bait us into terminating the request + connect_to_new_client(true); + } + else + { + on_read_complete(); + } + } + break; + + default: + WINRT_ASSERT(false); + throw winrt::hresult_error(E_UNEXPECTED, L"Unexpected failure waiting for AuthRequest result"); + break; + } + } + catch (...) + { + winrt::make_self()->error(this, winrt::to_hresult()); + } +} + +bool AuthRequestAsyncOperation::try_create_pipe(const winrt::hstring& state) +{ + // NOTE: Called on construction where no synchronization is needed + auto name = request_pipe_name(state); + m_pipe = + ::CreateNamedPipeW(name.c_str(), PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED, + PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS, 1, 1024, 1024, 0, nullptr); + + if (m_pipe != INVALID_HANDLE_VALUE) + { + m_pipeName = std::move(name); + return true; + } + + return false; +} + +void AuthRequestAsyncOperation::connect_to_new_client(bool disconnect) +{ + m_pipeReadData.clear(); + + DWORD lastError; + { + std::shared_lock guard{ m_mutex }; + if (m_state == state::closed) + { + return; + } + + if (disconnect) + { + [[maybe_unused]] auto disconnectResult = ::DisconnectNamedPipe(m_pipe); + WINRT_ASSERT(disconnectResult); // TODO: Correct if the client disconnected from us? + } + + [[maybe_unused]] auto connectResult = ::ConnectNamedPipe(m_pipe, &m_overlapped); + WINRT_ASSERT(!connectResult); // Only non-zero in asynchronous mode, even if already connected + lastError = ::GetLastError(); + } + + if (lastError == ERROR_PIPE_CONNECTED) + { + // Client already connected + initiate_read(); + } + else if (lastError != ERROR_IO_PENDING) + { + throw winrt::hresult_error(HRESULT_FROM_WIN32(lastError), L"Failed to listen for clients on the pipe"); + } + else + { + { + std::lock_guard guard{ m_mutex }; + if (m_state == state::closed) + { + // Don't set the threadpool wait again as we may have just cleared it! + return; + } + + m_state = state::connecting; + } + ::SetThreadpoolWait(m_ptp, m_overlapped.hEvent, nullptr); + } +} + +void AuthRequestAsyncOperation::initiate_read() +{ + while (true) + { + BOOL readResult; + { + std::shared_lock guard{ m_mutex }; + if (m_state == state::closed) + { + // No pipe to read from + return; + } + + readResult = ::ReadFile(m_pipe, m_pipeReadBuffer, sizeof(m_pipeReadBuffer), nullptr, &m_overlapped); + } + + if (readResult) + { + // Immediate success. No need to wait + on_read_complete(); + break; + } + + auto err = ::GetLastError(); + if (err == ERROR_MORE_DATA) + { + // Partial read successful; save data and continue loop to try and read more data + m_pipeReadData.insert(m_pipeReadData.end(), m_pipeReadBuffer, m_pipeReadBuffer + m_overlapped.InternalHigh); + } + else if (err == ERROR_IO_PENDING) + { + // Reading asynchronously + std::lock_guard guard{ m_mutex }; + if (m_state == state::closed) + { + // Simultaneously closed; don't set the threadpool wait as we may have just cleared it! + return; + } + + m_state = state::reading; + std::int64_t timeout = std::chrono::duration_cast(-50ms).count(); // 50ms timeout + ::SetThreadpoolWait(m_ptp, m_overlapped.hEvent, reinterpret_cast(&timeout)); + break; + } + else + { + connect_to_new_client(true); + break; + } + } +} + +void AuthRequestAsyncOperation::on_read_complete() +{ + m_pipeReadData.insert(m_pipeReadData.end(), m_pipeReadBuffer, m_pipeReadBuffer + m_overlapped.InternalHigh); + + bool shouldReconnect = true; + try + { + auto expectedState = m_params->State(); + auto encryptedBuffer = CryptographicBuffer::CreateFromByteArray(m_pipeReadData); + auto uriString = decrypt(encryptedBuffer, expectedState); + + // An exception is unlikely (we needed the state from the URI to open the pipe in the first place), but could + // happen if someone is connecting and sending garbage data. We'll catch below, so all is okay + Uri responseUri(uriString); + winrt::hstring state; + auto tryFindState = [&](const winrt::hstring& str) + { + if (str.empty()) + { + return; // Avoid unnecessary construction/activation + } + + for (auto&& entry : WwwFormUrlDecoder(str)) + { + if (entry.Name() == L"state") + { + state = entry.Value(); + break; + } + } + }; + + tryFindState(responseUri.Query()); + if (state.empty()) + { + tryFindState(fragment_component(responseUri)); + } + + if (state == expectedState) + { + shouldReconnect = + winrt::make_self()->try_complete_local(state, responseUri); + } + } + catch (...) + { + // Likely handed bad data; just disconnect and attempt a reconnect + } + + if (shouldReconnect) + { + connect_to_new_client(true); + } + // Otherwise the 'try_complete_local' call should have closed the pipe +} + +void AuthRequestAsyncOperation::invoke_handler(const AsyncOperationCompletedHandler& handler) +{ + try + { + handler(*this, m_status); + } + catch (...) + { + // Just eat exceptions as they're not relevant to the caller at all + } +} diff --git a/dev/OAuth/AuthRequestAsyncOperation.h b/dev/OAuth/AuthRequestAsyncOperation.h new file mode 100644 index 0000000000..c215bbcf20 --- /dev/null +++ b/dev/OAuth/AuthRequestAsyncOperation.h @@ -0,0 +1,69 @@ +#pragma once + +#include "AuthRequestParams.h" + +struct AuthRequestAsyncOperation : + winrt::implements, + foundation::IAsyncInfo> +{ + AuthRequestAsyncOperation(oauth::implementation::AuthRequestParams* params); + ~AuthRequestAsyncOperation(); + + // IAsyncInfo + winrt::hresult ErrorCode(); + uint32_t Id(); + foundation::AsyncStatus Status(); + void Cancel(); + void Close(); + + // IAsyncOperation + foundation::AsyncOperationCompletedHandler Completed(); + void Completed(const foundation::AsyncOperationCompletedHandler& handler); + oauth::AuthRequestResult GetResults(); + + // Internal functions + void complete(const foundation::Uri& responseUri); + void cancel(); + void error(winrt::hresult hr); + +private: + enum class state + { + closed, + connecting, + reading, + }; + + static void CALLBACK async_callback(PTP_CALLBACK_INSTANCE, PVOID context, PTP_WAIT, TP_WAIT_RESULT waitResult); + void callback(TP_WAIT_RESULT waitResult); + + bool try_create_pipe(const winrt::hstring& state); + void close_pipe(); + void connect_to_new_client(bool disconnect = false); + void initiate_read(); + void on_read_complete(); + + void transition_state(foundation::AsyncStatus status, const foundation::Uri& responseUri = nullptr, + winrt::hresult hr = {}); + void invoke_handler(const foundation::AsyncOperationCompletedHandler& handler); + + void destroy(); + + std::shared_mutex m_mutex; + + winrt::com_ptr m_params; + std::wstring m_pipeName; + HANDLE m_pipe = INVALID_HANDLE_VALUE; + state m_state = state::connecting; + OVERLAPPED m_overlapped = {}; + PTP_WAIT m_ptp = nullptr; + std::vector m_pipeReadData; + std::uint8_t m_pipeReadBuffer[128]; + + // IAsyncOperation state + oauth::AuthRequestResult m_result{ nullptr }; + bool m_handlerSet = false; + foundation::AsyncOperationCompletedHandler m_handler; + foundation::AsyncStatus m_status = foundation::AsyncStatus::Started; + winrt::hresult m_error = {}; +}; diff --git a/dev/OAuth/AuthRequestParams.cpp b/dev/OAuth/AuthRequestParams.cpp new file mode 100644 index 0000000000..8ecc41ef00 --- /dev/null +++ b/dev/OAuth/AuthRequestParams.cpp @@ -0,0 +1,252 @@ +#include +#include "common.h" + +#include "AuthRequestParams.h" + +#include + +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; +using namespace winrt::Windows::Security::Cryptography; +using namespace winrt::Windows::Security::Cryptography::Core; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + AuthRequestParams::AuthRequestParams(const winrt::hstring& responseType, const winrt::hstring& clientId) : + m_responseType(responseType), + m_clientId(clientId) + { + THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::Security::Authentication::OAuth::Feature_OAuth::IsEnabled()); + } + + AuthRequestParams::AuthRequestParams(const winrt::hstring& responseType, const winrt::hstring& clientId, + const Uri& redirectUri) : + m_responseType(responseType), + m_clientId(clientId), + m_redirectUri(redirectUri) + { + THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::Security::Authentication::OAuth::Feature_OAuth::IsEnabled()); + } + + oauth::AuthRequestParams AuthRequestParams::CreateForAuthorizationCodeRequest(const winrt::hstring& clientId) + { + return CreateForAuthorizationCodeRequest(clientId, nullptr); + } + + oauth::AuthRequestParams AuthRequestParams::CreateForAuthorizationCodeRequest(const winrt::hstring& clientId, + const Uri& redirectUri) + { + auto result = winrt::make_self(L"code", clientId, redirectUri); + result->m_codeChallengeMethod = CodeChallengeMethodKind::S256; + return *result; + } + + oauth::AuthRequestParams AuthRequestParams::CreateForImplicitRequest(const winrt::hstring& clientId) + { + return winrt::make(L"token", clientId); + } + + oauth::AuthRequestParams AuthRequestParams::CreateForImplicitRequest(const winrt::hstring& clientId, + const Uri& redirectUri) + { + return winrt::make(L"token", clientId, redirectUri); + } + + winrt::hstring AuthRequestParams::ResponseType() + { + std::shared_lock guard{ m_mutex }; + return m_responseType; + } + + void AuthRequestParams::ResponseType(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_responseType = value; + } + + winrt::hstring AuthRequestParams::ClientId() + { + std::shared_lock guard{ m_mutex }; + return m_clientId; + } + + void AuthRequestParams::ClientId(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_clientId = value; + } + + Uri AuthRequestParams::RedirectUri() + { + std::shared_lock guard{ m_mutex }; + return m_redirectUri; + } + + void AuthRequestParams::RedirectUri(const Uri& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_redirectUri = value; + } + + winrt::hstring AuthRequestParams::State() + { + std::shared_lock guard{ m_mutex }; + return m_state; + } + + void AuthRequestParams::State(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_state = value; + } + + winrt::hstring AuthRequestParams::Scope() + { + std::shared_lock guard{ m_mutex }; + return m_scope; + } + + void AuthRequestParams::Scope(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_scope = value; + } + + winrt::hstring AuthRequestParams::CodeVerifier() + { + std::shared_lock guard{ m_mutex }; + return m_codeVerifier; + } + + void AuthRequestParams::CodeVerifier(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_codeVerifier = value; + } + + CodeChallengeMethodKind AuthRequestParams::CodeChallengeMethod() + { + std::shared_lock guard{ m_mutex }; + return m_codeChallengeMethod; + } + + void AuthRequestParams::CodeChallengeMethod(CodeChallengeMethodKind value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_codeChallengeMethod = value; + } + + IMap AuthRequestParams::AdditionalParams() + { + std::shared_lock guard{ m_mutex }; + return *m_additionalParams; + } + + void AuthRequestParams::finalize() + { + std::lock_guard guard{ m_mutex }; + if (m_finalized) + { + throw winrt::hresult_illegal_method_call(L"AuthRequestParams can only be used for a single request call"); + } + + m_finalized = true; + m_additionalParams->lock(); + + if (!m_codeVerifier.empty() && (m_codeChallengeMethod == CodeChallengeMethodKind::None)) + { + throw winrt::hresult_illegal_method_call( + L"'CodeVerifier' cannot be set when 'CodeChallengeMethod' is set to 'None'"); + } + } + + void AuthRequestParams::set_state(winrt::hstring value) + { + std::lock_guard guard{ m_mutex }; + WINRT_ASSERT(m_state.empty()); + m_state = std::move(value); + } + + void AuthRequestParams::set_code_verifier(winrt::hstring value) + { + std::lock_guard guard{ m_mutex }; + WINRT_ASSERT(m_codeVerifier.empty()); + WINRT_ASSERT(m_codeChallengeMethod != CodeChallengeMethodKind::None); + m_codeVerifier = std::move(value); + } + + std::wstring AuthRequestParams::create_url(const Uri& authEndpoint) + { + std::shared_lock guard{ m_mutex }; + WINRT_ASSERT(m_finalized); + + // Per RFC 6749 section 3.1, the auth endpoint URI *MAY* contain a query string, which must be retained + std::wstring result{ authEndpoint.RawUri() }; + if (authEndpoint.Query().empty()) + { + result += L"?state="; + } + else + { + result += L"&state="; + } + + result += Uri::EscapeComponent(m_state); + + if (!m_responseType.empty()) + { + result += L"&response_type="; + result += Uri::EscapeComponent(m_responseType); + } + + if (!m_clientId.empty()) + { + result += L"&client_id="; + result += Uri::EscapeComponent(m_clientId); + } + + if (m_redirectUri) + { + result += L"&redirect_uri="; + result += Uri::EscapeComponent(m_redirectUri.RawUri()); + } + + if (!m_scope.empty()) + { + result += L"&scope="; + result += Uri::EscapeComponent(m_scope); + } + + if (m_codeChallengeMethod == CodeChallengeMethodKind::S256) + { + result += L"&code_challenge_method=S256&code_challenge="; + result += base64urlencode(sha256(m_codeVerifier)); + } + else if (m_codeChallengeMethod == CodeChallengeMethodKind::Plain) + { + result += L"&code_challenge_method=plain&code_challenge="; + result += Uri::EscapeComponent(m_codeVerifier); + } + + if (m_additionalParams) + { + for (auto&& pair : IMap{ *m_additionalParams }) + { + result += L"&"; + result += Uri::EscapeComponent(pair.Key()); + result += L"="; + result += Uri::EscapeComponent(pair.Value()); + } + } + + return result; + } +} diff --git a/dev/OAuth/AuthRequestParams.h b/dev/OAuth/AuthRequestParams.h new file mode 100644 index 0000000000..7d8f28b2f3 --- /dev/null +++ b/dev/OAuth/AuthRequestParams.h @@ -0,0 +1,76 @@ +#pragma once +#include + +#include + +#include "LockableMap.h" + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct AuthRequestParams : AuthRequestParamsT + { + AuthRequestParams(const winrt::hstring& responseType, const winrt::hstring& clientId); + AuthRequestParams(const winrt::hstring& responseType, const winrt::hstring& clientId, + const foundation::Uri& redirectUri); + + static oauth::AuthRequestParams CreateForAuthorizationCodeRequest(const winrt::hstring& clientId); + static oauth::AuthRequestParams CreateForAuthorizationCodeRequest(const winrt::hstring& clientId, + const foundation::Uri& redirectUri); + static oauth::AuthRequestParams CreateForImplicitRequest(const winrt::hstring& clientId); + static oauth::AuthRequestParams CreateForImplicitRequest(const winrt::hstring& clientId, + const foundation::Uri& redirectUri); + + // Interface functions + winrt::hstring ResponseType(); + void ResponseType(const winrt::hstring& value); + winrt::hstring ClientId(); + void ClientId(const winrt::hstring& value); + foundation::Uri RedirectUri(); + void RedirectUri(const foundation::Uri& value); + winrt::hstring State(); + void State(const winrt::hstring& value); + winrt::hstring Scope(); + void Scope(const winrt::hstring& value); + winrt::hstring CodeVerifier(); + void CodeVerifier(const winrt::hstring& value); + oauth::CodeChallengeMethodKind CodeChallengeMethod(); + void CodeChallengeMethod(oauth::CodeChallengeMethodKind value); + collections::IMap AdditionalParams(); + + // Implementation functions + void finalize(); + void set_state(winrt::hstring value); + void set_code_verifier(winrt::hstring value); + std::wstring create_url(const foundation::Uri& authEndpoint); + + private: + void check_not_finalized() + { + // NOTE: Lock should be held when calling + if (m_finalized) + { + throw winrt::hresult_illegal_method_call( + L"AuthRequestParams object cannot be modified after being used to initiate a request"); + } + } + + std::shared_mutex m_mutex; + bool m_finalized = false; + winrt::hstring m_responseType; + winrt::hstring m_clientId; + foundation::Uri m_redirectUri{ nullptr }; + winrt::hstring m_state; + winrt::hstring m_scope; + winrt::hstring m_codeVerifier; + oauth::CodeChallengeMethodKind m_codeChallengeMethod = oauth::CodeChallengeMethodKind::None; + winrt::com_ptr> m_additionalParams = + winrt::make_self>(); + }; +} + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::factory_implementation +{ + struct AuthRequestParams : AuthRequestParamsT + { + }; +} diff --git a/dev/OAuth/AuthRequestResult.cpp b/dev/OAuth/AuthRequestResult.cpp new file mode 100644 index 0000000000..702d4112a3 --- /dev/null +++ b/dev/OAuth/AuthRequestResult.cpp @@ -0,0 +1,75 @@ +#include +#include "common.h" + +#include "AuthFailure.h" +#include "AuthRequestResult.h" +#include "AuthResponse.h" + +#include + +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + AuthRequestResult::AuthRequestResult(AuthRequestParams* params, const Uri& responseUri) : m_responseUri(responseUri) + { + // We first need to figure out if this is a success or failure response + bool isError = false; + bool isSuccess = false; + auto checkComponent = [&](const winrt::hstring& str) { + if (str.empty()) + { + return; // Avoid unnecessary construction/activation + } + + for (auto&& entry : WwwFormUrlDecoder(str)) + { + auto name = entry.Name(); + if ((name == L"code") || (name == L"access_token")) + { + isSuccess = true; + break; + } + else if (name == L"error") + { + isError = true; + break; + } + } + }; + + checkComponent(responseUri.Query()); + if (!isError && !isSuccess) + { + checkComponent(fragment_component(responseUri)); + } + + // If we don't recognize the response as an error, interpret it as success. The application may be using an + // extension that we don't recognize + if (isError) + { + m_failure = winrt::make(m_responseUri); + } + else + { + m_response = winrt::make(params, m_responseUri); + } + } + + Uri AuthRequestResult::ResponseUri() + { + return m_responseUri; + } + + oauth::AuthResponse AuthRequestResult::Response() + { + return m_response; + } + + oauth::AuthFailure AuthRequestResult::Failure() + { + return m_failure; + } +} diff --git a/dev/OAuth/AuthRequestResult.h b/dev/OAuth/AuthRequestResult.h new file mode 100644 index 0000000000..3da290919a --- /dev/null +++ b/dev/OAuth/AuthRequestResult.h @@ -0,0 +1,21 @@ +#pragma once +#include + +#include "AuthRequestParams.h" + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct AuthRequestResult : AuthRequestResultT + { + AuthRequestResult(AuthRequestParams* params, const foundation::Uri& responseUri); + + foundation::Uri ResponseUri(); + oauth::AuthResponse Response(); + oauth::AuthFailure Failure(); + + private: + foundation::Uri m_responseUri; + oauth::AuthResponse m_response{ nullptr }; + oauth::AuthFailure m_failure{ nullptr }; + }; +} diff --git a/dev/OAuth/AuthResponse.cpp b/dev/OAuth/AuthResponse.cpp new file mode 100644 index 0000000000..c793fe66be --- /dev/null +++ b/dev/OAuth/AuthResponse.cpp @@ -0,0 +1,99 @@ +#include +#include "common.h" + +#include "AuthResponse.h" + +#include + +using namespace std::literals; +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + AuthResponse::AuthResponse(AuthRequestParams* requestParams, const Uri& responseUri) : + m_requestParams(requestParams->get_strong()) + { + std::map additionalParams; + auto parseComponents = [&](const winrt::hstring& str) { + if (str.empty()) + { + return; // Avoid unnecessary construction/activation + } + + for (auto&& entry : WwwFormUrlDecoder(str)) + { + auto name = entry.Name(); + if (name == L"state"sv) + { + m_state = entry.Value(); + } + else if (name == L"code"sv) + { + m_code = entry.Value(); + } + else if (name == L"access_token"sv) + { + m_accessToken = entry.Value(); + } + else if (name == L"token_type"sv) + { + m_tokenType = entry.Value(); + } + else if (name == L"expires_in"sv) + { + m_expiresIn = entry.Value(); + } + else if (name == L"scope"sv) + { + m_scope = entry.Value(); + } + else + { + additionalParams.emplace(std::move(name), entry.Value()); + } + } + }; + + parseComponents(responseUri.Query()); + parseComponents(fragment_component(responseUri)); + + m_additionalParams = winrt::single_threaded_map(std::move(additionalParams)).GetView(); + } + + winrt::hstring AuthResponse::State() + { + return m_state; + } + + winrt::hstring AuthResponse::Code() + { + return m_code; + } + + winrt::hstring AuthResponse::AccessToken() + { + return m_accessToken; + } + + winrt::hstring AuthResponse::TokenType() + { + return m_tokenType; + } + + winrt::hstring AuthResponse::ExpiresIn() + { + return m_expiresIn; + } + + winrt::hstring AuthResponse::Scope() + { + return m_scope; + } + + IMapView AuthResponse::AdditionalParams() + { + return m_additionalParams; + } +} diff --git a/dev/OAuth/AuthResponse.h b/dev/OAuth/AuthResponse.h new file mode 100644 index 0000000000..7c1fd95722 --- /dev/null +++ b/dev/OAuth/AuthResponse.h @@ -0,0 +1,37 @@ +#pragma once +#include + +#include "AuthRequestParams.h" + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct AuthResponse : AuthResponseT + { + AuthResponse(AuthRequestParams* params, const foundation::Uri& responseUri); + + winrt::hstring State(); + winrt::hstring Code(); + winrt::hstring AccessToken(); + winrt::hstring TokenType(); + winrt::hstring ExpiresIn(); + winrt::hstring Scope(); + collections::IMapView AdditionalParams(); + + // Implementation functions + const winrt::com_ptr& request_params() const noexcept + { + return m_requestParams; + } + + private: + winrt::com_ptr m_requestParams; + + winrt::hstring m_state; + winrt::hstring m_code; + winrt::hstring m_accessToken; + winrt::hstring m_tokenType; + winrt::hstring m_expiresIn; + winrt::hstring m_scope; + collections::IMapView m_additionalParams; + }; +} diff --git a/dev/OAuth/ClientAuthentication.cpp b/dev/OAuth/ClientAuthentication.cpp new file mode 100644 index 0000000000..608ee16d9b --- /dev/null +++ b/dev/OAuth/ClientAuthentication.cpp @@ -0,0 +1,66 @@ +#include +#include "common.h" + +#include "ClientAuthentication.h" + +#include + +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; +using namespace winrt::Windows::Security::Cryptography; +using namespace winrt::Windows::Web::Http::Headers; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + ClientAuthentication::ClientAuthentication() + { + THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::Security::Authentication::OAuth::Feature_OAuth::IsEnabled()); + } + + ClientAuthentication::ClientAuthentication(const HttpCredentialsHeaderValue& authorization) : + m_authorization(authorization) + { + THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::Security::Authentication::OAuth::Feature_OAuth::IsEnabled()); + } + + oauth::ClientAuthentication ClientAuthentication::CreateForBasicAuthorization(const winrt::hstring& clientId, + const winrt::hstring& clientSecret) + { + auto authString = clientId + L":" + clientSecret; + auto buffer = CryptographicBuffer::ConvertStringToBinary(authString, BinaryStringEncoding::Utf8); + auto base64Token = CryptographicBuffer::EncodeToBase64String(buffer); + HttpCredentialsHeaderValue header(L"Basic", base64Token); + return winrt::make(header); + } + + HttpCredentialsHeaderValue ClientAuthentication::Authorization() + { + std::shared_lock guard{ m_mutex }; + return m_authorization; + } + + void ClientAuthentication::Authorization(const HttpCredentialsHeaderValue& value) + { + std::lock_guard guard{ m_mutex }; + m_authorization = value; + } + + HttpCredentialsHeaderValue ClientAuthentication::ProxyAuthorization() + { + std::shared_lock guard{ m_mutex }; + return m_proxyAuthorization; + } + + void ClientAuthentication::ProxyAuthorization(const HttpCredentialsHeaderValue& value) + { + std::lock_guard guard{ m_mutex }; + m_proxyAuthorization = value; + } + + winrt::Windows::Foundation::Collections::IMap ClientAuthentication::AdditionalHeaders() + { + std::shared_lock guard{ m_mutex }; + return m_additionalHeaders; + } +} diff --git a/dev/OAuth/ClientAuthentication.h b/dev/OAuth/ClientAuthentication.h new file mode 100644 index 0000000000..2773304dc2 --- /dev/null +++ b/dev/OAuth/ClientAuthentication.h @@ -0,0 +1,35 @@ +#pragma once +#include + +#include + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct ClientAuthentication : ClientAuthenticationT + { + ClientAuthentication(); + ClientAuthentication(http::Headers::HttpCredentialsHeaderValue const& authorization); + + static oauth::ClientAuthentication CreateForBasicAuthorization(const winrt::hstring& clientId, + const winrt::hstring& clientSecret); + + http::Headers::HttpCredentialsHeaderValue Authorization(); + void Authorization(http::Headers::HttpCredentialsHeaderValue const& value); + http::Headers::HttpCredentialsHeaderValue ProxyAuthorization(); + void ProxyAuthorization(http::Headers::HttpCredentialsHeaderValue const& value); + collections::IMap AdditionalHeaders(); + + private: + std::shared_mutex m_mutex; + http::Headers::HttpCredentialsHeaderValue m_authorization{ nullptr }; + http::Headers::HttpCredentialsHeaderValue m_proxyAuthorization{ nullptr }; + collections::IMap m_additionalHeaders = + winrt::multi_threaded_map(); + }; +} +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::factory_implementation +{ + struct ClientAuthentication : ClientAuthenticationT + { + }; +} diff --git a/dev/OAuth/Crypto.h b/dev/OAuth/Crypto.h new file mode 100644 index 0000000000..217d0ccda4 --- /dev/null +++ b/dev/OAuth/Crypto.h @@ -0,0 +1,104 @@ +// Helpers using the cryptographic APIs +#pragma once + +#include + +inline std::wstring base64urlencode(const streams::IBuffer& buffer) +{ + using namespace winrt::Windows::Security::Cryptography; + + std::wstring result; + auto base64 = CryptographicBuffer::EncodeToBase64String(buffer); + result.reserve(base64.size()); + + for (auto ch : base64) + { + switch (ch) + { + case '+': result.push_back('-'); break; + case '/': result.push_back('_'); break; + case '=': break; // No padding + default: result.push_back(ch); break; + } + } + + return result; +} + +inline std::wstring random_base64urlencoded_string(std::uint32_t octets) +{ + using namespace winrt::Windows::Security::Cryptography; + auto buffer = CryptographicBuffer::GenerateRandom(octets); + return base64urlencode(buffer); +} + +inline streams::IBuffer sha256(const winrt::hstring& text, + crypto::BinaryStringEncoding encoding = crypto::BinaryStringEncoding::Utf8) +{ + using namespace winrt::Windows::Security::Cryptography; + using namespace winrt::Windows::Security::Cryptography::Core; + + auto algo = HashAlgorithmProvider::OpenAlgorithm(HashAlgorithmNames::Sha256()); + return CryptographicBuffer::ConvertStringToBinary(text, encoding); +} + +inline winrt::hstring sha256_base64encoded(const winrt::hstring& text) +{ + auto buffer = sha256(text); + return crypto::CryptographicBuffer::EncodeToBase64String(buffer); +} + +inline std::wstring request_pipe_name(const winrt::hstring& state) +{ + // In order to try and protect the state and auth code, we use a hash of the state value for the pipe name + std::wstring result = LR"^-^(\\.\pipe\oauth\)^-^"; + result += sha256_base64encoded(state); + return result; +} + +inline crypto::Core::CryptographicKey create_key(const winrt::hstring& keyString) +{ + using namespace winrt::Windows::Security::Cryptography; + using namespace winrt::Windows::Security::Cryptography::Core; + using namespace winrt::Windows::Storage::Streams; + + WINRT_ASSERT(!keyString.empty()); + + // AES key must be 128, 192, or 256 bits (16, 24, or 32 bytes). Note that the key doesn't have to make a valid + // string. If we end up slicing a UTF-8 character, that's okay + auto keyBuffer = CryptographicBuffer::ConvertStringToBinary(keyString, BinaryStringEncoding::Utf8); + auto keyBufferBegin = keyBuffer.data(); + auto keyBufferEnd = keyBufferBegin + keyBuffer.Length(); + + // Repeat the key string as necessary to achieve the desired length + std::vector buffer(keyBufferBegin, keyBufferEnd); + auto desiredSize = (buffer.size() <= 16) ? 16 : (buffer.size() <= 24) ? 24 : 32; + while (buffer.size() < desiredSize) + { + buffer.insert(buffer.end(), keyBufferBegin, keyBufferEnd); + } + buffer.resize(desiredSize); + + auto algo = SymmetricKeyAlgorithmProvider::OpenAlgorithm(SymmetricAlgorithmNames::AesEcbPkcs7()); + return algo.CreateSymmetricKey(CryptographicBuffer::CreateFromByteArray(buffer)); +} + +inline streams::IBuffer encrypt(const winrt::hstring& message, const winrt::hstring& keyString) +{ + using namespace winrt::Windows::Security::Cryptography; + using namespace winrt::Windows::Security::Cryptography::Core; + + auto msgBuffer = CryptographicBuffer::ConvertStringToBinary(message, BinaryStringEncoding::Utf8); + auto key = create_key(keyString); + return CryptographicEngine::Encrypt(key, msgBuffer, nullptr); +} + +inline winrt::hstring decrypt(const streams::IBuffer& encryptedBuffer, const winrt::hstring& keyString) +{ + using namespace winrt::Windows::Security::Cryptography; + using namespace winrt::Windows::Security::Cryptography::Core; + + auto key = create_key(keyString); + auto decryptedBuffer = CryptographicEngine::Decrypt(key, encryptedBuffer, nullptr); + return CryptographicBuffer::ConvertBinaryToString(BinaryStringEncoding::Utf8, decryptedBuffer); +} diff --git a/dev/OAuth/LockableMap.h b/dev/OAuth/LockableMap.h new file mode 100644 index 0000000000..879ea93af6 --- /dev/null +++ b/dev/OAuth/LockableMap.h @@ -0,0 +1,301 @@ +#pragma once + +#include +#include + +namespace impl +{ + template + inline T default_value() + { + if constexpr (std::is_constructible_v) + { + // Handles classes where we'd otherwise get activation + return T{ nullptr }; + } + else + { + return T{}; + } + } + + template + struct KeyValuePair : winrt::implements, collections::IKeyValuePair> + { + KeyValuePair(KeyT key, ValueT value) : + m_key(std::move(key)), + m_value(std::move(value)) + { + } + + KeyT Key() + { + return m_key; + } + + ValueT Value() + { + return m_value; + } + + private: + + KeyT m_key; + ValueT m_value; + }; + + template + struct LockableMapIterator : winrt::implements, + collections::IIterator>> + { + LockableMapIterator(winrt::com_ptr map, std::size_t version) : m_map(std::move(map)), m_version(version) + { + m_itr = m_map->m_map.begin(); + } + + // IIterator + collections::IKeyValuePair Current() + { + std::shared_lock guard{ m_map->m_mutex }; + check_version(); + if (m_itr == m_map->m_map.end()) + { + throw winrt::hresult_out_of_bounds(); + } + + return winrt::make>(m_itr->first, m_itr->second); + } + + bool HasCurrent() + { + std::shared_lock guard{ m_map->m_mutex }; + check_version(); + return m_itr != m_map->m_map.end(); + } + + std::uint32_t GetMany(winrt::array_view> items) + { + std::shared_lock guard{ m_map->m_mutex }; + check_version(); + + auto end = m_map->m_map.end(); + std::uint32_t result = 0; + for (; (m_itr != end) && (result < items.size()); ++m_itr) + { + items[result++] = winrt::make>(m_itr->first, m_itr->second); + } + + return result; + } + + bool MoveNext() + { + std::shared_lock guard{ m_map->m_mutex }; + check_version(); + + auto end = m_map->m_map.end(); + if (m_itr != end) + { + ++m_itr; + } + + return m_itr != end; + } + + private: + void check_version() + { + if (m_version != m_map->m_version) + { + throw winrt::hresult_changed_state(); + } + } + + winrt::com_ptr m_map; + std::size_t m_version; + typename std::map::const_iterator m_itr; + }; + + template + struct LockableMapView : winrt::implements, + collections::IMapView, + collections::IIterable>> + { + LockableMapView(winrt::com_ptr map, std::size_t version) : m_map(std::move(map)), m_version(version) + { + } + + // IMapView + std::uint32_t Size() + { + std::shared_lock guard{ m_map->m_mutex }; + check_version(); + return static_cast(m_map->m_map.size()); + } + + bool HasKey(const KeyT& key) + { + std::shared_lock guard{ m_map->m_mutex }; + check_version(); + return m_map->m_map.find(key) != m_map->m_map.end(); + } + + ValueT Lookup(const KeyT& key) + { + std::shared_lock guard{ m_map->m_mutex }; + check_version(); + auto itr = m_map->m_map.find(key); + if (itr == m_map->m_map.end()) + { + throw winrt::hresult_out_of_bounds(); + } + + return itr->second; + } + + void Split(collections::IMapView& lhs, collections::IMapView& rhs) + { + // NOTE: Follows C++/WinRT implementation + lhs = nullptr; + rhs = nullptr; + } + + // IIterable + collections::IIterator> First() + { + std::shared_lock guard{ m_map->m_mutex }; + return winrt::make>(m_map, m_version); + } + + private: + void check_version() + { + if (m_version != m_map->m_version) + { + throw winrt::hresult_changed_state(); + } + } + + winrt::com_ptr m_map; + std::size_t m_version; + }; +} + +// Here, "lock" means "prevent further modification." Of course, the objects contained within the map can modified, but +// nothing can be added/removed from the map +template +struct LockableMap : winrt::implements, + collections::IMap, + collections::IIterable>> +{ + friend struct impl::LockableMapIterator; + friend struct impl::LockableMapView; + + // IMap + std::uint32_t Size() + { + std::shared_lock guard{ m_mutex }; + return static_cast(m_map.size()); + } + + void Clear() + { + std::map oldValues; // Release outside of lock + + std::lock_guard guard{ m_mutex }; + check_not_locked(); + m_map.swap(oldValues); + ++m_version; + } + + collections::IMapView GetView() + { + std::shared_lock guard{ m_mutex }; + return winrt::make>(this->get_strong(), m_version); + } + + bool HasKey(const KeyT& value) + { + std::shared_lock guard{ m_mutex }; + return m_map.find(value) != m_map.end(); + } + + bool Insert(const KeyT& key, const ValueT& value) + { + auto removedValue = impl::default_value(); + + std::lock_guard guard{ m_mutex }; + check_not_locked(); + auto [itr, added] = m_map.emplace(key, value); + if (!added) + { + std::swap(removedValue, itr->second); + itr->second = value; + } + ++m_version; + + return !added; + } + + ValueT Lookup(const KeyT& key) + { + std::shared_lock guard{ m_mutex }; + auto itr = m_map.find(key); + if (itr == m_map.end()) + { + throw winrt::hresult_out_of_bounds(); + } + return itr->second; + } + + void Remove(const KeyT& key) + { + typename std::map::node_type node; // Destroy outside of lock + + { + std::lock_guard guard{ m_mutex }; + check_not_locked(); + node = m_map.extract(key); + ++m_version; + } + + if (!node) + { + throw winrt::hresult_out_of_bounds(); + } + } + + // IIterable + collections::IIterator> First() + { + std::shared_lock guard{ m_mutex }; + return winrt::make>(this->get_strong(), m_version); + } + + // Implementation Functions + void lock() + { + std::lock_guard guard{ m_mutex }; + if (m_locked) + { + throw winrt::hresult_illegal_method_call(L"Map has already been locked from modification"); + } + + m_locked = true; + } + +private: + void check_not_locked() + { + // NOTE: Lock should be held when calling + if (m_locked) + { + throw winrt::hresult_illegal_method_call(L"Map has been locked from modification"); + } + } + + std::shared_mutex m_mutex; + std::size_t m_version = 0; + bool m_locked = false; + std::map m_map; +}; diff --git a/dev/OAuth/OAuth.idl b/dev/OAuth/OAuth.idl new file mode 100644 index 0000000000..cb70da86ba --- /dev/null +++ b/dev/OAuth/OAuth.idl @@ -0,0 +1,464 @@ +// Copyright (c) Microsoft Corporation and Contributors. +// Licensed under the MIT License. + +#include + +namespace Microsoft.Windows.Security.Authentication.OAuth +{ + [contractversion(1)] + apicontract OAuthContract {}; + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + runtimeclass ClientAuthentication + { + ClientAuthentication(); + ClientAuthentication(Windows.Web.Http.Headers.HttpCredentialsHeaderValue authorization); + + static ClientAuthentication CreateForBasicAuthorization(String clientId, String clientSecret); + + // Specifies the 'Authorization' header of the HTTP POST request when requesting a token + Windows.Web.Http.Headers.HttpCredentialsHeaderValue Authorization { get; set; }; + + // Specifies the 'Proxy-Authorization' header of the HTTP POST request when requesting a token + Windows.Web.Http.Headers.HttpCredentialsHeaderValue ProxyAuthorization { get; set; }; + + // Specifies additional header values of the HTTP POST request when requesting a token + Windows.Foundation.Collections.IMap AdditionalHeaders { get; }; + } + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + static runtimeclass AuthManager + { + // Initiates an authorization request in the user's default browser as described by RFC 6749 section 3.1. The + // returned 'IAsyncOperation' will remain in the 'Started' state until it is either cancelled or completed by a + // call to 'CompleteAuthRequest'. + static Windows.Foundation.IAsyncOperation InitiateAuthRequestAsync( + Windows.Foundation.Uri authEndpoint, + AuthRequestParams params); + + // Called by the application when the user agent completes an auth request via a redirect Uri. Return value is + // true if an appropriate request could be found and completed. Otherwise returns false indicating that the + // response went unhandled and the application may respond as appropriate. + static Boolean CompleteAuthRequest(Windows.Foundation.Uri responseUri); + + // Initiates an access token request as described by RFC 6749 section 3.2. + static Windows.Foundation.IAsyncOperation RequestTokenAsync( + Windows.Foundation.Uri tokenEndpoint, + TokenRequestParams params); + + // Initiates an access token request as described by RFC 6749 section 3.2. + static Windows.Foundation.IAsyncOperation RequestTokenAsync( + Windows.Foundation.Uri tokenEndpoint, + TokenRequestParams params, + ClientAuthentication clientAuth); + } + + // Correlates to the 'code_challenge_method' as described by section 4.3 of RFC 7636: Proof Key for Code Exchange by + // OAuth Public Clients (https://www.rfc-editor.org/rfc/rfc7636.html#section-4.3) + [contract(OAuthContract, 1), feature(Feature_OAuth)] + enum CodeChallengeMethodKind + { + // Suppresses the use of a code verifier. An error will be thrown if a code challenge string is set when this + // option is used + None = 0, + // Challenge method of "S256" (i.e. SHA256). This is the default unless explicitly set + S256 = 1, + // Challenge method of "plain" (i.e. send as plain text) + Plain = 2, + }; + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + runtimeclass AuthRequestParams + { + // Construct with required parameters + AuthRequestParams(String responseType, String clientId); + // Construct with required parameters as well as a redirect URI, which is frequently specified + AuthRequestParams(String responseType, String clientId, Windows.Foundation.Uri redirectUri); + + // Helper method to create for an authorization code grant request ("code" response type) with required + // parameters, per RFC 6749 section 4.1.1. + static AuthRequestParams CreateForAuthorizationCodeRequest(String clientId); + // Helper method to create for an authorization code grant request ("code" response type) with required + // parameters as well as a redirect URI, which is frequently specified. + static AuthRequestParams CreateForAuthorizationCodeRequest(String clientId, Windows.Foundation.Uri redirectUri); + + // Helper method to create for an implicit grant request ("token" response type) with required parameters, per + // RFC 6749 section 4.2.1. + static AuthRequestParams CreateForImplicitRequest(String clientId); + // Helper method to create for an implicit grant request ("token" response type) with required parameters as + // well as a redirect URI, which is frequently specified. + static AuthRequestParams CreateForImplicitRequest(String clientId, Windows.Foundation.Uri redirectUri); + + // Specifies the required "response_type" parameter of the authorization request. This property is initialized + // by the creation function used ("code" for 'CreateForAuthorizationCodeRequest' and "token" for + // 'CreateForImplicitRequest'). + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.1 and 4.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.1 + String ResponseType { get; set; }; + + // Specifies the required "client_id" parameter of the authorization request. This property is initialized by + // the value provided in the creation function call. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.1 and 4.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.1 + String ClientId { get; set; }; + + // Specifies the optional "redirect_uri" parameter of the authorization request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.1 and 4.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.1 + Windows.Foundation.Uri RedirectUri { get; set; }; + + // Specifies the recommended "state" parameter of the authorization request. Note that although this is not + // required by the OAuth standard, a state value will always be set to correlate requests and responses. This + // parameter can be manually specified, in which case it must be globally unique across the entire system, + // otherwise an error will be thrown. It is therefore recommended to let the API select a value for you as it + // will guarantee that a unique value will be used. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.1 and 4.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.1 + String State { get; set; }; + + // Specifies the optional "scope" parameter of the authorization request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.1 and 4.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.1 + String Scope { get; set; }; + + // Used as the PKCE code verifier. Either this value or a hash of this value will be used to specify the + // "code_challenge" parameter of the authorization request, depending on the value of 'CodeChallengeMethod'. If + // this value is not specified and 'CodeChallengeMethod' is not 'None', a random value will be generated for + // this property. The code verifier will persist all the way through to the token request. + // + // Defined by RFC 7636: Proof Key for Code Exchange by OAuth Public Clients, section 4.1 + // https://www.rfc-editor.org/rfc/rfc7636#section-4.1 + String CodeVerifier { get; set; }; + + // Specifies the optional "code_challenge_method" parameter of the authorization request. For authorization code + // requests, this value defaults to 'S256'. For implicit requests, this value defaults to 'None' and cannot be + // changed. + // + // Defined by RFC 7636: Proof Key for Code Exchange by OAuth Public Clients, section 4.3 + // https://www.rfc-editor.org/rfc/rfc7636#section-4.3 + CodeChallengeMethodKind CodeChallengeMethod { get; set; }; + + // Additional parameters passed along in the query string of the request URL. + Windows.Foundation.Collections.IMap AdditionalParams { get; }; + } + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + runtimeclass AuthResponse + { + // From the "state" parameter of the authorization response. This property will always be set because a state + // value is always sent with the request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.2 and 4.2.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2 + String State { get; }; + + // From the "code" parameter of the authorization response. Set only if the request was an authorization code + // request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.1.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2 + String Code { get; }; + + // From the "access_token" parameter of the authorization response. Set only if the request was an implicit + // request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.2.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2 + String AccessToken { get; }; + + // From the "token_type" parameter of the authorization response. Set only if the request was an implicit + // request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.2.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2 + String TokenType { get; }; + + // From the "expires_in" parameter of the authorization response. An optional parameter that may be set only if + // the request was an implicit request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.2.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2 + String ExpiresIn { get; }; // TODO: DateTime? + + // From the "scope" parameter of the authorization response. An optional parameter that may be set only if the + // request was an implicit request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.2.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2 + String Scope { get; }; + + // Additional parameters set by the authorization server in the response URI. + Windows.Foundation.Collections.IMapView AdditionalParams { get; }; + } + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + runtimeclass AuthFailure + { + // From the "error" parameter of the error response. The value of this property will map to a well known string + // specified in RFC 6749 sections 4.1.2.1 and 4.2.2.1, or approved extensions. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.2.1 and 4.2.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2.1 + String Error { get; }; + + // From the "error_description" parameter of the error response. An optional parameter that, when set, provides + // additional human-readable information intended to assist the developer in understanding the error. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.2.1 and 4.2.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2.1 + String ErrorDescription { get; }; + + // From the "error_uri" parameter of the error response. An optional parameter that, when set, specifies a URI + // identifying a human-readable webpage intended to assist the developer in understanding the error. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.2.1 and 4.2.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2.1 + Windows.Foundation.Uri ErrorUri { get; }; + + // From the "state" parameter of the error response. This property will always be set because a state value is + // always sent with the request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.2.1 and 4.2.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2.1 + String State { get; }; + + // Additional parameters set by the authorization server in the response URI. + Windows.Foundation.Collections.IMapView AdditionalParams { get; }; + } + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + runtimeclass AuthRequestResult + { + // The raw URI that was used to complete the request. + Windows.Foundation.Uri ResponseUri { get; }; + + // Non-null if the server's response indicates success, otherwise null + AuthResponse Response { get; }; + + // Non-null if the server's response indicates failure, otherwise null + AuthFailure Failure { get; }; + } + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + runtimeclass TokenRequestParams + { + // Construct with required parameters + TokenRequestParams(String grantType); + + // Helper method to create for an authorization code grant request ("authorization_code" grant type), + // initialized with the required parameters extracted from the authorization response, per RFC 6749 section + // 4.1.3. + static TokenRequestParams CreateForAuthorizationCodeRequest(AuthResponse authResponse); + + // Helper method to create for a resource owner password credentials grant request ("password" grant type), + // initialized with the required parameters, per RFC 6749 section 4.3.2. + static TokenRequestParams CreateForResourceOwnerPasswordCredentials(String username, String password); + + // Helper method to create for a client credentials grant request ("client_credentials" grant type), initialized + // with the required parameters, per RFC 6749 section 4.4.2. + static TokenRequestParams CreateForClientCredentials(); + + // Helper method to create for an extension grant request, using the provided URI for the grant type, per RFC + // 6749 section 4.5. + static TokenRequestParams CreateForExtension(Windows.Foundation.Uri extensionUri); + + // Helper method to create for an access token refresh request ("refresh_token" grant type), initialized with + // the required parameters, per RFC 6749 section 6. + static TokenRequestParams CreateForRefreshToken(String refreshToken); + + // Specifies the required "grant_type" parameter of the token request. This property is initialized by the + // creation function used ("authorization_code" for 'CreateForAuthorizationCodeRequest', "password" for + // 'CreateForResourceOwnerPasswordCredentials', "client_credentials" for 'CreateForClientCredentials', + // "refresh_token" for 'CreateForRefreshToken', or the specified URI for 'CreateForExtension'). + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.1.3, 4.3.2, 4.4.2, 4.5, and 6 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.4.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.5 + // https://www.rfc-editor.org/rfc/rfc6749#section-6 + String GrantType { get; set; }; + + // Specifies the "code" parameter of the token request. This property is required when the grant type is + // "authorization_code" and is initialized by 'CreateForAuthorizationCodeRequest'. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.1.3 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3 + String Code { get; set; }; + + // Specifies the "redirect_uri" parameter of the token request. This property is required when the grant type is + // "authorization_code" and a redirect URI was included in the authorization request. This property is + // initialized by 'CreateForAuthorizationCodeRequest'. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.1.3 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3 + Windows.Foundation.Uri RedirectUri { get; set; }; + + // Specifies the "code_verifier" parameter of the token request. This property is required when the grant type + // is "authorization_code" and a code challenge was included in the authorization request. This property is + // initialized by 'CreateForAuthorizationCodeRequest'. + // + // Defined by RFC 7636: Proof Key for Code Exchange by OAuth Public Clients, section 4.5 + // https://www.rfc-editor.org/rfc/rfc7636#section-4.5 + String CodeVerifier { get; set; }; + + // Specifies the "client_id" parameter of the token request. This property is required when the grant type is + // "authorization_code" and no alternative client authentication is specified. This property is initiated by + // 'CreateForAuthorizationCodeRequest'. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.1.3 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3 + String ClientId { get; set; }; + + // Specifies the "username" parameter of the token request. This property is required when the grant type is + // "password" and is initialized by 'CreateForResourceOwnerPasswordCredentials'. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.3.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2 + String Username { get; set; }; + + // Specifies the "password" parameter of the token request. This property is required when the grant type is + // "password" and is initialized by 'CreateForResourceOwnerPasswordCredentials'. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 4.3.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2 + String Password { get; set; }; + + // Specifies the "scope" parameter of the token request. This property is valid only when the grant type is + // "password", "client_credentials", or "refresh_token". + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, sections 4.3.2, 4.4.2, and 6 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-4.4.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-6 + String Scope { get; set; }; + + // Specifies the "refresh_token" parameter of the token request. This property is required when the grant type + // is "refresh_token" and is initialized by 'CreateForRefreshToken'. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 6 + // https://www.rfc-editor.org/rfc/rfc6749#section-6 + String RefreshToken { get; set; }; + + // Additional parameters passed along in the HTTP request entity-body. + Windows.Foundation.Collections.IMap AdditionalParams { get; }; + } + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + runtimeclass TokenResponse + { + // From the "access_token" parameter of the token response. A required property that should always be set. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 5.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-5.1 + String AccessToken { get; }; + + // From the "token_type" parameter of the token response. A required property that should always be set. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 5.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-5.1 + String TokenType { get; }; + + // From the "expires_in" parameter of the token response. An optional property that, when set, specifies the + // lifetime of the access token in seconds. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 5.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-5.1 + Double ExpiresIn { get; }; // TODO: DateTime? + + // From the "refresh_token" parameter of the token response. An optional property that, when set, can be used to + // obtain new access tokens using the same authorization grant provided during the request. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 5.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-5.1 + String RefreshToken { get; }; + + // From the "scope" parameter of the token response. An optional property that, when set, describes the scope of + // the access token issued by the authorization server. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 5.1 + // https://www.rfc-editor.org/rfc/rfc6749#section-5.1 + String Scope { get; }; + + // Additional parameters set by the authorization server in the token response. + Windows.Foundation.Collections.IMapView AdditionalParams { get; }; + } + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + enum TokenFailureKind + { + // The server responded with an error response as described by RFC 6749 section 5.2. This means that the failure + // object has an 'Error' string and possibly other specified properties. + ErrorResponse = 0, + + // The HTTP POST request failed. See the 'ErrorCode' property for more details as to why. + HttpFailure = 1, + + // The server responded, but its response was improperly formatted. This could be that the server did not send + // the response as JSON, the response JSON string was improperly formatted, or the response JSON contained + // unexpected object types (e.g. a number when a string is expected, etc.). + InvalidResponse = 2, + }; + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + runtimeclass TokenFailure + { + // Indicates the type of failure that this object describes, which will indicate which properties might be set. + TokenFailureKind Kind { get; }; + + // If 'Kind' was anything other than 'ErrorResponse', + HRESULT ErrorCode { get; }; + + // From the "error" parameter of the error response. The value of this property will map to a well known string + // specified in RFC 6749 section 5.2, or approved extensions. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 5.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-5.2 + String Error { get; }; + + // From the "error_description" parameter of the error response. An optional parameter that, when set, provides + // additional human-readable information intended to assist the developer in understanding the error. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 5.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-5.2 + String ErrorDescription { get; }; + + // From the "error_uri" parameter of the error response. An optional parameter that, when set, specifies a URI + // identifying a human-readable webpage intended to assist the developer in understanding the error. + // + // Defined by RFC 6749: The OAuth 2.0 Authorization Framework, section 5.2 + // https://www.rfc-editor.org/rfc/rfc6749#section-5.2 + Windows.Foundation.Uri ErrorUri { get; }; + + // Additional parameters set by the authorization server in the token response. + Windows.Foundation.Collections.IMapView AdditionalParams { get; }; + } + + [contract(OAuthContract, 1), feature(Feature_OAuth)] + runtimeclass TokenRequestResult + { + // The raw HTTP response that was used to complete the request + Windows.Web.Http.HttpResponseMessage ResponseMessage { get; }; + + // Non-null if the server's response indicates success, otherwise null + TokenResponse Response { get; }; + + // Non-null if the server's response indicates failure, otherwise null + TokenFailure Failure { get; }; + } +} diff --git a/dev/OAuth/OAuth.vcxitems b/dev/OAuth/OAuth.vcxitems new file mode 100644 index 0000000000..3f7dfc992f --- /dev/null +++ b/dev/OAuth/OAuth.vcxitems @@ -0,0 +1,88 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + {3E7FD510-8B66-40E7-A80B-780CB8972F83} + + + + %(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dev/OAuth/TokenFailure.cpp b/dev/OAuth/TokenFailure.cpp new file mode 100644 index 0000000000..58fc77cb70 --- /dev/null +++ b/dev/OAuth/TokenFailure.cpp @@ -0,0 +1,80 @@ +#include +#include "common.h" + +#include "TokenFailure.h" + +#include + +using namespace std::literals; +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Data::Json; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + TokenFailure::TokenFailure(TokenFailureKind kind, winrt::hresult code) : m_kind(kind), m_errorCode(code) {} + + TokenFailure::TokenFailure(const JsonObject& jsonObject) : + m_kind(TokenFailureKind::ErrorResponse), + m_errorCode(E_FAIL) + { + std::map additionalParams; + + // NOTE: Functions like 'GetString' will throw if the value is not the requested type, so the calling code must + // be ready to handle such failures + for (auto&& pair : jsonObject) + { + auto name = pair.Key(); + if (name == L"error"sv) + { + m_error = pair.Value().GetString(); + // TODO: Use the error string to set a more accurate HRESULT? + } + else if (name == L"error_description"sv) + { + m_errorDescription = pair.Value().GetString(); + } + else if (name == L"error_uri"sv) + { + m_errorUri = Uri(pair.Value().GetString()); + } + else + { + additionalParams.emplace(std::move(name), pair.Value()); + } + } + + m_additionalParams = winrt::single_threaded_map(std::move(additionalParams)).GetView(); + } + + TokenFailureKind TokenFailure::Kind() + { + return m_kind; + } + + winrt::hresult TokenFailure::ErrorCode() + { + return m_errorCode; + } + + winrt::hstring TokenFailure::Error() + { + return m_error; + } + + winrt::hstring TokenFailure::ErrorDescription() + { + return m_errorDescription; + } + + Uri TokenFailure::ErrorUri() + { + return m_errorUri; + } + + IMapView TokenFailure::AdditionalParams() + { + return m_additionalParams; + } +} diff --git a/dev/OAuth/TokenFailure.h b/dev/OAuth/TokenFailure.h new file mode 100644 index 0000000000..5a33bde7e0 --- /dev/null +++ b/dev/OAuth/TokenFailure.h @@ -0,0 +1,26 @@ +#pragma once +#include + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct TokenFailure : TokenFailureT + { + TokenFailure(TokenFailureKind kind, winrt::hresult code); + TokenFailure(const json::JsonObject& jsonObject); + + TokenFailureKind Kind(); + winrt::hresult ErrorCode(); + winrt::hstring Error(); + winrt::hstring ErrorDescription(); + foundation::Uri ErrorUri(); + collections::IMapView AdditionalParams(); + + private: + TokenFailureKind m_kind; + winrt::hresult m_errorCode; + winrt::hstring m_error; + winrt::hstring m_errorDescription; + foundation::Uri m_errorUri{ nullptr }; + collections::IMapView m_additionalParams; + }; +} diff --git a/dev/OAuth/TokenRequestParams.cpp b/dev/OAuth/TokenRequestParams.cpp new file mode 100644 index 0000000000..5d8925568f --- /dev/null +++ b/dev/OAuth/TokenRequestParams.cpp @@ -0,0 +1,237 @@ +#include +#include "common.h" + +#include "AuthResponse.h" +#include "TokenRequestParams.h" + +#include + +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Foundation; +using namespace Collections; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + TokenRequestParams::TokenRequestParams(const winrt::hstring& grantType) : m_grantType(grantType) + { + THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::Security::Authentication::OAuth::Feature_OAuth::IsEnabled()); + } + + oauth::TokenRequestParams TokenRequestParams::CreateForAuthorizationCodeRequest( + const oauth::AuthResponse& authResponse) + { + auto result = winrt::make_self(L"authorization_code"); + result->m_code = authResponse.Code(); + + auto implResponse = winrt::get_self(authResponse); + if (auto redirectUri = implResponse->request_params()->RedirectUri()) + { + result->m_redirectUri = std::move(redirectUri); + } + + if (auto clientId = implResponse->request_params()->ClientId(); !clientId.empty()) + { + result->m_clientId = std::move(clientId); + } + + if (auto codeVerifier = implResponse->request_params()->CodeVerifier(); !codeVerifier.empty()) + { + result->m_codeVerifier = std::move(codeVerifier); + } + + return *result; + } + + oauth::TokenRequestParams TokenRequestParams::CreateForResourceOwnerPasswordCredentials( + const winrt::hstring& username, const winrt::hstring& password) + { + auto result = winrt::make_self(L"password"); + result->m_username = username; + result->m_password = password; + + return *result; + } + + oauth::TokenRequestParams TokenRequestParams::CreateForClientCredentials() + { + return winrt::make(L"client_credentials"); + } + + oauth::TokenRequestParams TokenRequestParams::CreateForExtension(const Uri& extensionUri) + { + return winrt::make(extensionUri.RawUri()); + } + + oauth::TokenRequestParams TokenRequestParams::CreateForRefreshToken(const winrt::hstring& refreshToken) + { + auto result = winrt::make_self(L"refresh_token"); + result->m_refreshToken = refreshToken; + + return *result; + } + + winrt::hstring TokenRequestParams::GrantType() + { + std::shared_lock guard{ m_mutex }; + return m_grantType; + } + + void TokenRequestParams::GrantType(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_grantType = value; + } + + winrt::hstring TokenRequestParams::Code() + { + std::shared_lock guard{ m_mutex }; + return m_code; + } + + void TokenRequestParams::Code(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_code = value; + } + + Uri TokenRequestParams::RedirectUri() + { + std::shared_lock guard{ m_mutex }; + return m_redirectUri; + } + + void TokenRequestParams::RedirectUri(const Uri& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_redirectUri = value; + } + + winrt::hstring TokenRequestParams::CodeVerifier() + { + std::shared_lock guard{ m_mutex }; + return m_codeVerifier; + } + + void TokenRequestParams::CodeVerifier(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_codeVerifier = value; + } + + winrt::hstring TokenRequestParams::ClientId() + { + std::shared_lock guard{ m_mutex }; + return m_clientId; + } + + void TokenRequestParams::ClientId(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_clientId = value; + } + + winrt::hstring TokenRequestParams::Username() + { + std::shared_lock guard{ m_mutex }; + return m_username; + } + + void TokenRequestParams::Username(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_username = value; + } + + winrt::hstring TokenRequestParams::Password() + { + std::shared_lock guard{ m_mutex }; + return m_password; + } + + void TokenRequestParams::Password(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_password = value; + } + + winrt::hstring TokenRequestParams::Scope() + { + std::shared_lock guard{ m_mutex }; + return m_scope; + } + + void TokenRequestParams::Scope(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_scope = value; + } + + winrt::hstring TokenRequestParams::RefreshToken() + { + std::shared_lock guard{ m_mutex }; + return m_refreshToken; + } + + void TokenRequestParams::RefreshToken(const winrt::hstring& value) + { + std::lock_guard guard{ m_mutex }; + check_not_finalized(); + m_refreshToken = value; + } + + IMap TokenRequestParams::AdditionalParams() + { + std::shared_lock guard{ m_mutex }; + return *m_additionalParams; + } + + void TokenRequestParams::finalize() + { + std::lock_guard guard{ m_mutex }; + if (m_finalized) + { + throw winrt::hresult_illegal_method_call(L"TokenRequestParams can only be used for a single request call"); + } + + m_finalized = true; + m_additionalParams->lock(); + } + + std::map TokenRequestParams::params() + { + // HttpFormUrlEncodedContent requires an IIterable> as input. In theory we can + // make the TokenRequestParams implement this type to save on some work, however this may be a little tricky + std::map result; + auto addIfSet = [&](std::wstring_view key, const winrt::hstring& value) { + if (!value.empty()) + { + result.emplace(key, value); + } + }; + + std::shared_lock guard{ m_mutex }; + addIfSet(L"grant_type", m_grantType); + addIfSet(L"code", m_code); + if (m_redirectUri) result.emplace(L"redirect_uri", m_redirectUri.RawUri()); + addIfSet(L"code_verifier", m_codeVerifier); + addIfSet(L"client_id", m_clientId); + addIfSet(L"username", m_username); + addIfSet(L"password", m_password); + addIfSet(L"scope", m_scope); + addIfSet(L"refresh_token", m_refreshToken); + for (auto&& pair : IMap{ *m_additionalParams }) + { + result.emplace(pair.Key(), pair.Value()); + } + + return result; + } +} diff --git a/dev/OAuth/TokenRequestParams.h b/dev/OAuth/TokenRequestParams.h new file mode 100644 index 0000000000..b6aa5dade7 --- /dev/null +++ b/dev/OAuth/TokenRequestParams.h @@ -0,0 +1,78 @@ +#pragma once +#include + +#include + +#include "LockableMap.h" + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct TokenRequestParams : TokenRequestParamsT + { + TokenRequestParams() = default; + TokenRequestParams(const winrt::hstring& grantType); + + static oauth::TokenRequestParams CreateForAuthorizationCodeRequest(const oauth::AuthResponse& authResponse); + static oauth::TokenRequestParams CreateForResourceOwnerPasswordCredentials(const winrt::hstring& username, + const winrt::hstring& password); + static oauth::TokenRequestParams CreateForClientCredentials(); + static oauth::TokenRequestParams CreateForExtension(const foundation::Uri& extensionUri); + static oauth::TokenRequestParams CreateForRefreshToken(const winrt::hstring& refreshToken); + + winrt::hstring GrantType(); + void GrantType(const winrt::hstring& value); + winrt::hstring Code(); + void Code(const winrt::hstring& value); + foundation::Uri RedirectUri(); + void RedirectUri(const foundation::Uri& value); + winrt::hstring CodeVerifier(); + void CodeVerifier(const winrt::hstring& value); + winrt::hstring ClientId(); + void ClientId(const winrt::hstring& value); + winrt::hstring Username(); + void Username(const winrt::hstring& value); + winrt::hstring Password(); + void Password(const winrt::hstring& value); + winrt::hstring Scope(); + void Scope(const winrt::hstring& value); + winrt::hstring RefreshToken(); + void RefreshToken(const winrt::hstring& value); + collections::IMap AdditionalParams(); + + // Implementation functions + void finalize(); + std::map params(); + + private: + void check_not_finalized() + { + // NOTE: Lock should be held when calling + if (m_finalized) + { + throw winrt::hresult_illegal_method_call( + L"TokenRequestParams object cannot be modified after being used to initiate a request"); + } + } + + std::shared_mutex m_mutex; + bool m_finalized = false; + winrt::hstring m_grantType; + winrt::hstring m_code; + foundation::Uri m_redirectUri{ nullptr }; + winrt::hstring m_codeVerifier; + winrt::hstring m_clientId; + winrt::hstring m_username; + winrt::hstring m_password; + winrt::hstring m_scope; + winrt::hstring m_refreshToken; + winrt::com_ptr> m_additionalParams = + winrt::make_self>(); + }; +} + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::factory_implementation +{ + struct TokenRequestParams : TokenRequestParamsT + { + }; +} diff --git a/dev/OAuth/TokenRequestResult.cpp b/dev/OAuth/TokenRequestResult.cpp new file mode 100644 index 0000000000..b2515f2570 --- /dev/null +++ b/dev/OAuth/TokenRequestResult.cpp @@ -0,0 +1,47 @@ +#include +#include "common.h" + +#include "TokenFailure.h" +#include "TokenRequestResult.h" +#include "TokenResponse.h" + +#include + +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Data::Json; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; +using namespace winrt::Windows::Web::Http; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + TokenRequestResult::TokenRequestResult(HttpResponseMessage responseMessage, oauth::TokenResponse response, + oauth::TokenFailure failure) : + m_responseMessage(std::move(responseMessage)), + m_response(std::move(response)), + m_failure(std::move(failure)) + { + } + + oauth::TokenRequestResult TokenRequestResult::MakeFailure(HttpResponseMessage response, + TokenFailureKind failureKind, winrt::hresult failureCode) + { + return winrt::make(std::move(response), nullptr, + winrt::make(failureKind, failureCode)); + } + + HttpResponseMessage TokenRequestResult::ResponseMessage() + { + return m_responseMessage; + } + + oauth::TokenResponse TokenRequestResult::Response() + { + return m_response; + } + + oauth::TokenFailure TokenRequestResult::Failure() + { + return m_failure; + } +} diff --git a/dev/OAuth/TokenRequestResult.h b/dev/OAuth/TokenRequestResult.h new file mode 100644 index 0000000000..b8df9fb30b --- /dev/null +++ b/dev/OAuth/TokenRequestResult.h @@ -0,0 +1,23 @@ +#pragma once +#include + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct TokenRequestResult : TokenRequestResultT + { + TokenRequestResult(http::HttpResponseMessage responseMessage, oauth::TokenResponse resposne, + oauth::TokenFailure failure); + + static oauth::TokenRequestResult MakeFailure(http::HttpResponseMessage response, TokenFailureKind failureKind, + winrt::hresult failureCode); + + http::HttpResponseMessage ResponseMessage(); + oauth::TokenResponse Response(); + oauth::TokenFailure Failure(); + + private: + http::HttpResponseMessage m_responseMessage; + oauth::TokenResponse m_response{ nullptr }; + oauth::TokenFailure m_failure{ nullptr }; + }; +} diff --git a/dev/OAuth/TokenResponse.cpp b/dev/OAuth/TokenResponse.cpp new file mode 100644 index 0000000000..35b6196756 --- /dev/null +++ b/dev/OAuth/TokenResponse.cpp @@ -0,0 +1,82 @@ +#include +#include "common.h" + +#include "TokenResponse.h" + +#include + +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Data::Json; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + TokenResponse::TokenResponse(const json::JsonObject& jsonObject) + { + std::map additionalParams; + + // NOTE: Functions like 'GetString' will throw if the value is not the requested type. It might be worth + // revisiting this in the future + for (auto&& pair : jsonObject) + { + auto name = pair.Key(); + if (name == L"access_token") + { + m_accessToken = pair.Value().GetString(); + } + else if (name == L"token_type") + { + m_tokenType = pair.Value().GetString(); + } + else if (name == L"expires_in") + { + m_expiresIn = pair.Value().GetNumber(); + } + else if (name == L"refresh_token") + { + m_refreshToken = pair.Value().GetString(); + } + else if (name == L"scope") + { + m_scope = pair.Value().GetString(); + } + else + { + additionalParams.emplace(std::move(name), pair.Value()); + } + } + + m_additionalParams = winrt::single_threaded_map(std::move(additionalParams)).GetView(); + } + + winrt::hstring TokenResponse::AccessToken() + { + return m_accessToken; + } + + winrt::hstring TokenResponse::TokenType() + { + return m_tokenType; + } + + double TokenResponse::ExpiresIn() + { + return m_expiresIn; + } + + winrt::hstring TokenResponse::RefreshToken() + { + return m_refreshToken; + } + + winrt::hstring TokenResponse::Scope() + { + return m_scope; + } + + IMapView TokenResponse::AdditionalParams() + { + return m_additionalParams; + } +} diff --git a/dev/OAuth/TokenResponse.h b/dev/OAuth/TokenResponse.h new file mode 100644 index 0000000000..ccef9e5cce --- /dev/null +++ b/dev/OAuth/TokenResponse.h @@ -0,0 +1,25 @@ +#pragma once +#include + +namespace winrt::Microsoft::Windows::Security::Authentication::OAuth::implementation +{ + struct TokenResponse : TokenResponseT + { + TokenResponse(const json::JsonObject& jsonObject); + + winrt::hstring AccessToken(); + winrt::hstring TokenType(); + double ExpiresIn(); + winrt::hstring RefreshToken(); + winrt::hstring Scope(); + collections::IMapView AdditionalParams(); + + private: + winrt::hstring m_accessToken; + winrt::hstring m_tokenType; + double m_expiresIn; + winrt::hstring m_refreshToken; + winrt::hstring m_scope; + collections::IMapView m_additionalParams; + }; +} diff --git a/dev/OAuth/common.h b/dev/OAuth/common.h new file mode 100644 index 0000000000..c04d6f3416 --- /dev/null +++ b/dev/OAuth/common.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace collections = winrt::Windows::Foundation::Collections; +namespace crypto = winrt::Windows::Security::Cryptography; +namespace foundation = winrt::Windows::Foundation; +namespace http = winrt::Windows::Web::Http; +namespace json = winrt::Windows::Data::Json; +namespace oauth = winrt::Microsoft::Windows::Security::Authentication::OAuth; +namespace streams = winrt::Windows::Storage::Streams; + +#include "Crypto.h" + +inline winrt::hstring fragment_component(const foundation::Uri& uri) +{ + auto fragment = uri.Fragment(); + std::wstring_view fragmentStr = fragment; + if (!fragmentStr.empty()) + { + WINRT_ASSERT(fragmentStr.front() == '#'); + fragmentStr = fragmentStr.substr(1); + } + + return winrt::hstring(fragmentStr); +} diff --git a/dev/Projections/CS/Microsoft.Windows.Security.Authentication.OAuth/Microsoft.Windows.Security.Authentication.OAuth.Projection.csproj b/dev/Projections/CS/Microsoft.Windows.Security.Authentication.OAuth/Microsoft.Windows.Security.Authentication.OAuth.Projection.csproj new file mode 100644 index 0000000000..401aeaaa1a --- /dev/null +++ b/dev/Projections/CS/Microsoft.Windows.Security.Authentication.OAuth/Microsoft.Windows.Security.Authentication.OAuth.Projection.csproj @@ -0,0 +1,50 @@ + + + net6.0-windows10.0.17763.0 + 10.0.17763.0 + x64;x86;arm64 + AnyCPU + + + + true + true + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + Microsoft.Windows.Security.Authentication.OAuth + 10.0.17763.0 + 10.0.17763.$(CsWinRTDependencyWindowsSdkVersionSuffixPackageVersion) + false + + + + + pdbonly + true + + + + + + + + + $(OutDir)..\WindowsAppRuntime_DLL\StrippedWinMD\Microsoft.Windows.Security.Authentication.OAuth.winmd + true + + + + diff --git a/dev/WindowsAppRuntime_DLL/WindowsAppRuntime_DLL.vcxproj b/dev/WindowsAppRuntime_DLL/WindowsAppRuntime_DLL.vcxproj index 9ebf07e65a..9199a4ce75 100644 --- a/dev/WindowsAppRuntime_DLL/WindowsAppRuntime_DLL.vcxproj +++ b/dev/WindowsAppRuntime_DLL/WindowsAppRuntime_DLL.vcxproj @@ -96,6 +96,7 @@ + diff --git a/docs/Coding-Guidelines/Experimental.md b/docs/Coding-Guidelines/Experimental.md index 5a76bdeeb2..fc47bd5785 100644 --- a/docs/Coding-Guidelines/Experimental.md +++ b/docs/Coding-Guidelines/Experimental.md @@ -14,7 +14,7 @@ The implementation of experimental features in Windows App SDK makes heavy use o in different release channels. See the TerminalVelocity document for detailed information on how to implement an experimental feature using a specific technology (e.g. C++, IDL, WinRT). -Your should ensure that your feature's state is disabled in Preview and Stable release channels, and +You should ensure that your feature's state is disabled in Preview and Stable release channels, and enabled in the Experimental release channel. # Stripping experimental APIs from WinRT metadata (.winmd) diff --git a/specs/WinRT/WinRTAPIContracts.md b/specs/WinRT/WinRTAPIContracts.md index a5fc7cd562..639633cf49 100644 --- a/specs/WinRT/WinRTAPIContracts.md +++ b/specs/WinRT/WinRTAPIContracts.md @@ -111,6 +111,7 @@ The list of all contracts defined across Windows App SDK | MRTCore | windowsappsdk | MrtCoreContract | Microsoft.Windows.ApplicationModel.Resources | | | PowerNotifications | windowsappsdk | PowerNotificationsContract | Microsoft.Windows.System.Power | | | PushNotifications | windowsappsdk | PushNotificationsContract | Microsoft.Windows.PushNotifications | | +| OAuth | windowsappsdk | OAuthContract | Microsoft.Windows.Security.Authentication.OAuth | | | WinUI | winui | HostingContract | Microsoft.UI.Xaml.Hosting | | | WinUI | winui | WinUIContract | Microsoft.UI.Xaml | | | WinUI | winui | WinUIControlsContract | Microsoft.UI.Xaml.Controls | | diff --git a/test/Deployment/data/WindowsAppRuntime.Test.Framework/appxmanifest.xml b/test/Deployment/data/WindowsAppRuntime.Test.Framework/appxmanifest.xml index a3c742d4a2..54a6121065 100644 --- a/test/Deployment/data/WindowsAppRuntime.Test.Framework/appxmanifest.xml +++ b/test/Deployment/data/WindowsAppRuntime.Test.Framework/appxmanifest.xml @@ -106,5 +106,14 @@ + + + Microsoft.WindowsAppRuntime.dll + + + + + + diff --git a/test/DynamicDependency/data/Microsoft.WindowsAppRuntime.Framework/appxmanifest.xml b/test/DynamicDependency/data/Microsoft.WindowsAppRuntime.Framework/appxmanifest.xml index 6c640829b6..9c9b2ab1e8 100644 --- a/test/DynamicDependency/data/Microsoft.WindowsAppRuntime.Framework/appxmanifest.xml +++ b/test/DynamicDependency/data/Microsoft.WindowsAppRuntime.Framework/appxmanifest.xml @@ -94,6 +94,15 @@ + + + Microsoft.WindowsAppRuntime.dll + + + + + + Microsoft.WindowsAppRuntime.dll diff --git a/test/OAuthTests/OAuthTestValues.h b/test/OAuthTests/OAuthTestValues.h new file mode 100644 index 0000000000..f35569343f --- /dev/null +++ b/test/OAuthTests/OAuthTestValues.h @@ -0,0 +1,114 @@ +#pragma once + +#include +#include + +#include +#include + +// The 'client_id' describes the behavior and expectations of our mocked authorization server +// Specifying grant type is required +#define GRANT_TYPE_CODE L"grant=code" +#define GRANT_TYPE_TOKEN L"grant=token" +#define GRANT_TYPE_PASSWORD L"grant=password" +#define GRANT_TYPE_CLIENT L"grant=client" +#define GRANT_TYPE_REFRESH L"grant=refresh" +#define GRANT_TYPE_EXTENSION L"grant=extension" + +// Specifying redirect type is required +#define REDIRECT_TYPE_LOCALHOST "&redirect=localhost" +#define REDIRECT_TYPE_PROTOCOL "&redirect=protocol" +#define REDIRECT_TYPE_INFERRED "&redirect=inferred" + +// 'S256' is the default if not specified +#define PKCE_TYPE_S256 "&pkce=S256" +#define PKCE_TYPE_PLAIN "&pkce=plain" +#define PKCE_TYPE_NONE "&pkce=none" + +// 'none' is the default if not specified +#define SCOPE_TYPE_NONE "&scope=none" +#define SCOPE_TYPE_SINGLE "&scope=single" +#define SCOPE_TYPE_MULTIPLE "&scope=multiple" + +// 'none' is the default if not specified +#define AUTH_TYPE_NONE "&auth=none" +#define AUTH_TYPE_HEADER "&auth=header" + +// 'none' is the default if not specified +#define NO_ERROR_RESPONSE "&error=none" +#define AUTH_ERROR_RESPONSE "&error=auth" +#define TOKEN_ERROR_RESPONSE "&error=token" + +// 'true' is the default if not specified +#define COMPLETE_REQUEST "&complete=true" +#define DONT_COMPLETE_REQUEST "&complete=false" + +// 'false' is the default if not specified +#define NO_ADDITIONAL_PARAMS "&additional_params=false" +#define ADDITIONAL_PARAMS "&additional_params=true" + +// 'false' is the default if not specified +#define NO_AUTH_URL_QUERY_STRING "&query=false" +#define AUTH_URL_QUERY_STRING "&query=true" + +// Constants to validate expectations. The strings are specifically chosen to validate proper escaping of special characters +inline constexpr std::wstring_view error_description = L"This is an error & it contains characters like \"=\""; +inline constexpr std::wstring_view json_escaped_error_description = L"This is an error & it contains characters like \\\"=\\\""; +inline constexpr std::wstring_view error_uri = L"https://contoso.com/errors?foo=bar"; + +inline constexpr std::wstring_view additional_param_key = L"use=key&name=foo"; +inline constexpr std::wstring_view additional_param_value = L"use=value&name=bar"; + +inline constexpr std::wstring_view extension_grant_uri = L"oauth:test:extension"; + +inline constexpr std::wstring_view single_scope = L"foo=bar?"; +inline constexpr std::wstring_view multiple_scope = L"foo=bar? &\"foobar\""; + +inline constexpr std::wstring_view token = L"tacos=yummy&location=\"my tummy\""; +inline constexpr std::wstring_view json_escaped_token = L"tacos=yummy&location=\\\"my tummy\\\""; +inline constexpr std::wstring_view refresh_token_old = L"~!@#$%^&*()_+`-=[]\\{};':\",./<>?-old"; +inline constexpr std::wstring_view refresh_token = L"~!@#$%^&*()_+`-=[]\\{};':\",./<>?"; +inline constexpr std::wstring_view json_escaped_refresh_token = L"~!@#$%^&*()_+`-=[]\\\\{};':\\\",./<>?"; + +struct uri_builder +{ + std::wstring uri; + wchar_t prefix; + + uri_builder(const winrt::Windows::Foundation::Uri& uri, bool useQuery = true) : + uri(uri.RawUri()) + { + if (useQuery) + { + prefix = uri.Query().empty() ? L'?' : '&'; + } + else + { + prefix = '#'; + } + } + + void add(std::wstring_view name, std::wstring_view value) + { + assert(!name.empty() && !value.empty()); + + uri.push_back(prefix); + prefix = L'&'; + uri.append(winrt::Windows::Foundation::Uri::EscapeComponent(name)); + uri.push_back(L'='); + uri.append(winrt::Windows::Foundation::Uri::EscapeComponent(value)); + } + + void add_optional(std::wstring_view name, std::wstring_view value) + { + if (!value.empty()) + { + add(name, value); + } + } + + winrt::Windows::Foundation::Uri get() + { + return winrt::Windows::Foundation::Uri{ uri }; + } +}; diff --git a/test/OAuthTests/OAuthTests.cpp b/test/OAuthTests/OAuthTests.cpp new file mode 100644 index 0000000000..b8997eb055 --- /dev/null +++ b/test/OAuthTests/OAuthTests.cpp @@ -0,0 +1,1492 @@ + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "OAuthTestValues.h" + +// NOTE: Thise files don't include verything they need, hence they are here last +#include +#include + +#include // Included last to enable the most features + +using namespace std::literals; +using namespace WEX::Common; +using namespace WEX::Logging; +using namespace WEX::TestExecution; +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::Data::Json; +using namespace winrt::Windows::Foundation; +using namespace winrt::Windows::Foundation::Collections; +using namespace winrt::Windows::Security::Cryptography; +using namespace winrt::Windows::Security::Cryptography::Core; +using namespace winrt::Windows::Storage::Streams; + +EXTERN_C IMAGE_DOS_HEADER __ImageBase; + +struct OAuthTests +{ + BEGIN_TEST_CLASS(OAuthTests) + TEST_CLASS_PROPERTY(L"ThreadingModel", L"MTA") + END_TEST_CLASS() + + TEST_CLASS_SETUP(Setup) + { + if (!::Microsoft::Windows::Security::Authentication::OAuth::Feature_OAuth::IsEnabled()) + { + Log::Result(TestResults::Skipped, L"OAuth API Features are not enabled."); + return true; + } + + Test::Bootstrap::Setup(); + + Test::Packages::WapProj::AddPackage(Test::TAEF::GetDeploymentDir(), L"OAuthTestAppPackage", L".msix"); + + // Detour ShellExecuteW + ::DetourTransactionBegin(); + ::DetourUpdateThread(::GetCurrentThread()); + if (auto err = ::DetourAttach(reinterpret_cast(&RealShellExecuteW), &DetouredShellExecuteW)) + { + Log::Error(WEX::Common::String().Format(L"DetourAttach failed: %d", err)); + ::DetourTransactionAbort(); + return false; + } + ::DetourTransactionCommit(); + + // Initialize the HTTP server we use for token requests + VERIFY_WIN32_SUCCEEDED(::HttpInitialize(HTTPAPI_VERSION_2, HTTP_INITIALIZE_SERVER, nullptr)); + VERIFY_WIN32_SUCCEEDED(::HttpCreateRequestQueue(HTTPAPI_VERSION_2, nullptr, nullptr, 0, &m_requestQueue)); + VERIFY_WIN32_SUCCEEDED(::HttpCreateServerSession(HTTPAPI_VERSION_2, &m_serverSessionId, 0)); + VERIFY_WIN32_SUCCEEDED(::HttpCreateUrlGroup(m_serverSessionId, &m_urlGroup, 0)); + + HTTP_BINDING_INFO bindingInfo = {}; + bindingInfo.Flags.Present = 1; + bindingInfo.RequestQueueHandle = m_requestQueue; + VERIFY_WIN32_SUCCEEDED(::HttpSetUrlGroupProperty(m_urlGroup, HttpServerBindingProperty, &bindingInfo, + static_cast(sizeof(bindingInfo)))); + + // Find an open port; note that ports in the low 50000s are frequently claimed, hence the large iteration bounds + ULONG err = 0; + for (std::uint16_t i = 0; i < 500; ++i) + { + wchar_t buffer[18 + 5 + 1]; + std::swprintf(buffer, std::size(buffer), L"http://127.0.0.1:%d/", m_serverPort); + + err = ::HttpAddUrlToUrlGroup(m_urlGroup, buffer, 0, 0); + if (err == NO_ERROR) + { + m_serverUrlBase = buffer; + break; + } + + ++m_serverPort; + } + + VERIFY_WIN32_SUCCEEDED(err, L"Looking for an open port"); + m_httpServerThread = std::thread([this] { + RunHttpServer(); + }); + + return true; + } + + TEST_CLASS_CLEANUP(Cleanup) + { + Test::Packages::RemovePackage(L"OAuthTestAppPackage_1.0.0.0_" WINDOWSAPPRUNTIME_TEST_PACKAGE_DDLM_ARCHITECTURE L"__8wekyb3d8bbwe"); + + // Tear down the HTTP server + m_serverShutdownEvent.SetEvent(); + m_httpServerThread.join(); + + if (m_urlGroup) + { + ::HttpCloseUrlGroup(m_urlGroup); + m_urlGroup = 0; + } + + if (m_serverSessionId) + { + ::HttpCloseServerSession(m_serverSessionId); + m_serverSessionId = 0; + } + + if (m_requestQueue) + { + ::HttpCloseRequestQueue(m_requestQueue); + m_requestQueue = nullptr; + } + + ::HttpTerminate(HTTP_INITIALIZE_SERVER, nullptr); + + // Clean up our detours + ::DetourTransactionBegin(); + ::DetourUpdateThread(::GetCurrentThread()); + ::DetourDetach(reinterpret_cast(&RealShellExecuteW), &DetouredShellExecuteW); + ::DetourTransactionCommit(); + + Test::Bootstrap::Cleanup(); + + return true; + } + + template + static void WaitWithTimeout(const IAsyncOperation& op, AsyncStatus expectedStatus) + { + wil::unique_event event(wil::EventOptions::None); + op.Completed([event = event.get()](const IAsyncOperation&, AsyncStatus) { + ::SetEvent(event); + }); + + // 10 seconds is beyond + if (::WaitForSingleObject(event.get(), 1000) == WAIT_OBJECT_0) + { + VERIFY_ARE_EQUAL(expectedStatus, op.Status()); + return; + } + + Log::Warning(L"Timed out waiting for IAsyncOperation to complete; cancelling..."); + op.Cancel(); + + // Cancel should cause the operation to complete with the cancellation + if (::WaitForSingleObject(event.get(), 1000) != WAIT_OBJECT_0) + { + // Lambda holds a reference to the event. Best just to leak it here + Log::Warning(L"Failed to cancel IAsyncOperation; leaking event"); + event.release(); + } + + VERIFY_FAIL(L"IAsyncOperation did not complete in a reasonable amount of time"); + } + + template + static void VerifyErrorNull(const ErrorT& error) + { + if (error) + { + Log::Error(WEX::Common::String().Format(L"Error object expected to be null! Message: %ls", + error.ErrorDescription().c_str())); + } + VERIFY_IS_NULL(error); + } + + AuthResponse InitiateAndWaitForSuccessfulAuthResponse(const AuthRequestParams& params) + { + auto op = AuthManager::InitiateAuthRequestAsync(Uri{ auth_url }, params); + WaitWithTimeout(op, AsyncStatus::Completed); + + auto result = op.GetResults(); + VerifyErrorNull(result.Failure()); + + auto response = result.Response(); + VERIFY_IS_NOT_NULL(response); + VERIFY_ARE_EQUAL(params.State(), response.State()); + + return response; + } + + TokenResponse RequestTokenAndWaitForSuccessfulResponse(const TokenRequestParams& params, const ClientAuthentication& auth = { nullptr }) + { + IAsyncOperation op{ nullptr }; + if (auth) + { + op = AuthManager::RequestTokenAsync(Uri{ m_serverUrlBase + L"token" }, params, auth); + } + else + { + op = AuthManager::RequestTokenAsync(Uri{ m_serverUrlBase + L"token" }, params); + } + WaitWithTimeout(op, AsyncStatus::Completed); + + auto result = op.GetResults(); + VerifyErrorNull(result.Failure()); + + auto response = result.Response(); + VERIFY_IS_NOT_NULL(response); + VERIFY_ARE_EQUAL(token, response.AccessToken()); + VERIFY_ARE_EQUAL(L"Bearer", response.TokenType()); + VERIFY_ARE_EQUAL(3600, response.ExpiresIn()); + VERIFY_ARE_EQUAL(refresh_token, response.RefreshToken()); + VERIFY_ARE_EQUAL(L"all", response.Scope()); + + return response; + } + + static inline constexpr std::wstring_view auth_url = L"http://oauthtests.com/oauth"sv; + + // Redirect URIs + static inline constexpr std::wstring_view localhost_redirect_uri = L"http://127.0.0.1/oauth"sv; + static inline constexpr std::wstring_view protocol_redirect_uri = L"oauthtestapp:oauth"sv; + + void DoEndToEndAuthCodeTest(const AuthRequestParams& requestParams) + { + auto authResponse = InitiateAndWaitForSuccessfulAuthResponse(requestParams); + VERIFY_IS_FALSE(authResponse.Code().empty()); + + auto tokenParams = TokenRequestParams::CreateForAuthorizationCodeRequest(authResponse); + RequestTokenAndWaitForSuccessfulResponse(tokenParams); + } + + void DoBasicEndToEndAuthCodeTest(std::wstring_view clientId, std::wstring_view redirectUri) + { + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(clientId, Uri{ redirectUri }); + DoEndToEndAuthCodeTest(requestParams); + } + + TEST_METHOD(Localhost_AuthorizationCode_BasicEndToEnd) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST; + DoBasicEndToEndAuthCodeTest(client_id, localhost_redirect_uri); + } + + TEST_METHOD(Protocol_AuthorizationCode_BasicEndToEnd) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_PROTOCOL; + DoBasicEndToEndAuthCodeTest(client_id, protocol_redirect_uri); + } + + TEST_METHOD(Implicit_BasicEndToEnd) + { + // NOTE: Responses for implicit requests are communicated via the URI fragment, meaning that in practice, an + // application would need code running in the browser. This effectively requires running a simple HTTP server, + // at which point the application can just recover the full URI for itself and does not need to use protocol + // activation, so there's no major reason to test it. That code path would be virtually identical to the auth + // code scenarios, so there's even more reason to avoid exploding out the number of test cases + static constexpr std::wstring_view client_id = GRANT_TYPE_TOKEN REDIRECT_TYPE_LOCALHOST PKCE_TYPE_NONE; + auto requestParams = AuthRequestParams::CreateForImplicitRequest(client_id, Uri{ localhost_redirect_uri }); + auto requestResponse = InitiateAndWaitForSuccessfulAuthResponse(requestParams); + + VERIFY_ARE_EQUAL(token, requestResponse.AccessToken()); + VERIFY_ARE_EQUAL(L"Bearer", requestResponse.TokenType()); + VERIFY_ARE_EQUAL(L"3600", requestResponse.ExpiresIn()); + VERIFY_ARE_EQUAL(L"all", requestResponse.Scope()); + } + + void DoChallengeMethodPlainTest(std::wstring_view clientId, std::wstring_view redirectUri) + { + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(clientId, Uri{ redirectUri }); + requestParams.CodeChallengeMethod(CodeChallengeMethodKind::Plain); + DoEndToEndAuthCodeTest(requestParams); + } + + TEST_METHOD(Localhost_ChallengeMethodPlain) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST PKCE_TYPE_PLAIN; + DoChallengeMethodPlainTest(client_id, localhost_redirect_uri); + } + + TEST_METHOD(Protocol_ChallengeMethodPlain) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_PROTOCOL PKCE_TYPE_PLAIN; + DoChallengeMethodPlainTest(client_id, protocol_redirect_uri); + } + + void DoChallengeMethodNoneTest(std::wstring_view clientId, std::wstring_view redirectUri) + { + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(clientId, Uri{ redirectUri }); + requestParams.CodeChallengeMethod(CodeChallengeMethodKind::None); + DoEndToEndAuthCodeTest(requestParams); + } + + TEST_METHOD(Localhost_ChallengeMethodNone) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST PKCE_TYPE_NONE; + DoChallengeMethodNoneTest(client_id, localhost_redirect_uri); + } + + TEST_METHOD(Protocol_ChallengeMethodNone) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_PROTOCOL PKCE_TYPE_NONE; + DoChallengeMethodNoneTest(client_id, protocol_redirect_uri); + } + + void DoCustomStateAuthCodeTest(std::wstring_view clientId, std::wstring_view redirectUri) + { + auto runTest = [&](std::wstring_view state) { + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(clientId, Uri{ redirectUri }); + requestParams.State(state); + InitiateAndWaitForSuccessfulAuthResponse(requestParams); + }; + + // AES needs a key of size 16, 24, or 32 bytes. Test with states between each of these sizes to ensure we pad + // correctly + runTest(L"=?-_/"); // 5 bytes + runTest(L"!@#$%^&*()-=_+/\\"); // 16 bytes + runTest(L"!@#$%^&*()-=_+[]{};/"); // 20 bytes + runTest(L"!@#$%^&*()_+-=[]{};',./~"); // 24 bytes + runTest(L"!@#$%^&*()_+-=[]{};',./<>?`~"); // 28 bytes + runTest(L"!@#$%^&*()_+-=[]{};',./<>?:\"`~|\\"); // 32 bytes + runTest(L"!@#$%^&*()_+-=[]{};',./<>?:\"`~|\\abc123"); // 38 bytes + } + + TEST_METHOD(Localhost_AuthorizationCode_CustomState) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST; + DoCustomStateAuthCodeTest(client_id, localhost_redirect_uri); + } + + TEST_METHOD(Protocol_AuthorizationCode_CustomState) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_PROTOCOL; + DoCustomStateAuthCodeTest(client_id, protocol_redirect_uri); + } + + TEST_METHOD(AuthorizationCode_InferredRedirectUri) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_INFERRED; + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(client_id); + auto authResponse = InitiateAndWaitForSuccessfulAuthResponse(requestParams); + + auto tokenParams = TokenRequestParams::CreateForAuthorizationCodeRequest(authResponse); + RequestTokenAndWaitForSuccessfulResponse(tokenParams); + } + + void DoImplicitCustomScopeTest(std::wstring_view clientId, std::wstring_view scope) + { + auto requestParams = AuthRequestParams::CreateForImplicitRequest(clientId, Uri{ localhost_redirect_uri }); + requestParams.Scope(scope); + + auto authResponse = InitiateAndWaitForSuccessfulAuthResponse(requestParams); + VERIFY_ARE_EQUAL(token, authResponse.AccessToken()); + VERIFY_ARE_EQUAL(scope, authResponse.Scope()); + } + + TEST_METHOD(Implicit_SingleCustomScope) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_TOKEN REDIRECT_TYPE_LOCALHOST PKCE_TYPE_NONE SCOPE_TYPE_SINGLE; + DoImplicitCustomScopeTest(client_id, single_scope); + } + + TEST_METHOD(Implicit_MultipleCustomScope) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_TOKEN REDIRECT_TYPE_LOCALHOST PKCE_TYPE_NONE SCOPE_TYPE_MULTIPLE; + DoImplicitCustomScopeTest(client_id, multiple_scope); + } + + TEST_METHOD(AuthRequestPreserveQueryString) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST AUTH_URL_QUERY_STRING; + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(client_id, Uri{ localhost_redirect_uri }); + auto requestAsyncOp = AuthManager::InitiateAuthRequestAsync(Uri{ std::wstring(auth_url) + L"?foo=bar" }, requestParams); + WaitWithTimeout(requestAsyncOp, AsyncStatus::Completed); + + auto authResponse = requestAsyncOp.GetResults().Response(); + VERIFY_IS_NOT_NULL(authResponse); + } + + TEST_METHOD(AuthorizationCodeWithClientAuth) + { + // NOTE: This is testing client auth, which is a token request only thing, hence only using a single redirection type + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST AUTH_TYPE_HEADER; + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(client_id, Uri{ localhost_redirect_uri }); + auto authResponse = InitiateAndWaitForSuccessfulAuthResponse(requestParams); + + auto tokenParams = TokenRequestParams::CreateForAuthorizationCodeRequest(authResponse); + auto auth = ClientAuthentication::CreateForBasicAuthorization(client_id, L"password"); + auto tokenAsyncOp = AuthManager::RequestTokenAsync(Uri{ m_serverUrlBase + L"token" }, tokenParams, auth); + WaitWithTimeout(tokenAsyncOp, AsyncStatus::Completed); + + auto tokenResult = tokenAsyncOp.GetResults(); + auto tokenResponse = tokenResult.Response(); + VerifyErrorNull(tokenResult.Failure()); + VERIFY_IS_NOT_NULL(tokenResponse); + VERIFY_ARE_EQUAL(token, tokenResponse.AccessToken()); + } + + TEST_METHOD(UserCredentialsTokenRequest) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_PASSWORD AUTH_TYPE_HEADER; + auto tokenParams = TokenRequestParams::CreateForResourceOwnerPasswordCredentials(L"username", L"password"); + auto auth = ClientAuthentication::CreateForBasicAuthorization(client_id, L"password"); + RequestTokenAndWaitForSuccessfulResponse(tokenParams, auth); + } + + TEST_METHOD(ClientCredentialsTokenRequest) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CLIENT AUTH_TYPE_HEADER; + auto tokenParams = TokenRequestParams::CreateForClientCredentials(); + auto auth = ClientAuthentication::CreateForBasicAuthorization(client_id, L"password"); + RequestTokenAndWaitForSuccessfulResponse(tokenParams, auth); + } + + TEST_METHOD(RefreshTokenRequest) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_REFRESH AUTH_TYPE_HEADER; + auto tokenParams = TokenRequestParams::CreateForRefreshToken(refresh_token_old); + auto auth = ClientAuthentication::CreateForBasicAuthorization(client_id, L"password"); + RequestTokenAndWaitForSuccessfulResponse(tokenParams, auth); + } + + TEST_METHOD(ExtensionTokenRequest) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_EXTENSION AUTH_TYPE_HEADER; + auto tokenParams = TokenRequestParams::CreateForExtension(Uri{ extension_grant_uri }); + auto auth = ClientAuthentication::CreateForBasicAuthorization(client_id, L"password"); + RequestTokenAndWaitForSuccessfulResponse(tokenParams, auth); + } + + void DoAuthCodeAuthRequestErrorResponseTest(std::wstring_view clientId, std::wstring_view redirectUri) + { + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(clientId, Uri{ redirectUri }); + auto requestAsyncOp = AuthManager::InitiateAuthRequestAsync(Uri{ auth_url }, requestParams); + WaitWithTimeout(requestAsyncOp, AsyncStatus::Completed); + + auto requestResult = requestAsyncOp.GetResults(); + auto authError = requestResult.Failure(); + VERIFY_IS_NULL(requestResult.Response()); + VERIFY_IS_NOT_NULL(authError); + auto additionalParams = authError.AdditionalParams(); + VERIFY_IS_NOT_NULL(additionalParams); + + VERIFY_ARE_EQUAL(requestParams.State(), authError.State()); + VERIFY_ARE_EQUAL(L"server_error", authError.Error()); + VERIFY_ARE_EQUAL(error_description, authError.ErrorDescription()); + VERIFY_IS_NOT_NULL(authError.ErrorUri()); + VERIFY_ARE_EQUAL(error_uri, authError.ErrorUri().RawUri()); + VERIFY_IS_TRUE(additionalParams.HasKey(additional_param_key)); + VERIFY_ARE_EQUAL(additional_param_value, additionalParams.Lookup(additional_param_key)); + } + + TEST_METHOD(Localhost_AuthRequestErrorResponse) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST AUTH_ERROR_RESPONSE; + DoAuthCodeAuthRequestErrorResponseTest(client_id, localhost_redirect_uri); + } + + TEST_METHOD(Protocol_AuthRequestErrorResponse) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_PROTOCOL AUTH_ERROR_RESPONSE; + DoAuthCodeAuthRequestErrorResponseTest(client_id, protocol_redirect_uri); + } + + TEST_METHOD(TokenRequestErrorResponse) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_PASSWORD TOKEN_ERROR_RESPONSE; + auto tokenParams = TokenRequestParams::CreateForResourceOwnerPasswordCredentials(L"username", L"password"); + auto auth = ClientAuthentication::CreateForBasicAuthorization(client_id, L"password"); + auto tokenAsyncOp = AuthManager::RequestTokenAsync(Uri{ m_serverUrlBase + L"token" }, tokenParams, auth); + WaitWithTimeout(tokenAsyncOp, AsyncStatus::Completed); + + auto tokenResult = tokenAsyncOp.GetResults(); + auto tokenError = tokenResult.Failure(); + VERIFY_IS_NULL(tokenResult.Response()); + VERIFY_IS_NOT_NULL(tokenError); + auto additionalParams = tokenError.AdditionalParams(); + VERIFY_IS_NOT_NULL(additionalParams); + + VERIFY_ARE_EQUAL(E_FAIL, tokenError.ErrorCode().value); + VERIFY_ARE_EQUAL(L"server_error", tokenError.Error()); + VERIFY_ARE_EQUAL(error_description, tokenError.ErrorDescription()); + VERIFY_IS_NOT_NULL(tokenError.ErrorUri()); + VERIFY_ARE_EQUAL(error_uri, tokenError.ErrorUri().RawUri()); + + VERIFY_IS_TRUE(additionalParams.HasKey(additional_param_key)); + auto jsonValue = additionalParams.Lookup(additional_param_key); + VERIFY_ARE_EQUAL(JsonValueType::String, jsonValue.ValueType()); + VERIFY_ARE_EQUAL(additional_param_value, jsonValue.GetString()); + } + + TEST_METHOD(AdditionalParams) + { + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST ADDITIONAL_PARAMS; + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(client_id, Uri{ localhost_redirect_uri }); + auto additionalRequestParams = requestParams.AdditionalParams(); + additionalRequestParams.Insert(additional_param_key, additional_param_value); + auto authResponse = InitiateAndWaitForSuccessfulAuthResponse(requestParams); + + auto tokenParams = TokenRequestParams::CreateForAuthorizationCodeRequest(authResponse); + auto additionalTokenParams = tokenParams.AdditionalParams(); + additionalTokenParams.Insert(additional_param_key, additional_param_value); + + auto tokenAsyncOp = AuthManager::RequestTokenAsync(Uri{ m_serverUrlBase + L"token" }, tokenParams); + WaitWithTimeout(tokenAsyncOp, AsyncStatus::Completed); + + auto tokenResult = tokenAsyncOp.GetResults(); + auto tokenResponse = tokenResult.Response(); + VerifyErrorNull(tokenResult.Failure()); + VERIFY_IS_NOT_NULL(tokenResponse); + } + + TEST_METHOD(CancelAuthRequest) + { + // NOTE: Grant type and redirection URI are irrelevant for testing cancellation, hence we only test this once + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST DONT_COMPLETE_REQUEST; + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(client_id, Uri{ localhost_redirect_uri }); + auto requestAsyncOp = AuthManager::InitiateAuthRequestAsync(Uri{ auth_url }, requestParams); + VERIFY_ARE_EQUAL(AsyncStatus::Started, requestAsyncOp.Status()); + + requestAsyncOp.Cancel(); + WaitWithTimeout(requestAsyncOp, AsyncStatus::Canceled); + } + + TEST_METHOD(CompleteAuthRequestTwice) + { + // NOTE: Grant type is irrelevant for this test and redirect URI is only relevant for the initial completion, + // meaning it too is irrelavent for this test + static constexpr std::wstring_view client_id = GRANT_TYPE_CODE REDIRECT_TYPE_LOCALHOST; + auto requestParams = AuthRequestParams::CreateForAuthorizationCodeRequest(client_id, Uri{ localhost_redirect_uri }); + auto requestAsyncOp = AuthManager::InitiateAuthRequestAsync(Uri{ auth_url }, requestParams); + WaitWithTimeout(requestAsyncOp, AsyncStatus::Completed); + + auto requestResult = requestAsyncOp.GetResults(); + auto requestResponseUri = requestResult.ResponseUri(); + VERIFY_IS_NOT_NULL(requestResponseUri); + VERIFY_IS_FALSE(AuthManager::CompleteAuthRequest(requestResponseUri)); + } + + TEST_METHOD(CompleteInvalidState) + { + VERIFY_IS_FALSE(AuthManager::CompleteAuthRequest(Uri{ L"unknown-protocol:" })); // No query parameters at all + VERIFY_IS_FALSE(AuthManager::CompleteAuthRequest(Uri{ L"http://127.0.0.1/oauth?code=abc123" })); // Missing state + VERIFY_IS_FALSE(AuthManager::CompleteAuthRequest(Uri{ L"oauthtestapp:oauth?code=abc&state=invalid" })); + VERIFY_IS_FALSE(AuthManager::CompleteAuthRequest(Uri{ L"http://127.0.0.1/oauth?code=abc123&state=invalid"})); + } + + // Detoured Functions + static HINSTANCE __stdcall DetouredShellExecuteW(_In_opt_ HWND hwnd, _In_opt_ LPCWSTR operation, _In_ LPCWSTR file, + _In_opt_ LPCWSTR params, _In_opt_ LPCWSTR directory, _In_ INT showCmd) try + { + std::wstring_view fileStr = file; + if (fileStr.substr(0, auth_url.size()) == auth_url) + { + winrt::hstring errorString; + winrt::hstring errorMessage; + auto assignInvalidRequestError = [&](std::wstring_view msg) { + if (errorString.empty()) + { + errorString = L"invalid_request"; + errorMessage = msg; + } + }; + auto assignMismatchedArgsError = [&](std::wstring_view name, std::wstring_view expected, std::wstring_view actual) { + if (errorString.empty()) + { + std::wstring msg = L"Unexpected value for '"; + msg.append(name); + msg += L"'. Expected '"; + msg.append(expected); + msg += L"' but got '"; + msg.append(actual); + msg += L"'"; + errorString = L"invalid_request"; + errorMessage = msg; + } + }; + + // There's no point in launching the browser and trying to fake an authorization flow as that would do + // nothing to test the API. Instead, perform the logic of the browser and authorization flow here in-proc + winrt::hstring responseType; + winrt::hstring clientId; + Uri redirectUri{ nullptr }; + winrt::hstring scope; + winrt::hstring state; + winrt::hstring codeChallenge; + winrt::hstring codeChallengeMethod; + winrt::hstring additionalParam; + winrt::hstring foo; + for (auto&& entry : Uri(fileStr).QueryParsed()) + { + auto name = entry.Name(); + auto value = entry.Value(); + if (name == L"response_type") + { + responseType = value; + } + else if (name == L"client_id") + { + clientId = value; + } + else if (name == L"redirect_uri") + { + redirectUri = Uri{ value }; + } + else if (name == L"scope") + { + scope = value; + } + else if (name == L"state") + { + state = value; + } + else if (name == L"code_challenge") + { + codeChallenge = value; + } + else if (name == L"code_challenge_method") + { + codeChallengeMethod = value; + } + else if (name == additional_param_key) + { + additionalParam = value; + } + else if (name == L"foo") + { + foo = value; + } + else + { + assignInvalidRequestError(L"Unrecognized query parameter '"s + name + L"'"); + } + } + + // Some behavior is encoded in the client id + winrt::hstring expectedGrantType; + winrt::hstring expectedRedirectType; + winrt::hstring expectedPkceType = L"S256"; + winrt::hstring expectedScopeType = L"none"; + winrt::hstring expectedError = L"none"; + bool completeRequest = true; + bool expectAdditionalParams = false; + bool expectAuthUrlQueryString = false; + for (auto&& entry : WwwFormUrlDecoder{ clientId }) + { + auto name = entry.Name(); + auto value = entry.Value(); + if (name == L"grant") + { + expectedGrantType = value; + } + else if (name == L"redirect") + { + expectedRedirectType = value; + } + else if (name == L"pkce") + { + expectedPkceType = value; + } + else if (name == L"scope") + { + expectedScopeType = value; + } + else if (name == L"error") + { + expectedError = value; + } + else if (name == L"complete") + { + completeRequest = (value == L"true"); + } + else if (name == L"additional_params") + { + expectAdditionalParams = (value == L"true"); + } + else if (name == L"query") + { + expectAuthUrlQueryString = (value == L"true"); + } + // Ignore other values as these are specific to the token request + } + + if (state.empty()) + { + // If no state is provided, we'll be unable to correlate the response to the request. The best we can + // really do here is to fail the launch which will fail the test early and reliably + Log::Error(L"No 'state' value provided in the URI"); + ::SetLastError(ERROR_INVALID_PARAMETER); + return nullptr; + } + else if (responseType.empty()) + { + assignInvalidRequestError(L"Missing 'response_type'"); + } + else if (clientId.empty()) + { + assignInvalidRequestError(L"Missing 'client_id'"); + } + else if (expectedGrantType.empty()) + { + assignInvalidRequestError(L"Client id is missing the expected grant type"); + } + else if (expectedRedirectType.empty()) + { + assignInvalidRequestError(L"Client id is missing the expected redirect type"); + } + + if (!redirectUri) + { + if (expectedRedirectType == L"inferred") + { + redirectUri = Uri{ localhost_redirect_uri }; + } + else + { + // If we aren't given a URI and we didn't expect to not be given a URI, then we can't reliably + // return back an error response + Log::Error(L"No 'redirect_uri' value provided in the URI"); + ::SetLastError(ERROR_INVALID_PARAMETER); + return nullptr; + } + } + else if (expectedRedirectType == L"inferred") + { + assignMismatchedArgsError(L"redirect_uri", L"", redirectUri.RawUri()); + } + + if (responseType != expectedGrantType) + { + assignMismatchedArgsError(L"response_type", expectedGrantType, responseType); + } + + auto expectedUri = (expectedRedirectType == L"protocol") ? protocol_redirect_uri : localhost_redirect_uri; + if (redirectUri.RawUri() != expectedUri) + { + assignMismatchedArgsError(L"redirect_uri", expectedUri, redirectUri.RawUri()); + } + + if (expectedPkceType == L"none") + { + if (!codeChallengeMethod.empty()) + { + assignMismatchedArgsError(L"code_challenge_method", L"", codeChallengeMethod); + } + } + else if (expectedPkceType != codeChallengeMethod) + { + assignMismatchedArgsError(L"code_challenge_method", expectedPkceType, codeChallengeMethod); + } + + if (expectedScopeType == L"none") + { + if (!scope.empty()) + { + assignMismatchedArgsError(L"scope", L"", scope); + } + } + else if (scope.empty()) + { + assignInvalidRequestError(L"Expected a 'scope' parameter, but none provided"); + } + else if (expectedScopeType == L"single") + { + if (scope != single_scope) + { + assignMismatchedArgsError(L"scope", single_scope, scope); + } + } + else if (expectedScopeType == L"multiple") + { + if (scope != multiple_scope) + { + assignMismatchedArgsError(L"scope", multiple_scope, scope); + } + } + + if (expectAdditionalParams) + { + if (additionalParam.empty()) + { + assignInvalidRequestError(L"Expected additional params, but none provided"); + } + else if (additionalParam != additional_param_value) + { + assignMismatchedArgsError(L"additional param", additional_param_value, additionalParam); + } + } + else if (!additionalParam.empty()) + { + assignInvalidRequestError(L"Expected no additional params, but one was provided"); + } + + if (!expectAuthUrlQueryString) + { + if (!foo.empty()) + { + assignInvalidRequestError(L"Query parameter 'foo' was unexpected"); + } + } + else if (foo != L"bar") + { + assignMismatchedArgsError(L"foo", L"bar", foo); + } + + Uri responseUri{ nullptr }; + if (expectedError == L"auth") + { + uri_builder builder(redirectUri, responseType != L"token"); + builder.add(L"state", state); + builder.add(L"error", L"server_error"); + builder.add(L"error_description", error_description); + builder.add(L"error_uri", error_uri); + builder.add(additional_param_key, additional_param_value); + responseUri = builder.get(); + } + else if (responseType == L"code") + { + // For simplicity, encode the client id and PKCE info in the code + std::wstring code = L"client="; + code += Uri::EscapeComponent(clientId); + if (codeChallengeMethod.empty()) + { + code += L"&challenge_method=none"; + } + else + { + code += L"&challenge_method="; + code += codeChallengeMethod; + code += L"&challenge="; + code += codeChallenge; + } + + // NOTE: The 'scope' should be empty, but we should never indicate an expected 'scope' other than 'none' + // for tests that use the auth code grant type + + uri_builder builder{ redirectUri }; + builder.add(L"code", code); + builder.add(L"state", state); + responseUri = builder.get(); + } + else if (responseType == L"token") + { + if (!codeChallengeMethod.empty()) + { + assignInvalidRequestError(L"Use of PKCE is not valid for implicit requests"); + } + + uri_builder builder{ redirectUri, false }; + builder.add(L"state", state); + builder.add(L"access_token", token); + builder.add(L"token_type", L"Bearer"); + builder.add(L"expires_in", L"3600"); + if (scope.empty()) + { + builder.add(L"scope", L"all"); + } + else + { + builder.add(L"scope", scope); + } + + responseUri = builder.get(); + } + else + { + assignInvalidRequestError(L"Unknown response type '"s + responseType + L"'"); + } + + if (!errorString.empty()) + { + // NOTE: We may have created a response URI already, in which case we want to overwrite it here + uri_builder builder(redirectUri, responseType != L"token"); + builder.add(L"state", state); + builder.add(L"error", errorString); + builder.add_optional(L"error_description", errorMessage); + responseUri = builder.get(); + } + + if (responseUri.SchemeName() != L"http") + { + // Protocol activation + return RealShellExecuteW(hwnd, L"open", responseUri.RawUri().c_str(), nullptr, nullptr, SW_SHOWDEFAULT); + } + + // Simulating a localhost server. This would give the response back in-proc so we can just go ahead and + // do that directly. Note that we do this in the same callstack as that will test more interesting code + // paths. TODO: Async completion as a parameter? Or just let protocol activation test that path + if (completeRequest && !AuthManager::CompleteAuthRequest(responseUri)) + { + Log::Warning(L"Failed to complete auth request"); + } + + return reinterpret_cast(42); // Value doesn't really matter; must be greater than 32 + } + + // Not intercepting. Let this "fall through" to the implementation + return RealShellExecuteW(hwnd, operation, file, params, directory, showCmd); + } + catch (...) + { + ::SetLastError(ERROR_FILE_NOT_FOUND); + return reinterpret_cast(ERROR_FILE_NOT_FOUND); + } + + // HTTP Server Thread Callback + void RunHttpServer() + { + wil::unique_event event{ wil::EventOptions::None }; + OVERLAPPED overlapped = {}; + overlapped.hEvent = event.get(); + + ULONG bufferSize = 0x1000; // 4 KB + auto buffer = std::make_unique(bufferSize); + auto request = reinterpret_cast(buffer.get()); + while (true) + { + auto err = ::HttpReceiveHttpRequest(m_requestQueue, HTTP_NULL_ID, HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY, + request, bufferSize, nullptr, &overlapped); + if (err == ERROR_IO_PENDING) + { + // Wait for either shutdown or a request to come in + HANDLE handles[] = { event.get(), m_serverShutdownEvent.get() }; + auto waitResult = ::WaitForMultipleObjects(2, handles, false, INFINITE); + if (waitResult == (WAIT_OBJECT_0 + 1)) + { + // Shutdown + ::CancelIo(m_requestQueue); + break; + } + else if (waitResult != WAIT_OBJECT_0) + { + Log::Warning(WEX::Common::String().Format( + L"WaitForMultipleObjects failed in the HTTP server thread: %d", ::GetLastError())); + ::CancelIo(m_requestQueue); + break; + } + } + + // We have a request; we'll block here until we have all data, if needed + DWORD bytes; + ::GetOverlappedResult(m_requestQueue, &overlapped, &bytes, false); + err = ::GetLastError(); + if (err == ERROR_MORE_DATA) + { + bufferSize = bytes; + buffer = std::make_unique(bufferSize); + request = reinterpret_cast(buffer.get()); + err = ::HttpReceiveHttpRequest(m_requestQueue, request->RequestId, HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY, + request, bufferSize, &bytes, nullptr); + } + + if (err == ERROR_CONNECTION_INVALID) + { + // Connection corrupted by peer + continue; + } + else if (err != ERROR_SUCCESS) + { + Log::Warning(WEX::Common::String().Format(L"HttpReceiveHttpRequest failed: %d", err)); + break; + } + + switch (request->Verb) + { + case HttpVerbPOST: + HandlePostRequest(request); + break; + + default: + Log::Warning(L"Received an HTTP request with an unexpected verb"); + break; + } + } + } + + void HandlePostRequest(HTTP_REQUEST* request) + { + std::string body; + for (USHORT i = 0; i < request->EntityChunkCount; ++i) + { + auto& chunk = request->pEntityChunks[i]; + WINRT_ASSERT(chunk.DataChunkType == HttpDataChunkFromMemory); + auto& data = chunk.FromMemory; + body.append(static_cast(data.pBuffer), data.BufferLength); + } + + if (request->Flags & HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS) + { + ULONG bufferLength = 2048; + auto buffer = std::make_unique(bufferLength); + while (true) + { + ULONG bytes = 0; + auto result = ::HttpReceiveRequestEntityBody(m_requestQueue, request->RequestId, 0, buffer.get(), + bufferLength, &bytes, nullptr); + if ((result == NO_ERROR) || (result == ERROR_HANDLE_EOF)) + { + body.append(buffer.get(), bytes); + } + else + { + Log::Warning(WEX::Common::String().Format(L"HttpReceiveRequestEntityBody failed: %d", result)); + return; // TODO: Should we send a response here? Getting an error probably means we shouldn't? + } + + if (result == ERROR_HANDLE_EOF) break; + } + } + + winrt::hstring errorString; + winrt::hstring errorMessage; + auto assignInvalidRequestError = [&](std::wstring_view msg) { + if (errorString.empty()) + { + errorString = L"invalid_request"; + errorMessage = msg; + } + }; + auto assignMismatchedArgsError = [&](std::wstring_view name, std::wstring_view expected, std::wstring_view actual) { + if (errorString.empty()) + { + std::wstring msg = L"Unexpected value for '"; + msg.append(name); + msg += L"'. Expected '"; + msg.append(expected); + msg += L"' but got '"; + msg.append(actual); + msg += L"'"; + errorString = L"invalid_request"; + errorMessage = msg; + } + }; + + winrt::hstring grantType; + winrt::hstring code; + Uri redirectUri{ nullptr }; + winrt::hstring clientId; + winrt::hstring codeVerifier; + winrt::hstring username; + winrt::hstring password; + winrt::hstring scope; + winrt::hstring refreshToken; + winrt::hstring additionalParam; + for (auto&& entry : WwwFormUrlDecoder(winrt::to_hstring(body))) + { + auto name = entry.Name(); + auto value = entry.Value(); + if (name == L"grant_type") + { + grantType = value; + } + else if (name == L"code") + { + code = value; + } + else if (name == L"redirect_uri") + { + redirectUri = Uri{ value }; + } + else if (name == L"client_id") + { + clientId = value; + } + else if (name == L"code_verifier") + { + codeVerifier = value; + } + else if (name == L"username") + { + username = value; + } + else if (name == L"password") + { + password = value; + } + else if (name == L"scope") + { + scope = value; + } + else if (name == L"refresh_token") + { + refreshToken = value; + } + else if (name == additional_param_key) + { + additionalParam = value; + } + else + { + assignInvalidRequestError(L"Unrecognized query parameter '"s + name + L"'"); + } + } + + auto& authHeader = request->Headers.KnownHeaders[HttpHeaderAuthorization]; + if (authHeader.RawValueLength > 0) + { + // Should be of the form ' ' + std::string_view authHeaderStr(authHeader.pRawValue, authHeader.RawValueLength); + auto firstSpace = authHeaderStr.find_first_of(' '); + if (firstSpace == authHeaderStr.npos) + { + assignInvalidRequestError(L"Bad Authorization hedaer"); + } + else + { + auto scheme = authHeaderStr.substr(0, firstSpace); + auto value = authHeaderStr.substr(firstSpace + 1); + if (scheme != "Basic") + { + assignInvalidRequestError(L"Authorization must use 'Basic' type"); + } + else + { + // 'value' is 'client_id:client_crednetials' base64urlencoded + auto credsBuffer = CryptographicBuffer::DecodeFromBase64String(winrt::to_hstring(value)); + auto fullCreds = CryptographicBuffer::ConvertBinaryToString(BinaryStringEncoding::Utf8, credsBuffer); + std::wstring_view fullCredsStr = fullCreds; + auto colonPos = fullCredsStr.find_first_of(':'); + if (colonPos == fullCredsStr.npos) + { + assignInvalidRequestError(L"Bad Authorization header"); + } + else + { + auto credsClientId = fullCredsStr.substr(0, colonPos); + auto credsClientSecret = fullCredsStr.substr(colonPos + 1); + if (credsClientSecret != L"password") + { + assignMismatchedArgsError(L"Authorization client secret", L"password", credsClientSecret); + } + else if (clientId.empty()) + { + clientId = credsClientId; + } + else if (credsClientId != clientId) + { + assignMismatchedArgsError(L"Authorization client id", clientId, credsClientId); + } + } + } + } + } + + if (clientId.empty()) + { + assignInvalidRequestError(L"Client id not provided"); + } + + winrt::hstring expectedGrantType; + winrt::hstring expectedRedirectType; + winrt::hstring expectedPkceType = L"S256"; + winrt::hstring expectedScopeType = L"none"; + winrt::hstring expectedAuthType = L"none"; + winrt::hstring expectedError = L"none"; + bool expectAdditionalParams = false; + for (auto&& entry : WwwFormUrlDecoder{ clientId }) + { + auto name = entry.Name(); + auto value = entry.Value(); + if (name == L"grant") + { + expectedGrantType = value; + } + else if (name == L"redirect") + { + expectedRedirectType = value; + } + else if (name == L"pkce") + { + expectedPkceType = value; + } + else if (name == L"scope") + { + expectedScopeType = value; + } + else if (name == L"auth") + { + expectedAuthType = value; + } + else if (name == L"error") + { + expectedError = value; + } + else if (name == L"additional_params") + { + expectAdditionalParams = (value == L"true"); + } + // Ignore other values as these are specific to the authorization request + } + + auto checkUnexpectedArg = [&](std::wstring_view name, const winrt::hstring& value) + { + if (!value.empty()) + { + assignMismatchedArgsError(name, L"", value); + } + }; + + if (expectAdditionalParams) + { + if (additionalParam.empty()) + { + assignInvalidRequestError(L"Expected additional params, but none provided"); + } + else if (additionalParam != additional_param_value) + { + assignMismatchedArgsError(L"additional param", additional_param_value, additionalParam); + } + } + else if (!additionalParam.empty()) + { + assignInvalidRequestError(L"Expected no additional params, but one was provided"); + } + + if ((expectedAuthType == L"header") && (authHeader.RawValueLength == 0)) + { + assignInvalidRequestError(L"Authorization header expected, but not provided"); + } + + std::wstring responseJson; + if (expectedError == L"token") + { + errorString = L"server_error"; + errorMessage = json_escaped_error_description; + } + else if (grantType == L"authorization_code") + { + if (expectedGrantType != L"code") + { + assignMismatchedArgsError(L"grant_type", expectedGrantType, grantType); + } + else if (code.empty()) + { + assignInvalidRequestError(L"Authorization code not provided"); + } + + if (redirectUri) + { + auto expectedUri = (expectedRedirectType == L"protocol") ? protocol_redirect_uri : localhost_redirect_uri; + if (redirectUri.RawUri() != expectedUri) + { + assignMismatchedArgsError(L"redirect_uri", expectedUri, redirectUri.RawUri()); + } + } + else if (expectedRedirectType != L"inferred") + { + assignInvalidRequestError(L"Expected a 'redirect_uri', but none provided"); + } + + checkUnexpectedArg(L"username", username); + checkUnexpectedArg(L"password", password); + checkUnexpectedArg(L"scope", scope); // Only expected during auth request + checkUnexpectedArg(L"refresh_token", refreshToken); + + winrt::hstring codeClientId; + winrt::hstring codeChallengeMethod; + winrt::hstring codeChallenge; + for (auto&& entry : WwwFormUrlDecoder{ code }) + { + auto name = entry.Name(); + auto value = entry.Value(); + if (name == L"client") + { + codeClientId = value; + } + else if (name == L"challenge_method") + { + codeChallengeMethod = value; + } + else if (name == L"challenge") + { + codeChallenge = value; + } + else + { + assignInvalidRequestError(L"Unrecognized query parameter '" + name + L"' in code"); + } + } + + if (clientId != codeClientId) + { + assignMismatchedArgsError(L"client_id", codeClientId, clientId); + } + + if (expectedPkceType != codeChallengeMethod) + { + assignMismatchedArgsError(L"code challenge method", expectedPkceType, codeChallengeMethod); + } + else if (codeChallengeMethod == L"none") + { + if (!codeVerifier.empty()) + { + assignMismatchedArgsError(L"code_verifier", L"", codeVerifier); + } + } + else if (codeVerifier.empty()) + { + assignInvalidRequestError(L"Expected 'code_verifier', but none provided"); + } + + if (codeChallengeMethod == L"S256") + { + // We can't "unhash" the code challenge, so hash the code verifier and base64urlencode it + auto algo = HashAlgorithmProvider::OpenAlgorithm(HashAlgorithmNames::Sha256()); + auto hash = CryptographicBuffer::ConvertStringToBinary(codeVerifier, BinaryStringEncoding::Utf8); + auto base64Hash = CryptographicBuffer::EncodeToBase64String(hash); + + std::wstring base64urlencodedHash; + base64urlencodedHash.reserve(base64Hash.size()); + for (auto ch : base64Hash) + { + switch (ch) + { + case '+': base64urlencodedHash.push_back('-'); break; + case '/': base64urlencodedHash.push_back('_'); break; + case '=': break; // No padding + default: base64urlencodedHash.push_back(ch); break; + } + } + + if (codeChallenge != base64urlencodedHash) + { + assignInvalidRequestError(L"The code verifier does not match the original code challenge"); + } + } + else if (codeChallengeMethod == L"plain") + { + if (codeChallenge != codeVerifier) + { + assignInvalidRequestError(L"Code verifier does not match the expected value"); + } + } + } + else if (grantType == L"password") + { + if (expectedGrantType != L"password") + { + assignMismatchedArgsError(L"grant_type", expectedGrantType, grantType); + } + else if (username.empty()) + { + assignMismatchedArgsError(L"username", L"username", L""); + } + else if (username != L"username") + { + assignMismatchedArgsError(L"username", L"username", username); + } + else if (password.empty()) + { + assignMismatchedArgsError(L"password", L"password", L""); + } + else if (password != L"password") + { + assignMismatchedArgsError(L"password", L"password", password); + } + + checkUnexpectedArg(L"code", code); + // checkUnexpectedArg(L"redirect_uri", redirectUri); + checkUnexpectedArg(L"code_verifier", codeVerifier); + checkUnexpectedArg(L"refresh_token", refreshToken); + + } + else if (grantType == L"client_credentials") + { + if (expectedGrantType != L"client") + { + assignMismatchedArgsError(L"grant_type", expectedGrantType, grantType); + } + + checkUnexpectedArg(L"code", code); + // checkUnexpectedArg(L"redirect_uri", redirectUri); + checkUnexpectedArg(L"code_verifier", codeVerifier); + checkUnexpectedArg(L"username", username); + checkUnexpectedArg(L"password", password); + checkUnexpectedArg(L"refresh_token", refreshToken); + } + else if (grantType == L"refresh_token") + { + if (expectedGrantType != L"refresh") + { + assignMismatchedArgsError(L"grant_type", expectedGrantType, grantType); + } + else if (refreshToken != refresh_token_old) + { + assignMismatchedArgsError(L"refresh_token", refresh_token_old, refreshToken); + } + + checkUnexpectedArg(L"code", code); + // checkUnexpectedArg(L"redirect_uri", redirectUri); + checkUnexpectedArg(L"code_verifier", codeVerifier); + checkUnexpectedArg(L"username", username); + checkUnexpectedArg(L"password", password); + } + else if (grantType == extension_grant_uri) + { + if (expectedGrantType != L"extension") + { + assignMismatchedArgsError(L"grant_type", expectedGrantType, grantType); + } + + checkUnexpectedArg(L"code", code); + // checkUnexpectedArg(L"redirect_uri", redirectUri); + checkUnexpectedArg(L"code_verifier", codeVerifier); + checkUnexpectedArg(L"username", username); + checkUnexpectedArg(L"password", password); + checkUnexpectedArg(L"refresh_token", refreshToken); + } + else + { + assignInvalidRequestError(L"Unrecognized grant type '"s + grantType + L"'"); + } + + if (errorString.empty()) + { + // NOTE: All responses are the same + responseJson = L"{\"access_token\":\""; + responseJson += json_escaped_token; + responseJson += L"\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"refresh_token\":\""; + responseJson += json_escaped_refresh_token; + responseJson += L"\""; + if (scope.empty()) + { + responseJson += L",\"scope\":\"all\""; + } + responseJson += L"}"; + } + else + { + responseJson = L"{\"error\":\"" + errorString + L"\",\"error_description\":\"" + errorMessage + + L"\",\"error_uri\":\"" + error_uri + L"\",\"" + additional_param_key + L"\":\"" + + additional_param_value + L"\"}"; + } + + WINRT_ASSERT(!responseJson.empty()); + + HTTP_RESPONSE response = {}; + response.StatusCode = 200; + response.pReason = "OK"; + response.ReasonLength = 2; + + auto& contentTypeHeader = response.Headers.KnownHeaders[HttpHeaderContentType]; + contentTypeHeader.pRawValue = "application/json; charset=UTF-8"; + contentTypeHeader.RawValueLength = static_cast(::strlen(contentTypeHeader.pRawValue)); + + auto responseJsonUtf8 = winrt::to_string(responseJson); + HTTP_DATA_CHUNK dataChunk = {}; + dataChunk.DataChunkType = HttpDataChunkFromMemory; + dataChunk.FromMemory.pBuffer = responseJsonUtf8.data(); + dataChunk.FromMemory.BufferLength = static_cast(responseJsonUtf8.size()); + + response.EntityChunkCount = 1; + response.pEntityChunks = &dataChunk; + + ULONG bytesSent; + auto sendResult = ::HttpSendHttpResponse(m_requestQueue, request->RequestId, 0, &response, nullptr, &bytesSent, + nullptr, 0, nullptr, nullptr); + if (sendResult != NO_ERROR) + { + Log::Warning(WEX::Common::String().Format(L"HttpSendHttpResponse failed: %d", sendResult)); + } + } + + // Detours Information + static inline decltype(&::ShellExecuteW) RealShellExecuteW = &::ShellExecuteW; + + // Local server for performing the token exchange + wil::unique_event m_serverShutdownEvent{ wil::EventOptions::None }; + std::thread m_httpServerThread; + HANDLE m_requestQueue = nullptr; + HTTP_SERVER_SESSION_ID m_serverSessionId = 0; + HTTP_URL_GROUP_ID m_urlGroup = 0; + std::uint16_t m_serverPort = 50001; + std::wstring m_serverUrlBase; +}; diff --git a/test/OAuthTests/OAuthTests.vcxproj b/test/OAuthTests/OAuthTests.vcxproj new file mode 100644 index 0000000000..c0dabfa349 --- /dev/null +++ b/test/OAuthTests/OAuthTests.vcxproj @@ -0,0 +1,158 @@ + + + + + + Debug + ARM64 + + + Debug + Win32 + + + Release + ARM64 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {21651459-648e-475c-91db-2bde359c75a4} + OAuthTests + 10.0 + + + + DynamicLibrary + v143 + Unicode + + + true + + + false + true + + + + + + + + + + + + + + Level4 + true + true + NOMINMAX;WIN32_LEAN_AND_MEAN;OAUTHTESTS_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + + ..\..\dev\Detours; + ..\..\dev\Common; + $(OutDir)\..\WindowsAppRuntime_DLL; + $(OutDir)\..\WindowsAppRuntime_BootstrapDLL; + %(AdditionalIncludeDirectories) + + + + Windows + true + false + httpapi.lib;%(AdditionalDependencies) + Microsoft.WindowsAppRuntime.dll;%(DelayLoadDLLs) + + + + + _DEBUG;%(PreprocessorDefinitions) + + + + + true + true + NDEBUG;%(PreprocessorDefinitions) + + + true + true + + + + + WIN32;%(PreprocessorDefinitions) + + + + + WIN32;%(PreprocessorDefinitions) + + + + + + + + + + .Debug + _Debug + $(AppxPackageDir)\OAuthTestAppPackage_1.0.0.0_$(PlatformTarget)$(TestPkgDebugConfigName)_Test + $(TestPkgOutputPath)\OAuthTestAppPackage_1.0.0.0_$(PlatformTarget)$(TestPkgDebugConfigName).msix + + + + + + + + {d6bc25c5-1aa7-4c4a-a02c-b42dedbfea33} + + + {f76b776e-86f5-48c5-8fc7-d2795ecc9746} + + + + + $(OutDir)\..\WindowsAppRuntime_DLL\Microsoft.Windows.Security.Authentication.OAuth.winmd + true + $(OutDir)\..\WindowsAppRuntime_DLL\Microsoft.WindowsAppRuntime.dll + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + + + + \ No newline at end of file diff --git a/test/OAuthTests/OAuthTests.vcxproj.filters b/test/OAuthTests/OAuthTests.vcxproj.filters new file mode 100644 index 0000000000..675aba6659 --- /dev/null +++ b/test/OAuthTests/OAuthTests.vcxproj.filters @@ -0,0 +1,25 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + + + + \ No newline at end of file diff --git a/test/OAuthTests/packages.config b/test/OAuthTests/packages.config new file mode 100644 index 0000000000..a2dc8394c3 --- /dev/null +++ b/test/OAuthTests/packages.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/test/TestApps/OAuthTestApp/OAuthTestApp.vcxproj b/test/TestApps/OAuthTestApp/OAuthTestApp.vcxproj new file mode 100644 index 0000000000..39fb17bbca --- /dev/null +++ b/test/TestApps/OAuthTestApp/OAuthTestApp.vcxproj @@ -0,0 +1,130 @@ + + + + + + Debug + ARM64 + + + Debug + Win32 + + + Release + ARM64 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {077bdbfd-c1aa-49c8-bd62-7c14221c45f2} + OAuthTestApp + 10.0 + + + + Application + v143 + Unicode + + + true + + + false + true + + + + + + + + + + + + + Level4 + true + _CONSOLE;%(PreprocessorDefinitions) + true + true + + + Console + true + + + + + _DEBUG;%(PreprocessorDefinitions) + + + + + true + true + NDEBUG;%(PreprocessorDefinitions) + + + true + true + + + + + WIN32;%(PreprocessorDefinitions) + + + + + + + + + + + {f76b776e-86f5-48c5-8fc7-d2795ecc9746} + + + + + $(BaseOutputPath)\WindowsAppRuntime_DLL\Microsoft.Windows.AppLifecycle.winmd + true + $(OutDir)\..\WindowsAppRuntime_DLL\Microsoft.WindowsAppRuntime.dll + + + $(OutDir)\..\WindowsAppRuntime_DLL\Microsoft.Windows.Security.Authentication.OAuth.winmd + true + $(OutDir)\..\WindowsAppRuntime_DLL\Microsoft.WindowsAppRuntime.dll + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + + diff --git a/test/TestApps/OAuthTestApp/OAuthTestApp.vcxproj.filters b/test/TestApps/OAuthTestApp/OAuthTestApp.vcxproj.filters new file mode 100644 index 0000000000..ce0c35ccf4 --- /dev/null +++ b/test/TestApps/OAuthTestApp/OAuthTestApp.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/test/TestApps/OAuthTestApp/main.cpp b/test/TestApps/OAuthTestApp/main.cpp new file mode 100644 index 0000000000..81cede8faa --- /dev/null +++ b/test/TestApps/OAuthTestApp/main.cpp @@ -0,0 +1,30 @@ + +#include + +#include +#include +#include +#include + +using namespace winrt::Microsoft::Windows::AppLifecycle; +using namespace winrt::Microsoft::Windows::Security::Authentication::OAuth; +using namespace winrt::Windows::ApplicationModel::Activation; + +int main() +{ + auto args = AppInstance::GetCurrent().GetActivatedEventArgs(); + auto kind = args.Kind(); + if (kind == ExtendedActivationKind::Protocol) + { + auto uri = args.Data().as().Uri(); + if (!AuthManager::CompleteAuthRequest(uri)) + { + std::printf("WARNING: Failed to complete auth request with uri '%ls'.\n", uri.RawUri().c_str()); + std::printf("WARNING: This may or may not be expected depending on which test is running.\n"); + } + } + else + { + std::printf("WARNING: Application was launched with something other than protocol activation!\n"); + } +} diff --git a/test/TestApps/OAuthTestApp/packages.config b/test/TestApps/OAuthTestApp/packages.config new file mode 100644 index 0000000000..fb3afa8d2f --- /dev/null +++ b/test/TestApps/OAuthTestApp/packages.config @@ -0,0 +1,4 @@ + + + + diff --git a/test/TestApps/OAuthTestAppPackage/Images/LockScreenLogo.scale-200.png b/test/TestApps/OAuthTestAppPackage/Images/LockScreenLogo.scale-200.png new file mode 100644 index 0000000000..735f57adb5 Binary files /dev/null and b/test/TestApps/OAuthTestAppPackage/Images/LockScreenLogo.scale-200.png differ diff --git a/test/TestApps/OAuthTestAppPackage/Images/SplashScreen.scale-200.png b/test/TestApps/OAuthTestAppPackage/Images/SplashScreen.scale-200.png new file mode 100644 index 0000000000..023e7f1fed Binary files /dev/null and b/test/TestApps/OAuthTestAppPackage/Images/SplashScreen.scale-200.png differ diff --git a/test/TestApps/OAuthTestAppPackage/Images/Square150x150Logo.scale-200.png b/test/TestApps/OAuthTestAppPackage/Images/Square150x150Logo.scale-200.png new file mode 100644 index 0000000000..af49fec1a5 Binary files /dev/null and b/test/TestApps/OAuthTestAppPackage/Images/Square150x150Logo.scale-200.png differ diff --git a/test/TestApps/OAuthTestAppPackage/Images/Square44x44Logo.scale-200.png b/test/TestApps/OAuthTestAppPackage/Images/Square44x44Logo.scale-200.png new file mode 100644 index 0000000000..ce342a2ec8 Binary files /dev/null and b/test/TestApps/OAuthTestAppPackage/Images/Square44x44Logo.scale-200.png differ diff --git a/test/TestApps/OAuthTestAppPackage/Images/Square44x44Logo.targetsize-24_altform-unplated.png b/test/TestApps/OAuthTestAppPackage/Images/Square44x44Logo.targetsize-24_altform-unplated.png new file mode 100644 index 0000000000..f6c02ce97e Binary files /dev/null and b/test/TestApps/OAuthTestAppPackage/Images/Square44x44Logo.targetsize-24_altform-unplated.png differ diff --git a/test/TestApps/OAuthTestAppPackage/Images/StoreLogo.png b/test/TestApps/OAuthTestAppPackage/Images/StoreLogo.png new file mode 100644 index 0000000000..7385b56c0e Binary files /dev/null and b/test/TestApps/OAuthTestAppPackage/Images/StoreLogo.png differ diff --git a/test/TestApps/OAuthTestAppPackage/Images/Wide310x150Logo.scale-200.png b/test/TestApps/OAuthTestAppPackage/Images/Wide310x150Logo.scale-200.png new file mode 100644 index 0000000000..288995b397 Binary files /dev/null and b/test/TestApps/OAuthTestAppPackage/Images/Wide310x150Logo.scale-200.png differ diff --git a/test/TestApps/OAuthTestAppPackage/OAuthTestAppPackage.wapproj b/test/TestApps/OAuthTestAppPackage/OAuthTestAppPackage.wapproj new file mode 100644 index 0000000000..6e886ee18e --- /dev/null +++ b/test/TestApps/OAuthTestAppPackage/OAuthTestAppPackage.wapproj @@ -0,0 +1,72 @@ + + + + 15.0 + + + + Debug + x86 + + + Release + x86 + + + Debug + x64 + + + Release + x64 + + + Debug + ARM64 + + + Release + ARM64 + + + + $(MSBuildExtensionsPath)\Microsoft\DesktopBridge\ + + + + c4454d2c-8024-41b8-bac1-fc2e544c810f + 10.0.19041.0 + 10.0.17763.0 + en-US + True + ..\OAuthTestApp\OAuthTestApp.vcxproj + true + False + $(RepoTestCertificatePFX) + $(RepoTestCertificatePassword) + false + SHA256 + True + True + $(Platform) + 0 + + + + Designer + + + + + + + + + + + + + + + + diff --git a/test/TestApps/OAuthTestAppPackage/Package.appxmanifest b/test/TestApps/OAuthTestAppPackage/Package.appxmanifest new file mode 100644 index 0000000000..c4f8563fe9 --- /dev/null +++ b/test/TestApps/OAuthTestAppPackage/Package.appxmanifest @@ -0,0 +1,58 @@ + + + + + + + + OAuthTestAppPackage + Microsoft Corporation + Images\StoreLogo.png + + + + + + + + + + + + + + + + + + + + + OAuth Test App + + + + + + + + + + + diff --git a/test/ToastNotificationTests/AppNotification-Test-Constants.h b/test/ToastNotificationTests/AppNotification-Test-Constants.h deleted file mode 100644 index e496d48b04..0000000000 --- a/test/ToastNotificationTests/AppNotification-Test-Constants.h +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation and Contributors. -// Licensed under the MIT License. -#pragma once - -inline const winrt::hstring c_rawNotificationPayload = L""; -inline const std::chrono::seconds c_timeout = std::chrono::seconds(300); -inline IID c_toastComServerId = winrt::guid("1940dba9-0f64-4f0d-8a4b-5d207b812e61"); // Value from ToastNotificationsTestAppPackage ComActivator in appxmanifest. diff --git a/test/ToastNotificationTests/ToastNotificationTests.vcxproj b/test/ToastNotificationTests/ToastNotificationTests.vcxproj deleted file mode 100644 index b7503081a0..0000000000 --- a/test/ToastNotificationTests/ToastNotificationTests.vcxproj +++ /dev/null @@ -1,254 +0,0 @@ - - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - Debug - ARM64 - - - Release - ARM64 - - - - 16.0 - Win32Proj - {e977b1bd-00dc-4085-a105-e0a18e0183d7} - ToastNotificationTests - 10.0 - - - - DynamicLibrary - true - v143 - Unicode - - - DynamicLibrary - false - v143 - Unicode - - - DynamicLibrary - true - v143 - Unicode - - - DynamicLibrary - false - v143 - Unicode - - - DynamicLibrary - true - v143 - Unicode - false - - - DynamicLibrary - false - v143 - Unicode - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %(AdditionalIncludeDirectories);$(OutDir)\..\WindowsAppRuntime_DLL;..\inc;$(OutDir)\..\WindowsAppRuntime_BootstrapDLL - WIN32;_DEBUG;TOASTNOTIFICATIONTESTS_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) - Use - pch.h - - - Windows - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories);$(OutDir)\..\WindowsAppRuntime_DLL - onecore.lib;onecoreuap.lib;Microsoft.WindowsAppRuntime.lib;wex.common.lib;wex.logger.lib;te.common.lib;%(AdditionalDependencies) - false - - - - - %(AdditionalIncludeDirectories);$(OutDir)\..\WindowsAppRuntime_DLL;..\inc;$(OutDir)\..\WindowsAppRuntime_BootstrapDLL - WIN32;NDEBUG;TOASTNOTIFICATIONTESTS_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) - true - Use - pch.h - - - Windows - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories);$(OutDir)\..\WindowsAppRuntime_DLL - onecore.lib;onecoreuap.lib;Microsoft.WindowsAppRuntime.lib;wex.common.lib;wex.logger.lib;te.common.lib;%(AdditionalDependencies) - false - - - - - %(AdditionalIncludeDirectories);$(OutDir)\..\WindowsAppRuntime_DLL;..\inc;$(OutDir)\..\WindowsAppRuntime_BootstrapDLL - _DEBUG;TOASTNOTIFICATIONTESTS_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) - true - Use - pch.h - - - Windows - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories);$(OutDir)\..\WindowsAppRuntime_DLL - onecore.lib;onecoreuap.lib;Microsoft.WindowsAppRuntime.lib;wex.common.lib;wex.logger.lib;te.common.lib;%(AdditionalDependencies) - false - - - - - %(AdditionalIncludeDirectories);$(OutDir)\..\WindowsAppRuntime_DLL;..\inc;$(OutDir)\..\WindowsAppRuntime_BootstrapDLL - NDEBUG;TOASTNOTIFICATIONTESTS_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) - Use - pch.h - - - Windows - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories);$(OutDir)\..\WindowsAppRuntime_DLL - onecore.lib;onecoreuap.lib;Microsoft.WindowsAppRuntime.lib;wex.common.lib;wex.logger.lib;te.common.lib;%(AdditionalDependencies) - false - - - - - Use - %(AdditionalIncludeDirectories);$(OutDir)\..\WindowsAppRuntime_DLL;..\inc;$(OutDir)\..\WindowsAppRuntime_BootstrapDLL - _DEBUG;%(PreprocessorDefinitions);;INLINE_TEST_METHOD_MARKUP - true - pch.h - - - Windows - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories);$(OutDir)\..\WindowsAppRuntime_DLL - onecore.lib;onecoreuap.lib;Microsoft.WindowsAppRuntime.lib;wex.common.lib;wex.logger.lib;te.common.lib;%(AdditionalDependencies) - - - - - Use - %(AdditionalIncludeDirectories);$(OutDir)\..\WindowsAppRuntime_DLL;..\inc;$(OutDir)\..\WindowsAppRuntime_BootstrapDLL - NDEBUG;%(PreprocessorDefinitions);;INLINE_TEST_METHOD_MARKUP - true - pch.h - - - Windows - $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories);$(OutDir)\..\WindowsAppRuntime_DLL - onecore.lib;onecoreuap.lib;Microsoft.WindowsAppRuntime.lib;wex.common.lib;wex.logger.lib;te.common.lib;%(AdditionalDependencies) - - - - - - - - - - Create - Create - Create - Create - Create - Create - Create - Create - - - - - - - .Debug - _Debug - $(AppxPackageDir)\ToastNotificationsTestAppPackage_1.0.0.0_$(PlatformTarget)$(TestPkgDebugConfigName)_Test - $(TestPkgOutputPath)\ToastNotificationsTestAppPackage_1.0.0.0_$(PlatformTarget)$(TestPkgDebugConfigName).msix - - - - - - - - - $(OutDir)\..\WindowsAppRuntime_DLL\Microsoft.Windows.AppLifecycle.winmd - true - - - $(OutDir)\..\WindowsAppRuntime_DLL\Microsoft.Windows.AppNotifications.winmd - true - - - - - {bf3fced0-cadb-490a-93a7-4d90e1f45ab0} - - - {f76b776e-86f5-48c5-8fc7-d2795ecc9746} - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - - - - \ No newline at end of file