2 Commits

Author SHA1 Message Date
GraceSolutions 14c8c4f384 Fix import merging and add count/scope logging across cmdlets
Publish to PowerShell Gallery / build (pull_request) Successful in 24s
Publish to PowerShell Gallery / release (pull_request) Successful in 15s
Publish to PowerShell Gallery / publish (pull_request) Successful in 8s
InfisicalSecretsClient.List now merges dto.Imports[].Secrets with dto.Secrets using local-wins precedence, restoring imported secrets that were previously dropped when -IncludeImports was set.

Get-InfisicalSecret, ConvertTo-InfisicalSecretDictionary, Export-InfisicalSecrets, Import-InfisicalSecret, New/Update/Remove-InfisicalSecret, and Start-InfisicalProcess now emit Information-level counts for retrieved/processed/injected items.

All collection-returning Get-* cmdlets (Folder, Project, Organization, Environment, Tag, SubOrganization, Certificate, CertificateAuthority, CertificateApplication, CertificatePolicy, CertificateProfile, PkiSubscriber) now log returned counts.

Get-InfisicalEnvironmentVariable gains an optional -Scope (EnvironmentVariableTarget) parameter plus per-scope verbose tracing and Information-level found/not-found outcome lines.
2026-06-15 22:18:02 -04:00
GraceSolutions 6318d06362 Add GitHub Actions workflow for PowerShell Gallery publish
Publish to PowerShell Gallery / release (pull_request) Has been cancelled
Publish to PowerShell Gallery / publish (pull_request) Has been cancelled
Publish to PowerShell Gallery / build (pull_request) Has been cancelled
Mirrors the Gitea workflow with GitHub-specific adaptations: ubuntu-latest runner, actions/upload-artifact and actions/download-artifact v4, Bearer auth with X-GitHub-Api-Version header, /pull/ URL path, upload_url URI template handling on uploads.github.com, contents:write permission on the release job, and on-demand Install-Module of Microsoft.PowerShell.PSResourceGet for CurrentUser.
2026-06-10 16:54:22 -04:00
27 changed files with 492 additions and 18 deletions
+328
View File
@@ -0,0 +1,328 @@
name: Publish to PowerShell Gallery
on:
pull_request:
types: [closed]
branches: [main]
jobs:
build:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Verify host prerequisites (pwsh, dotnet)
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$missing = @()
if (-not (Get-Command pwsh -ErrorAction SilentlyContinue)) { $missing += 'pwsh' }
if (-not (Get-Command dotnet -ErrorAction SilentlyContinue)) { $missing += 'dotnet' }
if ($missing.Count -gt 0) {
throw "Host runner is missing required tool(s): $($missing -join ', '). Provision them on the runner host."
}
Write-Host ("pwsh: " + (pwsh -NoProfile -Command '$PSVersionTable.PSVersion.ToString()'))
Write-Host ("dotnet: " + (dotnet --version))
Write-Host '--- dotnet --info ---'
dotnet --info
Write-Host '--- disk free ---'
df -h .
Write-Host '--- memory ---'
free -m
- name: Restore NuGet packages
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
Write-Host '==> dotnet restore src/PSInfisicalAPI/PSInfisicalAPI.csproj'
dotnet restore src/PSInfisicalAPI/PSInfisicalAPI.csproj --verbosity normal
if ($LASTEXITCODE -ne 0) { throw "Restore of PSInfisicalAPI.csproj failed with exit code $LASTEXITCODE" }
Write-Host '==> dotnet restore src/PSInfisicalAPI.Tests/PSInfisicalAPI.Tests.csproj'
dotnet restore src/PSInfisicalAPI.Tests/PSInfisicalAPI.Tests.csproj --verbosity normal
if ($LASTEXITCODE -ne 0) { throw "Restore of PSInfisicalAPI.Tests.csproj failed with exit code $LASTEXITCODE" }
- name: Build module
shell: pwsh
run: ./build.ps1
- name: Validate module manifest
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$manifestPath = Join-Path $PWD 'Module/PSInfisicalAPI/PSInfisicalAPI.psd1'
$manifest = Test-ModuleManifest -Path $manifestPath
Write-Host "Manifest OK: $($manifest.Name) $($manifest.Version)"
- name: Upload module artifact
uses: actions/upload-artifact@v4
with:
name: PSInfisicalAPI-module
path: Module/PSInfisicalAPI
if-no-files-found: error
retention-days: 7
release:
needs: build
if: ${{ success() && github.event.pull_request.merged == true }}
runs-on: ubuntu-latest
permissions:
contents: write
outputs:
version: ${{ steps.meta.outputs.version }}
tag: ${{ steps.meta.outputs.tag }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Verify host prerequisites (pwsh)
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
if (-not (Get-Command pwsh -ErrorAction SilentlyContinue)) {
throw "Host runner is missing required tool: pwsh. Provision it on the runner host."
}
Write-Host ("pwsh: " + (pwsh -NoProfile -Command '$PSVersionTable.PSVersion.ToString()'))
- name: Download module artifact
uses: actions/download-artifact@v4
with:
name: PSInfisicalAPI-module
path: Module/PSInfisicalAPI
- name: Resolve module version and tag
id: meta
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$manifestPath = Join-Path $PWD 'Module/PSInfisicalAPI/PSInfisicalAPI.psd1'
$manifest = Test-ModuleManifest -Path $manifestPath
$version = $manifest.Version.ToString()
$tag = $version
Write-Host "Module version: $version"
Write-Host "Release tag: $tag"
"version=$version" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
"tag=$tag" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
- name: Package module as release asset
shell: pwsh
env:
VERSION: ${{ steps.meta.outputs.version }}
run: |
$ErrorActionPreference = 'Stop'
$zipPath = Join-Path $PWD "PSInfisicalAPI-$($env:VERSION).zip"
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
Compress-Archive -Path 'Module/PSInfisicalAPI/*' -DestinationPath $zipPath -Force
Write-Host "Created: $zipPath ($([math]::Round((Get-Item $zipPath).Length / 1KB, 1)) KB)"
- name: Create GitHub release
shell: pwsh
env:
GITHUB_TOKEN: ${{ github.token }}
API_URL: ${{ github.api_url }}
REPO: ${{ github.repository }}
TAG: ${{ steps.meta.outputs.tag }}
VERSION: ${{ steps.meta.outputs.version }}
COMMIT_SHA: ${{ github.sha }}
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
SERVER_URL: ${{ github.server_url }}
RUN_ID: ${{ github.run_id }}
run: |
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
trap { Write-Host "==> RELEASE STEP FAILED: $($_ | Out-String)"; Write-Host ($_.ScriptStackTrace); exit 1 }
Write-Host "==> [1/8] Validating inputs"
Write-Host " TAG=$($env:TAG)"
Write-Host " VERSION=$($env:VERSION)"
Write-Host " REPO=$($env:REPO)"
Write-Host " API_URL=$($env:API_URL)"
Write-Host " SERVER_URL=$($env:SERVER_URL)"
Write-Host " PR_NUMBER=$($env:PR_NUMBER)"
Write-Host " RUN_ID=$($env:RUN_ID)"
if ([string]::IsNullOrWhiteSpace($env:GITHUB_TOKEN)) { throw "github.token is empty." }
if ([string]::IsNullOrWhiteSpace($env:TAG)) { throw "TAG is empty." }
if ([string]::IsNullOrWhiteSpace($env:VERSION)) { throw "VERSION is empty." }
if ([string]::IsNullOrWhiteSpace($env:API_URL)) { throw "API_URL is empty." }
if ([string]::IsNullOrWhiteSpace($env:REPO)) { throw "REPO is empty." }
if ([string]::IsNullOrWhiteSpace($env:COMMIT_SHA)) { throw "COMMIT_SHA is empty." }
Write-Host "==> [2/8] Deriving metadata"
$shortSha = $env:COMMIT_SHA.Substring(0, [Math]::Min(12, $env:COMMIT_SHA.Length))
$buildUtc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
$runUrl = "$($env:SERVER_URL)/$($env:REPO)/actions/runs/$($env:RUN_ID)"
$prUrl = "$($env:SERVER_URL)/$($env:REPO)/pull/$($env:PR_NUMBER)"
Write-Host " shortSha=$shortSha"
Write-Host "==> [3/8] Extracting CHANGELOG section"
$changelogSection = ''
if (Test-Path 'CHANGELOG.md') {
$lines = [System.IO.File]::ReadAllLines('CHANGELOG.md')
$start = -1; $end = $lines.Length
for ($i = 0; $i -lt $lines.Length; $i++) {
if ($lines[$i] -match "^##\s+$([regex]::Escape($env:VERSION))\s*$") { $start = $i + 1; continue }
if ($start -ge 0 -and $lines[$i] -match '^##\s+') { $end = $i; break }
}
if ($start -ge 0) {
$changelogSection = ($lines[$start..($end - 1)] -join "`n").Trim()
}
}
Write-Host " CHANGELOG section length: $($changelogSection.Length) chars"
Write-Host "==> [4/8] Building release body"
$changelogText = if ($changelogSection) { $changelogSection } else { '_No CHANGELOG section found for this version._' }
$sb = New-Object System.Text.StringBuilder
[void]$sb.AppendLine("**PSInfisicalAPI $($env:VERSION)**")
[void]$sb.AppendLine('')
[void]$sb.AppendLine('| Field | Value |')
[void]$sb.AppendLine('| --- | --- |')
[void]$sb.AppendLine("| Version | ``$($env:VERSION)`` |")
[void]$sb.AppendLine("| Tag | ``$($env:TAG)`` |")
[void]$sb.AppendLine("| Commit | [``$shortSha``]($($env:SERVER_URL)/$($env:REPO)/commit/$($env:COMMIT_SHA)) |")
[void]$sb.AppendLine("| Built (UTC) | $buildUtc |")
[void]$sb.AppendLine("| Merged PR | [#$($env:PR_NUMBER) $($env:PR_TITLE)]($prUrl) by @$($env:PR_AUTHOR) |")
[void]$sb.AppendLine("| Workflow run | [$($env:RUN_ID)]($runUrl) |")
[void]$sb.AppendLine('')
[void]$sb.AppendLine('## Changes')
[void]$sb.AppendLine($changelogText)
[void]$sb.AppendLine('')
[void]$sb.AppendLine('## Install')
[void]$sb.AppendLine('```powershell')
[void]$sb.AppendLine("Install-Module -Name PSInfisicalAPI -RequiredVersion $($env:VERSION) -Scope CurrentUser")
[void]$sb.AppendLine('```')
$body = $sb.ToString()
Write-Host " body length: $($body.Length) chars"
$headers = @{
Authorization = "Bearer $($env:GITHUB_TOKEN)"
Accept = 'application/vnd.github+json'
'X-GitHub-Api-Version' = '2022-11-28'
}
$createUri = "$($env:API_URL)/repos/$($env:REPO)/releases"
Write-Host "==> [5/8] Checking for existing release tag: $createUri/tags/$($env:TAG)"
$existing = $null
try {
$existing = Invoke-RestMethod -Method Get -Headers $headers `
-Uri "$createUri/tags/$($env:TAG)" -ErrorAction Stop
} catch {
$status = $null
try { $status = $_.Exception.Response.StatusCode.value__ } catch { }
if ($status -ne 404) {
Write-Host " Lookup failed (status=$status): $($_.Exception.Message)"
throw
}
Write-Host " No existing release (404)."
}
if ($existing) {
Write-Host " Release tag '$($env:TAG)' already exists (id=$($existing.id)); skipping creation."
return
}
Write-Host "==> [6/8] Creating release"
$payload = @{
tag_name = $env:TAG
target_commitish = $env:COMMIT_SHA
name = "PSInfisicalAPI $($env:VERSION)"
body = $body
draft = $false
prerelease = $false
} | ConvertTo-Json -Depth 4
Write-Host " payload bytes: $([System.Text.Encoding]::UTF8.GetByteCount($payload))"
$release = Invoke-RestMethod -Method Post -Uri $createUri -Headers $headers `
-ContentType 'application/json' -Body $payload
Write-Host " Created release id=$($release.id) at $($release.html_url)"
Write-Host "==> [7/8] Locating release asset"
$assetPath = Join-Path $PWD "PSInfisicalAPI-$($env:VERSION).zip"
if (-not (Test-Path $assetPath)) { throw "Release asset not found at: $assetPath" }
$fileBytes = [System.IO.File]::ReadAllBytes($assetPath)
Write-Host " Asset: $assetPath ($([math]::Round($fileBytes.Length / 1KB, 1)) KB)"
Write-Host "==> [8/8] Uploading asset"
# GitHub returns a URI Template in upload_url (e.g. "https://uploads.github.com/.../assets{?name,label}").
# Strip the template suffix and append the asset name query.
$uploadBase = ($release.upload_url -replace '\{.*\}$', '')
$uploadUri = "$uploadBase`?name=PSInfisicalAPI-$($env:VERSION).zip"
Invoke-RestMethod -Method Post -Uri $uploadUri -Headers $headers `
-ContentType 'application/zip' -Body $fileBytes | Out-Null
Write-Host "==> Done: uploaded PSInfisicalAPI-$($env:VERSION).zip"
publish:
needs: release
if: ${{ success() && github.event.pull_request.merged == true }}
runs-on: ubuntu-latest
steps:
- name: Verify host prerequisites (pwsh)
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
if (-not (Get-Command pwsh -ErrorAction SilentlyContinue)) {
throw "Host runner is missing required tool: pwsh. Provision it on the runner host."
}
Write-Host ("pwsh: " + (pwsh -NoProfile -Command '$PSVersionTable.PSVersion.ToString()'))
- name: Download module artifact
uses: actions/download-artifact@v4
with:
name: PSInfisicalAPI-module
path: Module/PSInfisicalAPI
- name: Bootstrap Microsoft.PowerShell.PSResourceGet
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
if (-not (Get-Module -ListAvailable -Name Microsoft.PowerShell.PSResourceGet)) {
Write-Host "==> Installing Microsoft.PowerShell.PSResourceGet for CurrentUser"
Install-Module -Name Microsoft.PowerShell.PSResourceGet -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop
}
Import-Module Microsoft.PowerShell.PSResourceGet -ErrorAction Stop
$existing = Get-PSResourceRepository -Name PSGallery -ErrorAction SilentlyContinue
if (-not $existing) {
Write-Host "==> Registering PSGallery repository"
Register-PSResourceRepository -PSGallery -Trusted -ErrorAction Stop
} else {
Write-Host "==> PSGallery already registered; ensuring Trusted + ApiVersion v2"
Set-PSResourceRepository -Name PSGallery -Trusted -ApiVersion v2 -ErrorAction Stop
}
Get-PSResourceRepository -Name PSGallery | Format-Table Name,Uri,Trusted,ApiVersion
- name: Verify PowerShell Gallery API key is configured
shell: pwsh
env:
PSGALLERY_API_KEY: ${{ secrets.PSGALLERY_API_KEY }}
run: |
if ([string]::IsNullOrWhiteSpace($env:PSGALLERY_API_KEY)) {
throw "Repository secret 'PSGALLERY_API_KEY' is not configured."
}
- name: Re-validate downloaded module manifest
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$manifestPath = Join-Path $PWD 'Module/PSInfisicalAPI/PSInfisicalAPI.psd1'
$manifest = Test-ModuleManifest -Path $manifestPath
Write-Host "Manifest OK: $($manifest.Name) $($manifest.Version)"
- name: Publish to PowerShell Gallery
shell: pwsh
env:
PSGALLERY_API_KEY: ${{ secrets.PSGALLERY_API_KEY }}
run: |
$ErrorActionPreference = 'Stop'
$moduleDir = Join-Path $PWD 'Module/PSInfisicalAPI'
Write-Host "Publishing module from: $moduleDir"
Publish-PSResource `
-Path $moduleDir `
-Repository PSGallery `
-ApiKey $env:PSGALLERY_API_KEY `
-Verbose
+39 -9
View File
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -1,6 +1,6 @@
@{ @{
RootModule = 'PSInfisicalAPI.psm1' RootModule = 'PSInfisicalAPI.psm1'
ModuleVersion = '2026.06.10.2018' ModuleVersion = '2026.06.16.0217'
GUID = 'b8a2f3d4-7c51-4d2f-9e6a-1f0c8b3d4e51' GUID = 'b8a2f3d4-7c51-4d2f-9e6a-1f0c8b3d4e51'
Author = 'Grace Solutions' Author = 'Grace Solutions'
CompanyName = 'Grace Solutions' CompanyName = 'Grace Solutions'
@@ -74,7 +74,7 @@
LicenseUri = 'https://www.gnu.org/licenses/agpl-3.0.html' LicenseUri = 'https://www.gnu.org/licenses/agpl-3.0.html'
ProjectUri = 'https://prod.git.gracesolution.info/gsadmin/PSInfisicalAPI' ProjectUri = 'https://prod.git.gracesolution.info/gsadmin/PSInfisicalAPI'
ReleaseNotes = 'See CHANGELOG.md in the project repository for release history.' ReleaseNotes = 'See CHANGELOG.md in the project repository for release history.'
CommitHash = 'daf1cdce6576' CommitHash = '6318d06362ad'
} }
} }
} }
Binary file not shown.
@@ -49,14 +49,18 @@ namespace PSInfisicalAPI.Cmdlets
{ {
try try
{ {
Logger.Information("ConvertTo-InfisicalSecretDictionary", string.Concat("Processing ", _buffer.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), " input secret(s)."));
if (AsPlainText.IsPresent) if (AsPlainText.IsPresent)
{ {
Dictionary<string, string> plain = BuildDictionary<string>(secret => secret.GetPlainTextValue()); Dictionary<string, string> plain = BuildDictionary<string>(secret => secret.GetPlainTextValue());
Logger.Information("ConvertTo-InfisicalSecretDictionary", string.Concat("Built plain-text dictionary with ", plain.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), " entry/entries."));
WriteObject(plain); WriteObject(plain);
} }
else else
{ {
Dictionary<string, SecureString> secure = BuildDictionary<SecureString>(secret => secret.SecretValue); Dictionary<string, SecureString> secure = BuildDictionary<SecureString>(secret => secret.SecretValue);
Logger.Information("ConvertTo-InfisicalSecretDictionary", string.Concat("Built SecureString dictionary with ", secure.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), " entry/entries."));
WriteObject(secure); WriteObject(secure);
} }
} }
@@ -75,6 +75,8 @@ namespace PSInfisicalAPI.Cmdlets
{ {
} }
Logger.Information("Export-InfisicalSecrets", string.Concat("Exporting ", _buffer.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), " secret(s) as ", Format.ToString(), (Path != null ? string.Concat(" to '", Path.FullName, "'") : string.Empty), "."));
InfisicalExportRequest request = new InfisicalExportRequest InfisicalExportRequest request = new InfisicalExportRequest
{ {
Secrets = ApplySecretsPrefix(_buffer, SecretsPrefix, ForceSecretsPrefix.IsPresent), Secrets = ApplySecretsPrefix(_buffer, SecretsPrefix, ForceSecretsPrefix.IsPresent),
@@ -46,6 +46,7 @@ namespace PSInfisicalAPI.Cmdlets
} }
InfisicalCertificateApplication[] all = client.ListCertificateApplications(connection, ProjectId, Limit, Offset); InfisicalCertificateApplication[] all = client.ListCertificateApplications(connection, ProjectId, Limit, Offset);
Logger.Information("Get-InfisicalCertificateApplication", string.Concat("Returned ", all.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " certificate application(s)."));
foreach (InfisicalCertificateApplication app in all) foreach (InfisicalCertificateApplication app in all)
{ {
WriteObject(app); WriteObject(app);
@@ -52,6 +52,7 @@ namespace PSInfisicalAPI.Cmdlets
} }
} }
Logger.Information("Get-InfisicalCertificateAuthority", string.Concat("Returned ", all.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " certificate authority/authorities (kind=", Kind, ")."));
foreach (InfisicalCertificateAuthority ca in all) foreach (InfisicalCertificateAuthority ca in all)
{ {
WriteObject(ca); WriteObject(ca);
@@ -129,6 +129,8 @@ namespace PSInfisicalAPI.Cmdlets
query.Offset = (query.Offset ?? 0) + page.Certificates.Length; query.Offset = (query.Offset ?? 0) + page.Certificates.Length;
} }
Logger.Information("Get-InfisicalCertificate", string.Concat("Returned ", emitted.ToString(System.Globalization.CultureInfo.InvariantCulture), " certificate(s)."));
} }
catch (Exception exception) catch (Exception exception)
{ {
@@ -39,6 +39,7 @@ namespace PSInfisicalAPI.Cmdlets
} }
InfisicalCertificatePolicy[] all = client.ListCertificatePolicies(connection, ProjectId, Limit, Offset); InfisicalCertificatePolicy[] all = client.ListCertificatePolicies(connection, ProjectId, Limit, Offset);
Logger.Information("Get-InfisicalCertificatePolicy", string.Concat("Returned ", all.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " certificate policy/policies."));
foreach (InfisicalCertificatePolicy policy in all) foreach (InfisicalCertificatePolicy policy in all)
{ {
WriteObject(policy); WriteObject(policy);
@@ -42,6 +42,7 @@ namespace PSInfisicalAPI.Cmdlets
bool? includeConfigs = MyInvocation.BoundParameters.ContainsKey("IncludeConfigs") ? (bool?)IncludeConfigs.IsPresent : null; bool? includeConfigs = MyInvocation.BoundParameters.ContainsKey("IncludeConfigs") ? (bool?)IncludeConfigs.IsPresent : null;
InfisicalCertificateProfile[] all = client.ListCertificateProfiles(connection, ProjectId, Limit, Offset, includeConfigs); InfisicalCertificateProfile[] all = client.ListCertificateProfiles(connection, ProjectId, Limit, Offset, includeConfigs);
Logger.Information("Get-InfisicalCertificateProfile", string.Concat("Returned ", all.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " certificate profile(s)."));
foreach (InfisicalCertificateProfile profile in all) foreach (InfisicalCertificateProfile profile in all)
{ {
WriteObject(profile); WriteObject(profile);
@@ -35,6 +35,7 @@ namespace PSInfisicalAPI.Cmdlets
} }
InfisicalEnvironment[] envs = client.List(connection, ProjectId); InfisicalEnvironment[] envs = client.List(connection, ProjectId);
Logger.Information("Get-InfisicalEnvironment", string.Concat("Returned ", envs.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " environment(s)."));
foreach (InfisicalEnvironment env in envs) foreach (InfisicalEnvironment env in envs)
{ {
WriteObject(env); WriteObject(env);
@@ -5,8 +5,10 @@ namespace PSInfisicalAPI.Cmdlets
{ {
[Cmdlet(VerbsCommon.Get, "InfisicalEnvironmentVariable")] [Cmdlet(VerbsCommon.Get, "InfisicalEnvironmentVariable")]
[OutputType(typeof(string))] [OutputType(typeof(string))]
public sealed class GetInfisicalEnvironmentVariableCmdlet : PSCmdlet public sealed class GetInfisicalEnvironmentVariableCmdlet : InfisicalCmdletBase
{ {
private const string Component = "Get-InfisicalEnvironmentVariable";
private static readonly EnvironmentVariableTarget[] TargetOrder = new[] private static readonly EnvironmentVariableTarget[] TargetOrder = new[]
{ {
EnvironmentVariableTarget.Process, EnvironmentVariableTarget.Process,
@@ -18,26 +20,38 @@ namespace PSInfisicalAPI.Cmdlets
[ValidateNotNullOrEmpty] [ValidateNotNullOrEmpty]
public string Name { get; set; } public string Name { get; set; }
[Parameter(Position = 1)]
public EnvironmentVariableTarget? Scope { get; set; }
protected override void ProcessRecord() protected override void ProcessRecord()
{ {
foreach (EnvironmentVariableTarget target in TargetOrder) EnvironmentVariableTarget[] targets = Scope.HasValue ? new[] { Scope.Value } : TargetOrder;
foreach (EnvironmentVariableTarget target in targets)
{ {
Logger.Verbose(Component, string.Concat("Searching ", target.ToString(), " scope for environment variable '", Name, "'."));
string value; string value;
try try
{ {
value = Environment.GetEnvironmentVariable(Name, target); value = Environment.GetEnvironmentVariable(Name, target);
} }
catch catch (Exception exception)
{ {
Logger.Verbose(Component, string.Concat("Failed to read ", target.ToString(), " scope for environment variable '", Name, "': ", exception.Message));
continue; continue;
} }
if (!string.IsNullOrEmpty(value)) if (!string.IsNullOrEmpty(value))
{ {
Logger.Information(Component, string.Concat("Found environment variable '", Name, "' in ", target.ToString(), " scope."));
WriteObject(value); WriteObject(value);
return; return;
} }
} }
string scopeDescription = Scope.HasValue ? string.Concat(Scope.Value.ToString(), " scope") : "Process, User, or Machine scope";
Logger.Information(Component, string.Concat("Environment variable '", Name, "' was not found in ", scopeDescription, "."));
} }
} }
} }
@@ -37,6 +37,7 @@ namespace PSInfisicalAPI.Cmdlets
} }
InfisicalFolder[] folders = client.List(connection, ProjectId, Environment, Path); InfisicalFolder[] folders = client.List(connection, ProjectId, Environment, Path);
Logger.Information("Get-InfisicalFolder", string.Concat("Returned ", folders.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " folder(s) from '", Path ?? "/", "'."));
foreach (InfisicalFolder folder in folders) foreach (InfisicalFolder folder in folders)
{ {
WriteObject(folder); WriteObject(folder);
@@ -33,6 +33,7 @@ namespace PSInfisicalAPI.Cmdlets
} }
InfisicalOrganization[] organizations = client.List(connection); InfisicalOrganization[] organizations = client.List(connection);
Logger.Information("Get-InfisicalOrganization", string.Concat("Returned ", organizations.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " organization(s)."));
foreach (InfisicalOrganization organization in organizations) foreach (InfisicalOrganization organization in organizations)
{ {
WriteObject(organization); WriteObject(organization);
@@ -35,6 +35,7 @@ namespace PSInfisicalAPI.Cmdlets
} }
InfisicalPkiSubscriber[] all = client.ListPkiSubscribers(connection, ProjectId); InfisicalPkiSubscriber[] all = client.ListPkiSubscribers(connection, ProjectId);
Logger.Information("Get-InfisicalPkiSubscriber", string.Concat("Returned ", all.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " PKI subscriber(s)."));
foreach (InfisicalPkiSubscriber subscriber in all) foreach (InfisicalPkiSubscriber subscriber in all)
{ {
WriteObject(subscriber); WriteObject(subscriber);
@@ -39,6 +39,7 @@ namespace PSInfisicalAPI.Cmdlets
} }
InfisicalProject[] projects = client.List(connection, Type, IncludeRoles.IsPresent); InfisicalProject[] projects = client.List(connection, Type, IncludeRoles.IsPresent);
Logger.Information("Get-InfisicalProject", string.Concat("Returned ", projects.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " project(s)."));
foreach (InfisicalProject project in projects) foreach (InfisicalProject project in projects)
{ {
WriteObject(project); WriteObject(project);
@@ -1,6 +1,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation; using System.Management.Automation;
using PSInfisicalAPI.Connections; using PSInfisicalAPI.Connections;
using PSInfisicalAPI.Models; using PSInfisicalAPI.Models;
@@ -57,8 +58,13 @@ namespace PSInfisicalAPI.Cmdlets
InfisicalSecret secret = client.Retrieve(connection, query); InfisicalSecret secret = client.Retrieve(connection, query);
if (secret != null) if (secret != null)
{ {
Logger.Information("Get-InfisicalSecret", string.Concat("Returned 1 secret for '", SecretName, "'."));
WriteObject(secret); WriteObject(secret);
} }
else
{
Logger.Information("Get-InfisicalSecret", string.Concat("No secret returned for '", SecretName, "'."));
}
return; return;
} }
@@ -79,6 +85,7 @@ namespace PSInfisicalAPI.Cmdlets
}; };
InfisicalSecret[] secrets = client.List(connection, listQuery); InfisicalSecret[] secrets = client.List(connection, listQuery);
Logger.Information("Get-InfisicalSecret", string.Concat("Returned ", secrets.Length.ToString(CultureInfo.InvariantCulture), " secret(s) from '", SecretPath ?? "/", "' (recursive=", Recursive.IsPresent ? "true" : "false", ", includeImports=", IncludeImports.IsPresent ? "true" : "false", ")."));
foreach (InfisicalSecret secret in secrets) foreach (InfisicalSecret secret in secrets)
{ {
WriteObject(secret); WriteObject(secret);
@@ -45,6 +45,7 @@ namespace PSInfisicalAPI.Cmdlets
bool? isAccessible = MyInvocation.BoundParameters.ContainsKey("IsAccessible") ? (bool?)IsAccessible.IsPresent : null; bool? isAccessible = MyInvocation.BoundParameters.ContainsKey("IsAccessible") ? (bool?)IsAccessible.IsPresent : null;
InfisicalSubOrganization[] subOrganizations = client.List(connection, Limit, Offset, Search, OrderBy, OrderDirection, isAccessible); InfisicalSubOrganization[] subOrganizations = client.List(connection, Limit, Offset, Search, OrderBy, OrderDirection, isAccessible);
Logger.Information("Get-InfisicalSubOrganization", string.Concat("Returned ", subOrganizations.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " sub-organization(s)."));
foreach (InfisicalSubOrganization subOrganization in subOrganizations) foreach (InfisicalSubOrganization subOrganization in subOrganizations)
{ {
WriteObject(subOrganization); WriteObject(subOrganization);
@@ -35,6 +35,7 @@ namespace PSInfisicalAPI.Cmdlets
} }
InfisicalTag[] tags = client.List(connection, ProjectId); InfisicalTag[] tags = client.List(connection, ProjectId);
Logger.Information("Get-InfisicalTag", string.Concat("Returned ", tags.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " tag(s)."));
foreach (InfisicalTag tag in tags) foreach (InfisicalTag tag in tags)
{ {
WriteObject(tag); WriteObject(tag);
@@ -49,15 +49,18 @@ namespace PSInfisicalAPI.Cmdlets
IInfisicalImporter importer = InfisicalImporterFactory.Create(Format); IInfisicalImporter importer = InfisicalImporterFactory.Create(Format);
IList<KeyValuePair<string, string>> pairs = importer.Import(Path); IList<KeyValuePair<string, string>> pairs = importer.Import(Path);
Logger.Information("Import-InfisicalSecret", string.Concat("Parsed ", pairs.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), " secret pair(s) from '", Path.FullName, "' (format=", Format.ToString(), ")."));
if (AsPlainText.IsPresent) if (AsPlainText.IsPresent)
{ {
Dictionary<string, string> plain = BuildDictionary<string>(pairs, value => value ?? string.Empty); Dictionary<string, string> plain = BuildDictionary<string>(pairs, value => value ?? string.Empty);
Logger.Information("Import-InfisicalSecret", string.Concat("Built plain-text dictionary with ", plain.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), " entry/entries."));
WriteObject(plain); WriteObject(plain);
} }
else else
{ {
Dictionary<string, SecureString> secure = BuildDictionary<SecureString>(pairs, value => SecureStringUtility.ToReadOnlySecureString(value ?? string.Empty)); Dictionary<string, SecureString> secure = BuildDictionary<SecureString>(pairs, value => SecureStringUtility.ToReadOnlySecureString(value ?? string.Empty));
Logger.Information("Import-InfisicalSecret", string.Concat("Built SecureString dictionary with ", secure.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), " entry/entries."));
WriteObject(secure); WriteObject(secure);
} }
} }
@@ -58,10 +58,12 @@ namespace PSInfisicalAPI.Cmdlets
Secrets = InfisicalBulkSecretConverter.ToCreateItems(Secrets) Secrets = InfisicalBulkSecretConverter.ToCreateItems(Secrets)
}; };
Logger.Information("New-InfisicalSecret", string.Concat("Bulk-creating ", Secrets.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " secret(s)."));
InfisicalSecretsClient bulkClient = new InfisicalSecretsClient(HttpClient, Logger); InfisicalSecretsClient bulkClient = new InfisicalSecretsClient(HttpClient, Logger);
InfisicalSecret[] created = bulkClient.CreateBatch(connection, bulk); InfisicalSecret[] created = bulkClient.CreateBatch(connection, bulk);
if (created != null) if (created != null)
{ {
Logger.Information("New-InfisicalSecret", string.Concat("Server returned ", created.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " created secret(s)."));
foreach (InfisicalSecret secret in created) { WriteObject(secret); } foreach (InfisicalSecret secret in created) { WriteObject(secret); }
} }
@@ -47,6 +47,7 @@ namespace PSInfisicalAPI.Cmdlets
SecretNames = SecretNames SecretNames = SecretNames
}; };
Logger.Information("Remove-InfisicalSecret", string.Concat("Bulk-removing ", SecretNames.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " secret(s)."));
client.DeleteBatch(connection, bulk); client.DeleteBatch(connection, bulk);
if (PassThru.IsPresent) if (PassThru.IsPresent)
@@ -121,6 +121,9 @@ namespace PSInfisicalAPI.Cmdlets
if (!ShouldProcess(target, "Start process with Infisical secrets")) { return; } if (!ShouldProcess(target, "Start process with Infisical secrets")) { return; }
int envVarCount = EnvironmentVariables != null ? EnvironmentVariables.Count : 0;
Logger.Information("Start-InfisicalProcess", string.Concat("Injecting ", _secretBuffer.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), " secret(s) and ", envVarCount.ToString(System.Globalization.CultureInfo.InvariantCulture), " explicit environment variable(s) into process environment."));
InfisicalProcessOptions options = new InfisicalProcessOptions InfisicalProcessOptions options = new InfisicalProcessOptions
{ {
FilePath = FilePath, FilePath = FilePath,
@@ -56,10 +56,12 @@ namespace PSInfisicalAPI.Cmdlets
Secrets = InfisicalBulkSecretConverter.ToUpdateItems(Secrets) Secrets = InfisicalBulkSecretConverter.ToUpdateItems(Secrets)
}; };
Logger.Information("Update-InfisicalSecret", string.Concat("Bulk-updating ", Secrets.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " secret(s)."));
InfisicalSecretsClient bulkClient = new InfisicalSecretsClient(HttpClient, Logger); InfisicalSecretsClient bulkClient = new InfisicalSecretsClient(HttpClient, Logger);
InfisicalSecret[] updated = bulkClient.UpdateBatch(connection, bulk); InfisicalSecret[] updated = bulkClient.UpdateBatch(connection, bulk);
if (updated != null) if (updated != null)
{ {
Logger.Information("Update-InfisicalSecret", string.Concat("Server returned ", updated.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " updated secret(s)."));
foreach (InfisicalSecret secret in updated) { WriteObject(secret); } foreach (InfisicalSecret secret in updated) { WriteObject(secret); }
} }
@@ -24,7 +24,7 @@ namespace PSInfisicalAPI.Process
if (options.EnvironmentVariables != null && options.EnvironmentVariables.Count > 0) if (options.EnvironmentVariables != null && options.EnvironmentVariables.Count > 0)
{ {
Log(logger, string.Concat("Injecting ", options.EnvironmentVariables.Count, " explicit environment variable(s) into the process.")); LogInformation(logger, string.Concat("Injecting ", options.EnvironmentVariables.Count, " explicit environment variable(s) into the process."));
foreach (DictionaryEntry entry in options.EnvironmentVariables) foreach (DictionaryEntry entry in options.EnvironmentVariables)
{ {
if (entry.Key == null) { continue; } if (entry.Key == null) { continue; }
@@ -36,7 +36,7 @@ namespace PSInfisicalAPI.Process
if (options.Secrets == null || options.Secrets.Length == 0) { return; } if (options.Secrets == null || options.Secrets.Length == 0) { return; }
Log(logger, string.Concat("Injecting ", options.Secrets.Length, " Infisical secret(s) into the process environment.")); LogInformation(logger, string.Concat("Injecting ", options.Secrets.Length, " Infisical secret(s) into the process environment."));
foreach (InfisicalSecret secret in options.Secrets) foreach (InfisicalSecret secret in options.Secrets)
{ {
if (secret == null || string.IsNullOrEmpty(secret.SecretName) || secret.SecretValue == null) { continue; } if (secret == null || string.IsNullOrEmpty(secret.SecretName) || secret.SecretValue == null) { continue; }
@@ -193,5 +193,10 @@ namespace PSInfisicalAPI.Process
{ {
if (logger != null) { logger.Verbose(Component, message); } if (logger != null) { logger.Verbose(Component, message); }
} }
private static void LogInformation(IInfisicalLogger logger, string message)
{
if (logger != null) { logger.Information(Component, message); }
}
} }
} }
@@ -75,8 +75,8 @@ namespace PSInfisicalAPI.Secrets
InfisicalSecretListResponseDto dto = _serializer.Deserialize<InfisicalSecretListResponseDto>(response.Body); InfisicalSecretListResponseDto dto = _serializer.Deserialize<InfisicalSecretListResponseDto>(response.Body);
response.Clear(); response.Clear();
InfisicalSecret[] mapped = InfisicalSecretMapper.MapMany(dto != null ? dto.Secrets : null); InfisicalSecret[] mapped = MergeListAndImports(dto);
_logger.Information(Component, "Infisical secrets retrieval was successful."); _logger.Information(Component, string.Concat("Infisical secrets retrieval was successful. Returned ", mapped.Length.ToString(CultureInfo.InvariantCulture), " secret(s)."));
return mapped; return mapped;
} }
catch (Exception) catch (Exception)
@@ -465,6 +465,66 @@ namespace PSInfisicalAPI.Secrets
} }
} }
private InfisicalSecret[] MergeListAndImports(InfisicalSecretListResponseDto dto)
{
if (dto == null) { return Array.Empty<InfisicalSecret>(); }
InfisicalSecret[] local = InfisicalSecretMapper.MapMany(dto.Secrets);
if (dto.Imports == null || dto.Imports.Count == 0)
{
return local;
}
Dictionary<string, InfisicalSecret> merged = new Dictionary<string, InfisicalSecret>(StringComparer.Ordinal);
int importsTotal = 0;
foreach (InfisicalSecretImportDto import in dto.Imports)
{
if (import == null) { continue; }
InfisicalSecret[] importedSecrets = InfisicalSecretMapper.MapMany(import.Secrets);
importsTotal += importedSecrets.Length;
_logger.Information(Component, string.Concat(
"Including ",
importedSecrets.Length.ToString(CultureInfo.InvariantCulture),
" secret(s) from import '",
import.SecretPath ?? string.Empty,
"' (environment='",
import.Environment ?? string.Empty,
"')."));
foreach (InfisicalSecret secret in importedSecrets)
{
if (secret == null || string.IsNullOrEmpty(secret.SecretName)) { continue; }
merged[secret.SecretName] = secret;
}
}
int overrides = 0;
foreach (InfisicalSecret secret in local)
{
if (secret == null || string.IsNullOrEmpty(secret.SecretName)) { continue; }
if (merged.ContainsKey(secret.SecretName)) { overrides++; }
merged[secret.SecretName] = secret;
}
_logger.Information(Component, string.Concat(
"Merged secrets: local=",
local.Length.ToString(CultureInfo.InvariantCulture),
", imports=",
importsTotal.ToString(CultureInfo.InvariantCulture),
", local-overrode-import=",
overrides.ToString(CultureInfo.InvariantCulture),
", final=",
merged.Count.ToString(CultureInfo.InvariantCulture),
"."));
InfisicalSecret[] result = new InfisicalSecret[merged.Count];
merged.Values.CopyTo(result, 0);
return result;
}
private InfisicalHttpResponse SendWithVersionFallback( private InfisicalHttpResponse SendWithVersionFallback(
InfisicalConnection connection, InfisicalConnection connection,
string endpointName, string endpointName,