Support for password input in a redirected console

Nov 1, 2011 at 12:53 AM
Hi,

When trying to automate nuget.exe for testing, I stumbled upon an issue with the new basic auth feature. ConsoleCredentialProvider uses methods that only work on a real console to read the password and replace it with stars. If I try to redirect the console, either from the shell with "<" or from code with ProcessStartInfo, it fails with an exception. Attached if a patch with a failover to use with a simple ReadLine, if the fancy reading fails. What do you think?

Cheers,
Marcin

Nov 1, 2011 at 12:55 AM

Oops, you can't post attachments here... Here's the very short patch inline:

# HG changeset patch
# User TripleEmcoder
# Date 1320103713 -3600
# Branch 1.6
# Node ID 08c8cb0f6231e79ec29225a08b14d912822bace2
# Parent  2a4278e63863b3db5c56330f78f974f365b2302d
Support for reading passwords from a redirected console.

diff -r 2a4278e63863 -r 08c8cb0f6231 src/CommandLine/Common/ConsoleCredentialProvider.cs
--- a/src/CommandLine/Common/ConsoleCredentialProvider.cs	Thu Oct 27 15:20:23 2011 -0700
+++ b/src/CommandLine/Common/ConsoleCredentialProvider.cs	Tue Nov 01 00:28:33 2011 +0100
@@ -25,7 +25,6 @@
                 UserName = username,
                 SecurePassword = password
             };
-
             return credentials;
         }
 
@@ -35,9 +34,10 @@
             Justification = "Caller's responsibility to dispose.")]
         public static SecureString ReadLineAsSecureString()
         {
+            var secureString = new SecureString();
+
             try
             {
-                var secureString = new SecureString();
                 ConsoleKeyInfo keyInfo;
                 while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter)
                 {
@@ -58,13 +58,16 @@
                         Console.Write('*');
                     }
                 }
-                secureString.MakeReadOnly();
-                return secureString;
-            }
-            finally
-            {
                 Console.WriteLine(String.Empty);
             }
+            catch (InvalidOperationException)
+            {
+                foreach (var c in Console.ReadLine())
+                    secureString.AppendChar(c);
+            }
+
+            secureString.MakeReadOnly();
+            return secureString;
         }
     }
 }
\ No newline at end of file

Nov 1, 2011 at 1:21 AM

It it doesn't regress any existing scenarios, I don't see any problem with it. Please make sure you test the console thoroughly and then send a pull request. Also create a bug for it first. Thanks.

Nov 3, 2011 at 4:20 PM

Ok, here it is:

Work item - http://nuget.codeplex.com/workitem/1694

Pull request http://nuget.codeplex.com/SourceControl/network/Forks/TripleEmcoder/NuGet/contribution/1622

Thanks!