Skip to content

Commit

Permalink
Added ConnectionString parameter to New-CosmosDBContext (#466)
Browse files Browse the repository at this point in the history
  • Loading branch information
ArmaanMcleod authored Jan 21, 2023
1 parent 6f847d6 commit 66c5c38
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- Added `-ConnectionString` parameter to `New-CosmosDbContext` - Fixes [Issue #426](https://github.com/PlagueHO/CosmosDB/issues/426).

### Fixed

- Fixed spelling errors in documentation.
Expand Down
41 changes: 38 additions & 3 deletions docs/New-CosmosDbContext.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ New-CosmosDbContext -Account <String> [-Database <String>] -Token <ContextToken[
[-WhatIf] [-Confirm] [<CommonParameters>]
```

### ConnectionString

```powershell
New-CosmosDbContext -ConnectionString <SecureString> [-Database <String>]
[-KeyType <String>] [-MasterKeyType <String>]
[-BackoffPolicy <BackoffPolicy>] [-Environment <Environment>]
[-WhatIf] [-Confirm] [<CommonParameters>]
```

### Emulator

```powershell
Expand Down Expand Up @@ -157,6 +166,16 @@ PS C:\> $cosmosDbContext = New-CosmosDbContext -Account 'AlternateCloud' -Databa
Creates a CosmosDB context specifying the master key manually connecting
to an custom Cosmos DB endpoint.

### Example 9

```powershell
PS C:\> $connectionString = Get-CosmosDbAccountConnectionString -Name 'MyAzureCosmosDB' -ResourceGroupName 'MyCosmosDbResourceGroup'
PS C:\> $cosmosDbContext = New-CosmosDbContext -ConnectionString ($connectionString | ConvertTo-SecureString -AsPlainText -Force) -Database 'MyDatabase' -MasterKeyType 'PrimaryMasterKey'
```

Creates a CosmosDB context specifying the connection string connecting
to the Cosmos DB account.

## PARAMETERS

### -Account
Expand Down Expand Up @@ -208,6 +227,22 @@ Accept pipeline input: False
Accept wildcard characters: False
```
### -ConnectionString
The connection string used to access the Cosmos DB account.
```yaml
Type: SecureString
Parameter Sets: ConnectionString
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Database
The name of the database to access in the Cosmos DB account.
Expand Down Expand Up @@ -268,7 +303,7 @@ The supported values are:
```yaml
Type: Environment
Parameter Sets: Account, AzureAccount, Token
Parameter Sets: Account, AzureAccount, Token, ConnectionString
Aliases:
Accepted values: AzureChinaCloud, AzureCloud, AzureUSGovernment

Expand Down Expand Up @@ -320,7 +355,7 @@ will be deprecated in a future release. Do not use it.
```yaml
Type: String
Parameter Sets: Account, CustomAccount
Parameter Sets: Account, CustomAccount, ConnectionString
Aliases:
Accepted values: master, resource

Expand All @@ -338,7 +373,7 @@ the Cosmos DB.
```yaml
Type: String
Parameter Sets: CustomAzureAccount, AzureAccount
Parameter Sets: CustomAzureAccount, AzureAccount, ConnectionString
Aliases:
Accepted values: PrimaryMasterKey, SecondaryMasterKey, PrimaryReadonlyMasterKey, SecondaryReadonlyMasterKey

Expand Down
16 changes: 16 additions & 0 deletions source/Public/utils/New-CosmosDbContext.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ function New-CosmosDbContext
[System.String]
$Account,

[Parameter(Mandatory = $true, ParameterSetName = 'ConnectionString')]
[System.Security.SecureString]
$ConnectionString,

[Parameter()]
[ValidateScript({ Assert-CosmosDbDatabaseIdValid -Id $_ })]
[System.String]
Expand All @@ -31,6 +35,7 @@ function New-CosmosDbContext

[Parameter(ParameterSetName = 'Account')]
[Parameter(ParameterSetName = 'CustomAccount')]
[Parameter(ParameterSetName = 'ConnectionString')]
[ValidateSet('master', 'resource')]
[System.String]
$KeyType = 'master',
Expand All @@ -44,6 +49,7 @@ function New-CosmosDbContext

[Parameter(ParameterSetName = 'AzureAccount')]
[Parameter(ParameterSetName = 'CustomAzureAccount')]
[Parameter(ParameterSetName = 'ConnectionString')]
[ValidateSet('PrimaryMasterKey', 'SecondaryMasterKey', 'PrimaryReadonlyMasterKey', 'SecondaryReadonlyMasterKey')]
[System.String]
$MasterKeyType = 'PrimaryMasterKey',
Expand Down Expand Up @@ -74,6 +80,7 @@ function New-CosmosDbContext
[Parameter(ParameterSetName = 'Account')]
[Parameter(ParameterSetName = 'Token')]
[Parameter(ParameterSetName = 'AzureAccount')]
[Parameter(ParameterSetName = 'ConnectionString')]
[CosmosDB.Environment]
$Environment = [CosmosDB.Environment]::AzureCloud,

Expand Down Expand Up @@ -177,6 +184,15 @@ function New-CosmosDbContext
{
$BaseUri = Get-CosmosDbUri -Account $Account -Environment $Environment
}

'ConnectionString'
{
$decryptedConnectionString = $ConnectionString | Convert-CosmosDbSecureStringToString
$connectionStringParts = $decryptedConnectionString -replace ';', [System.Environment]::NewLine | ConvertFrom-StringData
$BaseUri = [System.Uri]::new($connectionStringParts.AccountEndpoint)
$Account = $BaseUri.Host.Split('.')[0]
$Key = $connectionStringParts.AccountKey | ConvertTo-SecureString -AsPlainText -Force
}
}

if ($PSCmdlet.ShouldProcess('Azure', ($LocalizedData.ShouldCreateAzureCosmosDBContext -f $Account, $Database, $BaseUri)))
Expand Down
20 changes: 20 additions & 0 deletions tests/Integration/CosmosDB.integration.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,26 @@ Describe 'Cosmos DB Module' -Tag 'Integration' {
}
}

Context 'When getting existing document using connection string as context' {
It 'Should not throw an exception' {
$connectionString = Get-CosmosDbAccountConnectionString `
-Name $script:testAccountName `
-ResourceGroupName $script:testResourceGroupName `
-Verbose

$connectionStringContext = New-CosmosDbContext `
-ConnectionString ($connectionString | ConvertTo-SecureString -AsPlainText -Force) `
-Database $script:testDatabase `
-Verbose

$script:result = Get-CosmosDbDocument `
-Context $connectionStringContext `
-CollectionId $script:testCollection `
-Id $script:testDocumentId `
-Verbose
}
}

Context 'When adding a stored procedure to the collection' {
It 'Should not throw an exception' {
$script:result = New-CosmosDbStoredProcedure `
Expand Down
26 changes: 26 additions & 0 deletions tests/Unit/CosmosDB.utils.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ console.log("done");

$script:testRequestBodyJson = '{"Tricky Body":"if (entityAlreadyExists)\r\n throw new Error(`root entity # ${entity.id} already created`);\r\nconsole.log(`new entity \"${entity.id}\" is about to be created...`);\r\nlet a = \u0027some value\u0027;\r\nconsole.log(\"done\");"}'

$script:testConnectionString = "AccountEndpoint=https://{0}.documents.azure.com:443/;AccountKey={1};" -f $script:testAccount, $script:testKey

Describe 'Custom types' -Tag 'Unit' {
Context 'CosmosDB.Context' {
It 'Should exist' {
Expand Down Expand Up @@ -799,6 +801,30 @@ console.log("done");
$script:result.Environment | Should -BeExactly 'AzureCloud'
}
}

Context 'When called with Connection String parameter' {
$script:result = $null

It 'Should not throw exception' {
$newCosmosDbContextParameters = @{
ConnectionString = ($script:testConnectionString | ConvertTo-SecureString -AsPlainText -Force)
Database = $script:testDatabase
}

{ $script:result = New-CosmosDbContext @newCosmosDbContextParameters } | Should -Not -Throw
}

It 'Should return expected result' {
$script:result.Account | Should -Be $script:testAccount
$script:result.Database | Should -Be $script:testDatabase
$script:result.BaseUri | Should -Be ('https://{0}.documents.azure.com/' -f $script:testAccount)
$script:result.Environment | Should -BeExactly 'AzureCloud'
$script:result.Key | Should -BeOfType [System.Security.SecureString]
$decryptedConnectionString = $script:result.Key | Convert-CosmosDbSecureStringToString
$decryptedConnectionString | Should -BeExactly $script:testKey
$script:result.KeyType | Should -BeExactly 'master'
}
}
}

Describe 'Get-CosmosDbUri' -Tag 'Unit' {
Expand Down

0 comments on commit 66c5c38

Please sign in to comment.