fix: take the API token as a SecureString and stop exposing session credentials (#240)

Connect-PveServer -ApiToken was a plain string, so the token landed verbatim
in PSReadLine history and any transcript, and PveSession published ApiToken,
Ticket and CsrfToken as public getters, so Format-List *, ConvertTo-Json and
Export-Clixml of a session printed them.

The parameter is now a SecureString, extracted at the cmdlet boundary with the
Marshal/ZeroFree pattern ADR 0002 established for passwords. A plain string
still binds for one minor release through an argument transformation, and the
cmdlet warns that the string form goes away in the next major; the marker
lives in a ConditionalWeakTable keyed on the converted instance, so an
abandoned binding neither retains the secret nor mislabels a later call.

The three session getters become internal. PveHttpClient is in the same
assembly and the xUnit project already has InternalsVisibleTo, so the header
construction and its tests are unchanged.

Refs ADR 0028, issue #147.

Co-authored-by: goodolclint-claude[bot] <323206664+goodolclint-claude[bot]@users.noreply.github.com>
This commit is contained in:
goodolclint-claude[bot]
2026-09-03 21:34:11 +00:00
committed by GitHub
parent 8d955a0ea8
commit c8a7e809bb
9 changed files with 223 additions and 20 deletions
+6 -3
View File
@@ -64,8 +64,9 @@ Import-Module PSProxmoxVE
$cred = Get-Credential -UserName 'root@pam'
Connect-PveServer -Server 'pve.example.com' -Credential $cred -SkipCertificateCheck
# Using API token
Connect-PveServer -Server 'pve.example.com' -ApiToken 'root@pam!mytoken=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
# Using API token (SecureString)
$token = Read-Host -AsSecureString -Prompt 'API token (root@pam!mytoken=...)'
Connect-PveServer -Server 'pve.example.com' -ApiToken $token
# Verify connection
Test-PveConnection -Detailed
@@ -167,7 +168,9 @@ API tokens provide persistent, non-expiring authentication. They are the recomme
4. Copy the token value — it is shown only once
```powershell
Connect-PveServer -Server 'pve.example.com' -ApiToken 'root@pam!automation=12345678-abcd-efgh-ijkl-123456789012'
# Read-Host keeps the token out of shell history and transcripts.
$token = Read-Host -AsSecureString -Prompt 'API token (root@pam!automation=...)'
Connect-PveServer -Server 'pve.example.com' -ApiToken $token
```
## Multi-Cluster Usage
+6 -3
View File
@@ -20,7 +20,7 @@ Connect-PveServer [-Server] <String> [-Port <Int32>] -Credential <PSCredential>
### ApiToken
```
Connect-PveServer [-Server] <String> [-Port <Int32>] -ApiToken <String> [-SkipCertificateCheck]
Connect-PveServer [-Server] <String> [-Port <Int32>] -ApiToken <SecureString> [-SkipCertificateCheck]
[-TimeoutSeconds <Int32>] [-PassThru] [-Quiet] [-ProgressAction <ActionPreference>] [<CommonParameters>]
```
@@ -39,10 +39,13 @@ PS C:\> {{ Add example code here }}
## PARAMETERS
### -ApiToken
API token in USER@REALM!TOKENID=UUID format.
API token in USER@REALM!TOKENID=UUID format, as a SecureString.
Build one with `Read-Host -AsSecureString`, or read it from a secret vault. `ConvertTo-SecureString 'root@pam!mytoken=...' -AsPlainText -Force` also works, but a token written as a literal lands in shell history and in any transcript.
A plain string is still accepted in this release and emits a deprecation warning; it is removed in the next major release.
```yaml
Type: String
Type: SecureString
Parameter Sets: ApiToken
Aliases:
@@ -28,16 +28,16 @@ namespace PSProxmoxVE.Core.Authentication
public PveAuthMode AuthMode { get; }
/// <summary>The API token string, when using API token authentication.</summary>
public string? ApiToken { get; }
internal string? ApiToken { get; }
/// <summary>The user (user@realm) the ticket was issued to; null for API token sessions.</summary>
public string? Username { get; }
/// <summary>The session ticket cookie value, when using ticket authentication.</summary>
public string? Ticket => ReadTicket()?.Ticket;
internal string? Ticket => ReadTicket()?.Ticket;
/// <summary>The CSRF prevention token, when using ticket authentication.</summary>
public string? CsrfToken => ReadTicket()?.CsrfToken;
internal string? CsrfToken => ReadTicket()?.CsrfToken;
/// <summary>The UTC expiry time for the session ticket.</summary>
public DateTime TicketExpiry => ReadTicket()?.Expiry ?? DateTime.MaxValue;
@@ -0,0 +1,59 @@
using System;
using System.Management.Automation;
using System.Runtime.CompilerServices;
using System.Security;
namespace PSProxmoxVE.Cmdlets.Connection
{
/// <summary>
/// Converts a plain <see cref="string"/> API token argument to a <see cref="SecureString"/> so
/// that scripts written against the pre-SecureString parameter keep binding for one minor
/// release. A <see cref="SecureString"/> argument is returned unchanged.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public sealed class ApiTokenTransformationAttribute : ArgumentTransformationAttribute
{
/// <summary>
/// The SecureStrings this attribute built from a plain string, held weakly so an argument
/// bound by an invocation that never reached its cmdlet is not kept alive by this table.
/// </summary>
private static readonly ConditionalWeakTable<SecureString, object> ConvertedFromString =
new ConditionalWeakTable<SecureString, object>();
private static readonly object Marker = new object();
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
{
var value = inputData is PSObject wrapper ? wrapper.BaseObject : inputData;
if (value is SecureString secure)
return secure;
if (value is string plain)
{
var converted = new SecureString();
foreach (var c in plain)
converted.AppendChar(c);
converted.MakeReadOnly();
ConvertedFromString.Add(converted, Marker);
return converted;
}
return inputData;
}
/// <summary>
/// Reports whether <paramref name="value"/> is a SecureString this attribute built from a
/// plain string argument, and forgets it either way. A true answer also means the module
/// owns the instance and may dispose it.
/// </summary>
internal static bool WasConvertedFromString(SecureString? value)
{
if (value == null || !ConvertedFromString.TryGetValue(value, out _))
return false;
ConvertedFromString.Remove(value);
return true;
}
}
}
@@ -1,5 +1,7 @@
using System;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Security;
using PSProxmoxVE.Core.Authentication;
namespace PSProxmoxVE.Cmdlets.Connection
@@ -39,10 +41,12 @@ namespace PSProxmoxVE.Cmdlets.Connection
/// <summary>
/// Proxmox VE API token in the format USER@REALM!TOKENID=UUID,
/// e.g. root@pam!mytoken=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
/// A plain string is still accepted for this release and warns; it is removed in the next major.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = ParameterSetApiToken, HelpMessage = "API token in USER@REALM!TOKENID=UUID format.")]
[ValidateNotNullOrEmpty]
public string? ApiToken { get; set; }
[ApiTokenTransformation]
[ValidateNotNull]
public SecureString? ApiToken { get; set; }
/// <summary>When specified, skips TLS certificate validation for the server.</summary>
[Parameter(Mandatory = false, HelpMessage = "Skip TLS certificate validation.")]
@@ -111,10 +115,37 @@ namespace PSProxmoxVE.Cmdlets.Connection
case ParameterSetApiToken:
{
var moduleOwnsToken = ApiTokenTransformationAttribute.WasConvertedFromString(ApiToken);
if (moduleOwnsToken)
WriteWarning(
"Passing -ApiToken as a plain string is deprecated and will be removed in the next major release. " +
"Pass a SecureString instead, for example (Read-Host -AsSecureString), a token retrieved from a " +
"secret vault, or (ConvertTo-SecureString 'USER@REALM!TOKENID=UUID' -AsPlainText -Force).");
if (ApiToken!.Length == 0)
ThrowTerminatingError(new ErrorRecord(
new ArgumentException("API token cannot be empty.", nameof(ApiToken)),
"ApiTokenEmpty",
ErrorCategory.InvalidArgument,
null));
string apiToken;
var ptr = Marshal.SecureStringToGlobalAllocUnicode(ApiToken);
try
{
apiToken = Marshal.PtrToStringUni(ptr) ?? string.Empty;
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(ptr);
if (moduleOwnsToken)
ApiToken.Dispose();
}
try
{
session = PveAuthenticator.AuthenticateWithApiToken(
Server, Port, SkipCertificateCheck.IsPresent, ApiToken!, timeout);
Server, Port, SkipCertificateCheck.IsPresent, apiToken, timeout);
}
catch (Exception ex)
{
+8 -6
View File
@@ -708,11 +708,12 @@
<command:parameter required="true" variableLength="true" globbing="false" pipelineInput="False" position="named" aliases="none">
<maml:name>ApiToken</maml:name>
<maml:description>
<maml:para>API token in USER@REALM!TOKENID=UUID format.</maml:para>
<maml:para>API token in USER@REALM!TOKENID=UUID format, as a SecureString.</maml:para>
<maml:para>Build one with `Read-Host -AsSecureString`, or read it from a secret vault. `ConvertTo-SecureString 'root@pam!mytoken=...' -AsPlainText -Force` also works, but a token written as a literal lands in shell history and in any transcript. A plain string is still accepted in this release and emits a deprecation warning; it is removed in the next major release.</maml:para>
</maml:description>
<command:parameterValue required="true" variableLength="false">String</command:parameterValue>
<command:parameterValue required="true" variableLength="false">SecureString</command:parameterValue>
<dev:type>
<maml:name>String</maml:name>
<maml:name>SecureString</maml:name>
<maml:uri />
</dev:type>
<dev:defaultValue>None</dev:defaultValue>
@@ -888,11 +889,12 @@
<command:parameter required="true" variableLength="true" globbing="false" pipelineInput="False" position="named" aliases="none">
<maml:name>ApiToken</maml:name>
<maml:description>
<maml:para>API token in USER@REALM!TOKENID=UUID format.</maml:para>
<maml:para>API token in USER@REALM!TOKENID=UUID format, as a SecureString.</maml:para>
<maml:para>Build one with `Read-Host -AsSecureString`, or read it from a secret vault. `ConvertTo-SecureString 'root@pam!mytoken=...' -AsPlainText -Force` also works, but a token written as a literal lands in shell history and in any transcript. A plain string is still accepted in this release and emits a deprecation warning; it is removed in the next major release.</maml:para>
</maml:description>
<command:parameterValue required="true" variableLength="false">String</command:parameterValue>
<command:parameterValue required="true" variableLength="false">SecureString</command:parameterValue>
<dev:type>
<maml:name>String</maml:name>
<maml:name>SecureString</maml:name>
<maml:uri />
</dev:type>
<dev:defaultValue>None</dev:defaultValue>
@@ -1357,7 +1357,6 @@
</View>
<!-- PSProxmoxVE.Core.Authentication.PveSession -->
<!-- Hides sensitive properties (Ticket, ApiToken, CsrfToken) from default output -->
<View>
<Name>PSProxmoxVE.Core.Authentication.PveSession</Name>
<ViewSelectedBy>
@@ -1,4 +1,6 @@
using System;
using System.Linq;
using System.Reflection;
using Xunit;
using PSProxmoxVE.Core.Authentication;
@@ -184,6 +186,49 @@ namespace PSProxmoxVE.Core.Tests.Authentication
Assert.True(session.SkipCertificateCheck);
}
[Theory]
[InlineData("ApiToken")]
[InlineData("Ticket")]
[InlineData("CsrfToken")]
public void CredentialProperties_AreNotPubliclyReadable(string propertyName)
{
var property = typeof(PveSession).GetProperty(
propertyName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(property);
Assert.False(property!.GetMethod!.IsPublic);
}
[Fact]
public void PublicProperties_ExposeNoApiToken()
{
const string token = "root@pam!mytoken=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
var session = new PveSession(TestHostname, TestPort, false, token);
Assert.DoesNotContain(RenderPublicProperties(session), v => v.Contains(token));
}
[Fact]
public void PublicProperties_ExposeNoTicketOrCsrfToken()
{
const string ticket = "PVE:root@pam:SECRETTICKET";
const string csrf = "SECRETCSRFTOKEN";
var session = new PveSession(TestHostname, TestPort, false, "root@pam", ticket, csrf,
DateTime.UtcNow.AddHours(2));
var rendered = RenderPublicProperties(session);
Assert.DoesNotContain(rendered, v => v.Contains(ticket));
Assert.DoesNotContain(rendered, v => v.Contains(csrf));
}
private static string[] RenderPublicProperties(PveSession session) =>
typeof(PveSession)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => p.GetValue(session)?.ToString())
.Where(v => v != null)
.ToArray()!;
[Fact]
public void Timeout_DefaultIs100Seconds()
{
@@ -35,12 +35,73 @@ Describe 'Connect-PveServer' {
Connect-PveServer `
-Server 'pve.example.com' `
-Credential $cred `
-ApiToken 'root@pam!mytoken=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' `
-ApiToken (ConvertTo-SecureString 'root@pam!mytoken=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' -AsPlainText -Force) `
-ErrorAction Stop
} | Should -Throw
}
}
Context 'ApiToken accepts a SecureString and warns on a plain string' {
BeforeAll {
# Rejected by the token-format check before any HTTP call, so these cases stay offline.
$script:BadToken = 'not-a-valid-token'
}
It 'ApiToken should be typed SecureString' {
(Get-Command 'Connect-PveServer').Parameters['ApiToken'].ParameterType |
Should -Be ([System.Security.SecureString])
}
It 'Should bind a plain string and warn that it is deprecated' {
$warnings = @()
$err = $null
try {
Connect-PveServer -Server 'pve.example.com' -ApiToken $script:BadToken `
-ErrorAction Stop -WarningVariable +warnings
} catch { $err = $_ }
$err.FullyQualifiedErrorId | Should -Match 'PveAuthenticationFailed'
($warnings -join "`n") | Should -Match 'deprecated'
}
It 'Should not warn about deprecation when given a SecureString' {
$secure = ConvertTo-SecureString $script:BadToken -AsPlainText -Force
$warnings = @()
$err = $null
try {
Connect-PveServer -Server 'pve.example.com' -ApiToken $secure `
-ErrorAction Stop -WarningVariable +warnings
} catch { $err = $_ }
$err.FullyQualifiedErrorId | Should -Match 'PveAuthenticationFailed'
($warnings -join "`n") | Should -Not -Match 'deprecated'
}
It 'Should not warn when a SecureString follows a binding failure that transformed a string' {
$securePass = ConvertTo-SecureString 'hunter2' -AsPlainText -Force
$cred = [System.Management.Automation.PSCredential]::new('root@pam', $securePass)
try {
Connect-PveServer -Server 'pve.example.com' -Credential $cred `
-ApiToken $script:BadToken -ErrorAction Stop
} catch { }
$secure = ConvertTo-SecureString $script:BadToken -AsPlainText -Force
$warnings = @()
try {
Connect-PveServer -Server 'pve.example.com' -ApiToken $secure `
-ErrorAction Stop -WarningVariable +warnings
} catch { }
($warnings -join "`n") | Should -Not -Match 'deprecated'
}
It 'Should reject an empty SecureString as an invalid argument' {
$err = $null
try {
Connect-PveServer -Server 'pve.example.com' `
-ApiToken (New-Object System.Security.SecureString) -ErrorAction Stop
} catch { $err = $_ }
$err.FullyQualifiedErrorId | Should -Match 'ApiTokenEmpty'
}
}
Context 'Parameter metadata' {
BeforeAll {
$script:Cmd = Get-Command 'Connect-PveServer'