Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 174 additions & 31 deletions demos/analytics-using-managedcleanroom/README-API.md

Large diffs are not rendered by default.

232 changes: 199 additions & 33 deletions demos/analytics-using-managedcleanroom/README-CLI.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,11 @@ if ($persona -eq "woodgrove") {
}

$metadataFile = Join-Path $datastoreDir "$persona-datastore-metadata.json"
$datastoreMetadata | ConvertTo-Json -Depth 10 | Out-File -FilePath $metadataFile -Encoding utf8
$versionedMetadataFile = Join-Path $datastoreDir "$persona-datastore-metadata$datasetSuffix.json"
$metadataJson = $datastoreMetadata | ConvertTo-Json -Depth 10
$metadataJson | Out-File -FilePath $metadataFile -Encoding utf8
$metadataJson | Out-File -FilePath $versionedMetadataFile -Encoding utf8
Write-Host "Datastore metadata saved to: $metadataFile" -ForegroundColor Yellow
Write-Host "Versioned datastore metadata saved to: $versionedMetadataFile" -ForegroundColor Yellow

Write-Host "`nData preparation complete for '$persona' ($variant mode)." -ForegroundColor Green
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
Prerequisites:
- 05-prepare-data.ps1 (generates datastore metadata)
- 06-setup-oidc-storage.ps1 (generates identity metadata + issuer URL)
- 08-prepare-dataset-keys.ps1 (CPK only — generates KEKs, updates metadata)
For CPK, publish these dataset bodies before running 08-prepare-dataset-keys.ps1;
key preparation needs the SKR policy of the published dataset.
#>
param(
[Parameter(Mandatory)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
4. Wraps the DEK with the KEK (RSA-OAEP-SHA256, client-side).
5. Stores the wrapped DEK as a Key Vault secret.

This script makes frontend calls internally to fetch SKR policies.
The same script works regardless of whether the README uses AZ CLI or REST API.
This script uses HTTPS REST calls to fetch SKR policies; the managedcleanroom
CLI extension is not required and its configuration is not changed.

Prerequisites:
- 04-prepare-resources.ps1 must have been run.
Expand All @@ -36,7 +36,8 @@
Output directory.

.PARAMETER TokenFile
Token file for frontend authentication.
Token file for frontend authentication. If omitted, uses CLEANROOM_FRONTEND_TOKEN,
then MANAGEDCLEANROOM_ACCESS_TOKEN, then the current Azure CLI ARM access token.
#>
param(
[Parameter(Mandatory)]
Expand Down Expand Up @@ -99,33 +100,53 @@ if ($feBase.EndsWith('/collaborations')) {
$feBase = $feBase.Substring(0, $feBase.Length - '/collaborations'.Length)
}

# Try CLI first, fallback to REST
function Get-SkrPolicy {
param([string]$DatasetName)

# Try az CLI
$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION = "1"
if ($TokenFile) {
$env:MANAGEDCLEANROOM_ACCESS_TOKEN = (Get-Content $TokenFile -Raw).Trim()
$endpointUri = $null
if (-not [Uri]::TryCreate($feBase, [UriKind]::Absolute, [ref]$endpointUri) -or
$endpointUri.Scheme -ne "https" -or $endpointUri.Query -or $endpointUri.Fragment -or
$endpointUri.UserInfo) {
throw "frontendEndpoint must be an absolute HTTPS URL without credentials, query, or fragment."
}
az managedcleanroom frontend configure --endpoint $feBase 2>&1 | Out-Null

$PSNativeCommandUseErrorActionPreference = $false
$raw = az managedcleanroom frontend analytics skr-policy `
--collaboration-id $collaborationId `
--dataset-id $DatasetName 2>&1
$PSNativeCommandUseErrorActionPreference = $true

if ($LASTEXITCODE -eq 0) {
$jsonLines = $raw | Where-Object { $_ -is [string] }
return $jsonLines | ConvertFrom-Json
if ($TokenFile) {
if (-not (Test-Path -LiteralPath $TokenFile -PathType Leaf)) {
throw "Frontend token file not found: $TokenFile"
}
$token = ([string](Get-Content -LiteralPath $TokenFile -Raw)).Trim()
} elseif ($env:CLEANROOM_FRONTEND_TOKEN) {
$token = $env:CLEANROOM_FRONTEND_TOKEN.Trim()
} elseif ($env:MANAGEDCLEANROOM_ACCESS_TOKEN) {
$token = $env:MANAGEDCLEANROOM_ACCESS_TOKEN.Trim()
} else {
try {
$token = az account get-access-token --resource "https://management.azure.com/" `
--query accessToken -o tsv
if ($LASTEXITCODE -ne 0) { throw "Azure CLI exited with code $LASTEXITCODE." }
} catch {
throw "Could not acquire a frontend token. Supply -TokenFile or CLEANROOM_FRONTEND_TOKEN. $($_.Exception.Message)"
}
$token = ($token -join "`n").Trim()
}
if ([string]::IsNullOrWhiteSpace($token)) {
throw "Frontend token is empty. Supply a valid -TokenFile or CLEANROOM_FRONTEND_TOKEN."
}

# Fallback to REST
$token = if ($TokenFile) { (Get-Content $TokenFile -Raw).Trim() } else { az account get-access-token --query accessToken -o tsv }
$headers = @{ Authorization = "Bearer $token"; "Content-Type" = "application/json" }
$url = "$feBase/collaborations/$collaborationId/analytics/datasets/$DatasetName/skrpolicy?api-version=2026-03-01-preview"
return Invoke-RestMethod -Uri $url -Headers $headers -Method Get -SkipCertificateCheck
$encodedCollaborationId = [Uri]::EscapeDataString($collaborationId)
$encodedDatasetName = [Uri]::EscapeDataString($DatasetName)
$url = "$feBase/collaborations/$encodedCollaborationId/analytics/datasets/$encodedDatasetName/skrpolicy?api-version=2026-03-01-preview"
try {
$policy = Invoke-RestMethod -Uri $url -Headers $headers -Method Get -ErrorAction Stop
} catch {
throw "Failed to fetch SKR policy for dataset '$DatasetName': $($_.Exception.Message)"
}
if (-not $policy.version -or @($policy.anyOf).Count -eq 0 -or -not $policy.anyOf[0]) {
throw "Frontend returned an invalid SKR policy for dataset '$DatasetName': expected version and nonempty anyOf."
}

return $policy
}

# -- Process each dataset ----------------------------------------------------------
Expand Down
163 changes: 104 additions & 59 deletions demos/analytics-using-managedcleanroom/scripts/11-download-output.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
- SSE: Downloads via az storage blob download
- CPK: Downloads via azcopy --cpk-by-value using the DEK

If -JobId is provided, filters to blobs matching that run.
Otherwise downloads the latest CSV blob.
If -JobId is provided, downloads all CSV partitions under that exact run's
Analytics/<date>/<run-id>/ path. Otherwise downloads all CSV outputs.
Preserves blob paths locally to avoid collisions between runs/partitions.

.PARAMETER resourceGroup
Azure resource group (for loading generated names).
Expand All @@ -21,7 +22,8 @@

.PARAMETER JobId
Optional job ID from query run (e.g., "cl-spark-<uuid>").
Filters output to this specific run.
Filters output to this specific run in both SSE and CPK modes.
Also accepts the run UUID without the cl-spark- prefix.

.PARAMETER OutputDir
Local directory for downloaded output (default: ./generated/output).
Expand Down Expand Up @@ -64,87 +66,130 @@ if (-not (Test-Path $namesFile)) {
. $namesFile

# Detect encryption mode
$datastoreMetadataFile = Join-Path $outDir "datastores" "$persona-datastore-metadata.json"
$versionedMetadataFile = Join-Path $outDir "datastores" "$persona-datastore-metadata$datasetSuffix.json"
$datastoreMetadataFile = if (Test-Path $versionedMetadataFile) {
$versionedMetadataFile
} else {
Join-Path $outDir "datastores" "$persona-datastore-metadata.json"
}
if (-not (Test-Path $datastoreMetadataFile)) {
Write-Host "ERROR: '$datastoreMetadataFile' not found." -ForegroundColor Red
exit 1
}
$datastoreMeta = Get-Content $datastoreMetadataFile -Raw | ConvertFrom-Json
$isCpk = ($datastoreMeta.input.encryptionMode -eq "CPK")

$outputContainer = "woodgrove-output$datasetSuffix"
$outputMeta = $datastoreMeta.output
if (-not $outputMeta.containerName -or $outputMeta.encryptionMode -notin @("SSE", "CPK")) {
throw "Output metadata must specify containerName and encryptionMode (SSE or CPK): $datastoreMetadataFile"
}
$isCpk = ($outputMeta.encryptionMode -eq "CPK")
$outputContainer = $outputMeta.containerName
$storageUrl = if ($outputMeta.storeUrl) {
$outputMeta.storeUrl.TrimEnd('/')
} else {
"https://$STORAGE_ACCOUNT_NAME.blob.core.windows.net"
}
$storageUri = $null
if (-not [Uri]::TryCreate($storageUrl, [UriKind]::Absolute, [ref]$storageUri) -or
$storageUri.Scheme -ne "https" -or $storageUri.Query -or $storageUri.Fragment -or $storageUri.UserInfo) {
throw "Output storeUrl must be an absolute HTTPS storage endpoint without credentials, query, or fragment."
}
$storageAccountName = $storageUri.Host.Split('.')[0]
$runId = if ($JobId) { $JobId -creplace '^cl-spark-', '' } else { $null }
if ($JobId -and ([string]::IsNullOrWhiteSpace($runId) -or $runId -match '[/\\]')) {
throw "JobId must be a run ID or cl-spark-<run-id>, not a path."
}

Write-Host "=== Downloading query output ===" -ForegroundColor Cyan
Write-Host " Storage account: $STORAGE_ACCOUNT_NAME" -ForegroundColor Yellow
Write-Host " Storage account: $storageAccountName" -ForegroundColor Yellow
Write-Host " Container: $outputContainer" -ForegroundColor Yellow
Write-Host " Encryption: $(if ($isCpk) { 'CPK' } else { 'SSE' })" -ForegroundColor Yellow
if ($JobId) { Write-Host " Job ID filter: $JobId" -ForegroundColor Yellow }

New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null
$blobs = az storage blob list --account-name $storageAccountName `
--container-name $outputContainer `
--prefix "Analytics/" --auth-mode login -o json | ConvertFrom-Json
if ($LASTEXITCODE -ne 0) { throw "Failed to list output blobs in '$outputContainer'." }

$csvBlobs = @($blobs | Where-Object {
$segments = $_.name.Split('/')
$_.name.EndsWith('.csv', [StringComparison]::OrdinalIgnoreCase) -and
$segments.Count -ge 4 -and $segments[0] -ceq "Analytics" -and
(-not $runId -or $segments[2] -ceq $runId)
})
if ($csvBlobs.Count -eq 0) {
Write-Host "No CSV output blobs found$(if ($JobId) { " for job '$JobId'" })." -ForegroundColor Yellow
return
}

if ($isCpk) {
# -- CPK: Download via azcopy --cpk-by-value ----------------------------------
$dekFile = Join-Path $outDir "datastores" "keys" "woodgrove-output-csv$datasetSuffix-dek.bin"
if (-not (Test-Path $dekFile)) {
Write-Host "ERROR: DEK file '$dekFile' not found." -ForegroundColor Red
exit 1
$downloads = @($csvBlobs | ForEach-Object {
$localFile = [IO.Path]::GetFullPath((Join-Path $OutputDir $_.name))
$outputPrefix = $OutputDir.TrimEnd([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) +
[IO.Path]::DirectorySeparatorChar
if (-not $localFile.StartsWith($outputPrefix, [StringComparison]::OrdinalIgnoreCase)) {
throw "Output blob path escapes OutputDir: $($_.name)"
}
[pscustomobject]@{ BlobName = $_.name; LocalFile = $localFile }
})

$dekBytes = [System.IO.File]::ReadAllBytes($dekFile)
$env:CPK_ENCRYPTION_KEY = [Convert]::ToBase64String($dekBytes)
$env:CPK_ENCRYPTION_KEY_SHA256 = [Convert]::ToBase64String(
[System.Security.Cryptography.SHA256]::HashData($dekBytes))
$env:AZCOPY_AUTO_LOGIN_TYPE = "AZCLI"
$env:AZCOPY_TENANT_ID = (az account show --query tenantId -o tsv)

$srcUrl = "https://$STORAGE_ACCOUNT_NAME.blob.core.windows.net/$outputContainer/Analytics/*"
Write-Host " Downloading via azcopy --cpk-by-value..." -ForegroundColor Cyan

azcopy copy $srcUrl $OutputDir --cpk-by-value --recursive --include-pattern "*.csv" 2>&1 | ForEach-Object {
Write-Host " $_" -ForegroundColor Gray
if ($isCpk) {
$dekFile = $outputMeta._local.dekFile
if (-not $dekFile -or -not (Test-Path -LiteralPath $dekFile -PathType Leaf)) {
throw "Output DEK file from metadata was not found: '$dekFile'."
}

# Cleanup env vars
Remove-Item env:CPK_ENCRYPTION_KEY -ErrorAction SilentlyContinue
Remove-Item env:CPK_ENCRYPTION_KEY_SHA256 -ErrorAction SilentlyContinue
Remove-Item env:AZCOPY_AUTO_LOGIN_TYPE -ErrorAction SilentlyContinue
Remove-Item env:AZCOPY_TENANT_ID -ErrorAction SilentlyContinue
} else {
# -- SSE: Download via az storage blob download --------------------------------
$blobs = az storage blob list --account-name $STORAGE_ACCOUNT_NAME `
--container-name $outputContainer `
--prefix "Analytics/" --auth-mode login -o json | ConvertFrom-Json

# Filter to CSV blobs (exclude .crc checksum files)
$csvBlobs = $blobs | Where-Object {
$_.name -match '\.csv$' -and $_.name -notmatch '\.crc$'
$dekBytes = Get-Content -LiteralPath $dekFile -AsByteStream -Raw
if ($dekBytes.Length -ne 32) { throw "Output DEK must contain exactly 32 bytes: $dekFile" }

$environment = @{
CPK_ENCRYPTION_KEY = [Convert]::ToBase64String($dekBytes)
CPK_ENCRYPTION_KEY_SHA256 = [Convert]::ToBase64String(
[System.Security.Cryptography.SHA256]::HashData($dekBytes))
AZCOPY_AUTO_LOGIN_TYPE = "AZCLI"
AZCOPY_TENANT_ID = (az account show --query tenantId -o tsv)
}

# Optionally filter by job ID
if ($JobId) {
$runUuid = $JobId -replace '^cl-spark-', ''
$csvBlobs = $csvBlobs | Where-Object { $_.name -match $runUuid }
if ($LASTEXITCODE -ne 0 -or -not $environment.AZCOPY_TENANT_ID) {
throw "Could not determine the Azure CLI tenant for AzCopy."
}
$previousEnvironment = @{}
try {
foreach ($name in $environment.Keys) {
$previousEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
[Environment]::SetEnvironmentVariable($name, $environment[$name], 'Process')
}

if (-not $csvBlobs -or $csvBlobs.Count -eq 0) {
Write-Host "No CSV output blobs found." -ForegroundColor Yellow
exit 0
foreach ($download in $downloads) {
New-Item -ItemType Directory -Path (Split-Path $download.LocalFile -Parent) -Force | Out-Null
$blobPath = ($download.BlobName.Split('/') | ForEach-Object { [Uri]::EscapeDataString($_) }) -join '/'
$srcUrl = "$storageUrl/$([Uri]::EscapeDataString($outputContainer))/$blobPath"
Write-Host " Downloading: $($download.BlobName)" -ForegroundColor Cyan
azcopy copy $srcUrl $download.LocalFile --cpk-by-value --overwrite=true 2>&1 | ForEach-Object {
Write-Host " $_" -ForegroundColor Gray
}
if ($LASTEXITCODE -ne 0) { throw "AzCopy failed to download '$($download.BlobName)' (exit $LASTEXITCODE)." }
}
} finally {
foreach ($name in $previousEnvironment.Keys) {
if ($null -eq $previousEnvironment[$name]) {
Remove-Item -LiteralPath "Env:$name" -ErrorAction SilentlyContinue
} else {
[Environment]::SetEnvironmentVariable($name, $previousEnvironment[$name], 'Process')
}
}
}

# Download each matching blob
foreach ($blob in $csvBlobs) {
$localFile = Join-Path $OutputDir (Split-Path $blob.name -Leaf)
Write-Host " Downloading: $($blob.name)" -ForegroundColor Cyan
az storage blob download --account-name $STORAGE_ACCOUNT_NAME `
} else {
foreach ($download in $downloads) {
New-Item -ItemType Directory -Path (Split-Path $download.LocalFile -Parent) -Force | Out-Null
Write-Host " Downloading: $($download.BlobName)" -ForegroundColor Cyan
az storage blob download --account-name $storageAccountName `
--container-name $outputContainer `
--name $blob.name `
--file $localFile `
--name $download.BlobName `
--file $download.LocalFile `
--auth-mode login --output none
if ($LASTEXITCODE -ne 0) { throw "Failed to download '$($download.BlobName)'." }
}
}

# Display results
$csvFiles = Get-ChildItem $OutputDir -Recurse -Filter *.csv
$csvFiles = @($downloads | ForEach-Object { Get-Item -LiteralPath $_.LocalFile })
if ($csvFiles.Count -gt 0) {
Write-Host "`n=== Output ($($csvFiles.Count) CSV file(s)) ===" -ForegroundColor Green
foreach ($f in $csvFiles) {
Expand Down
Loading
Loading