-
Notifications
You must be signed in to change notification settings - Fork 298
/
History.cs
1306 lines (1155 loc) · 50.3 KB
/
History.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Management.Automation.Language;
using Microsoft.PowerShell.PSReadLine;
namespace Microsoft.PowerShell
{
/// <summary>
/// FNV-1a hashing algorithm: http://www.isthe.com/chongo/tech/comp/fnv/#FNV-1a
/// </summary>
internal class FNV1a32Hash
{
// FNV-1a algorithm parameters: http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param
private const uint FNV32_PRIME = 16777619;
private const uint FNV32_OFFSETBASIS = 2166136261;
internal static uint ComputeHash(string input)
{
char ch;
uint hash = FNV32_OFFSETBASIS, lowByte, highByte;
for (int i = 0; i < input.Length; i++)
{
ch = input[i];
lowByte = (uint)(ch & 0x00FF);
hash = unchecked((hash ^ lowByte) * FNV32_PRIME);
highByte = (uint)(ch >> 8);
hash = unchecked((hash ^ highByte) * FNV32_PRIME);
}
return hash;
}
}
public partial class PSConsoleReadLine
{
/// <summary>
/// History details including the command line, source, and start and approximate execution time.
/// </summary>
[DebuggerDisplay("{" + nameof(CommandLine) + "}")]
public class HistoryItem
{
/// <summary>
/// The command line, or if multiple lines, the lines joined
/// with a newline.
/// </summary>
public string CommandLine { get; internal set; }
/// <summary>
/// The time at which the command was added to history in UTC.
/// </summary>
public DateTime StartTime { get; internal set; }
/// <summary>
/// The approximate elapsed time (includes time to invoke Prompt).
/// The value can be 0 ticks if if accessed before PSReadLine
/// gets a chance to set it.
/// </summary>
public TimeSpan ApproximateElapsedTime { get; internal set; }
/// <summary>
/// True if the command was from another running session
/// (as opposed to read from the history file at startup.)
/// </summary>
public bool FromOtherSession { get; internal set; }
/// <summary>
/// True if the command was read in from the history file at startup.
/// </summary>
public bool FromHistoryFile { get; internal set; }
internal bool _saved;
internal bool _sensitive;
internal List<EditItem> _edits;
internal int _undoEditIndex;
internal int _editGroupStart;
}
// History state
private HistoryQueue<HistoryItem> _history;
private HistoryQueue<string> _recentHistory;
private HistoryItem _previousHistoryItem;
private Dictionary<string, int> _hashedHistory;
private int _currentHistoryIndex;
private int _getNextHistoryIndex;
private int _searchHistoryCommandCount;
private int _recallHistoryCommandCount;
private int _anyHistoryCommandCount;
private string _searchHistoryPrefix;
// When cycling through history, the current line (not yet added to history)
// is saved here so it can be restored.
private readonly HistoryItem _savedCurrentLine;
private Mutex _historyFileMutex;
private long _historyFileLastSavedSize;
private const string _forwardISearchPrompt = "fwd-i-search: ";
private const string _backwardISearchPrompt = "bck-i-search: ";
private const string _failedForwardISearchPrompt = "failed-fwd-i-search: ";
private const string _failedBackwardISearchPrompt = "failed-bck-i-search: ";
// Pattern used to check for sensitive inputs.
private static readonly Regex s_sensitivePattern = new Regex(
"password|asplaintext|token|apikey|secret",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly HashSet<string> s_SecretMgmtCommands = new(StringComparer.OrdinalIgnoreCase)
{
"Get-Secret",
"Get-SecretInfo",
"Get-SecretVault",
"Register-SecretVault",
"Remove-Secret",
"Set-SecretInfo",
"Set-SecretVaultDefault",
"Test-SecretVault",
"Unlock-SecretVault",
"Unregister-SecretVault",
"Get-AzAccessToken",
};
private void ClearSavedCurrentLine()
{
_savedCurrentLine.CommandLine = null;
_savedCurrentLine._edits = null;
_savedCurrentLine._undoEditIndex = 0;
_savedCurrentLine._editGroupStart = -1;
}
private AddToHistoryOption GetAddToHistoryOption(string line, bool fromHistoryFile)
{
// Whitespace only is useless, never add.
if (string.IsNullOrWhiteSpace(line))
{
return AddToHistoryOption.SkipAdding;
}
// Under "no dupes" (which is on by default), immediately drop dupes of the previous line.
if (Options.HistoryNoDuplicates && _history.Count > 0 &&
string.Equals(_history[_history.Count - 1].CommandLine, line, StringComparison.Ordinal))
{
return AddToHistoryOption.SkipAdding;
}
if (!fromHistoryFile && Options.AddToHistoryHandler != null)
{
if (Options.AddToHistoryHandler == PSConsoleReadLineOptions.DefaultAddToHistoryHandler)
{
// Avoid boxing if it's the default handler.
return GetDefaultAddToHistoryOption(line);
}
object value = Options.AddToHistoryHandler(line);
if (value is PSObject psObj)
{
value = psObj.BaseObject;
}
if (value is bool boolValue)
{
return boolValue ? AddToHistoryOption.MemoryAndFile : AddToHistoryOption.SkipAdding;
}
if (value is AddToHistoryOption enumValue)
{
return enumValue;
}
if (value is string strValue && Enum.TryParse(strValue, out enumValue))
{
return enumValue;
}
// 'TryConvertTo' incurs exception handling when the value cannot be converted to the target type.
// It's expensive, especially when we need to process lots of history items from file during the
// initialization. So do the conversion as the last resort.
if (LanguagePrimitives.TryConvertTo(value, out enumValue))
{
return enumValue;
}
}
// Add to both history queue and file by default.
return AddToHistoryOption.MemoryAndFile;
}
private string MaybeAddToHistory(
string result,
List<EditItem> edits,
int undoEditIndex,
bool fromDifferentSession = false,
bool fromInitialRead = false)
{
bool fromHistoryFile = fromDifferentSession || fromInitialRead;
var addToHistoryOption = GetAddToHistoryOption(result, fromHistoryFile);
if (addToHistoryOption != AddToHistoryOption.SkipAdding)
{
_previousHistoryItem = new HistoryItem
{
CommandLine = result,
_edits = edits,
_undoEditIndex = undoEditIndex,
_editGroupStart = -1,
_saved = fromHistoryFile,
FromOtherSession = fromDifferentSession,
FromHistoryFile = fromInitialRead,
};
if (!fromHistoryFile)
{
// Add to the recent history queue, which is used when querying for prediction.
_recentHistory.Enqueue(result);
// 'MemoryOnly' indicates sensitive content in the command line
_previousHistoryItem._sensitive = addToHistoryOption == AddToHistoryOption.MemoryOnly;
_previousHistoryItem.StartTime = DateTime.UtcNow;
}
_history.Enqueue(_previousHistoryItem);
_currentHistoryIndex = _history.Count;
if (_options.HistorySaveStyle == HistorySaveStyle.SaveIncrementally && !fromHistoryFile)
{
IncrementalHistoryWrite();
}
}
else
{
_previousHistoryItem = null;
}
// Clear the saved line unless we used AcceptAndGetNext in which
// case we're really still in middle of history and might want
// to recall the saved line.
if (_getNextHistoryIndex == 0)
{
ClearSavedCurrentLine();
}
return result;
}
private string GetHistorySaveFileMutexName()
{
// Return a reasonably unique name - it's not too important as there will rarely
// be any contention.
uint hashFromPath = FNV1a32Hash.ComputeHash(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? _options.HistorySavePath.ToLower()
: _options.HistorySavePath);
return "PSReadLineHistoryFile_" + hashFromPath.ToString();
}
private void IncrementalHistoryWrite()
{
var i = _currentHistoryIndex - 1;
while (i >= 0)
{
if (_history[i]._saved)
{
break;
}
i -= 1;
}
WriteHistoryRange(i + 1, _history.Count - 1, overwritten: false);
}
private void SaveHistoryAtExit()
{
WriteHistoryRange(0, _history.Count - 1, overwritten: true);
}
private int historyErrorReportedCount;
private void ReportHistoryFileError(Exception e)
{
if (historyErrorReportedCount == 2)
return;
historyErrorReportedCount += 1;
Console.Write(_options._errorColor);
Console.WriteLine(PSReadLineResources.HistoryFileErrorMessage, Options.HistorySavePath, e.Message);
if (historyErrorReportedCount == 2)
{
Console.WriteLine(PSReadLineResources.HistoryFileErrorFinalMessage);
}
Console.Write("\x1b0m");
}
private bool WithHistoryFileMutexDo(int timeout, Action action)
{
int retryCount = 0;
do
{
try
{
if (_historyFileMutex.WaitOne(timeout))
{
try
{
action();
return true;
}
catch (UnauthorizedAccessException uae)
{
ReportHistoryFileError(uae);
return false;
}
catch (IOException ioe)
{
ReportHistoryFileError(ioe);
return false;
}
finally
{
_historyFileMutex.ReleaseMutex();
}
}
// Consider it a failure if we timed out on the mutex.
return false;
}
catch (AbandonedMutexException)
{
retryCount += 1;
// We acquired the mutex object that was abandoned by another powershell process.
// Now, since we own it, we must release it before retry, otherwise, we will miss
// a release and keep holding the mutex, in which case the 'WaitOne' calls from
// all other powershell processes will time out.
_historyFileMutex.ReleaseMutex();
}
} while (retryCount > 0 && retryCount < 3);
// If we reach here, that means we've done the retries but always got the 'AbandonedMutexException'.
return false;
}
private void WriteHistoryRange(int start, int end, bool overwritten)
{
WithHistoryFileMutexDo(100, () =>
{
bool retry = true;
// Get the new content since the last sync.
List<string> historyLines = overwritten ? null : ReadHistoryFileIncrementally();
try
{
retry_after_creating_directory:
try
{
using (var file = overwritten ? File.CreateText(Options.HistorySavePath) : File.AppendText(Options.HistorySavePath))
{
for (var i = start; i <= end; i++)
{
HistoryItem item = _history[i];
item._saved = true;
// Actually, skip writing sensitive items to file.
if (item._sensitive) { continue; }
var line = item.CommandLine.Replace("\n", "`\n");
file.WriteLine(line);
}
}
var fileInfo = new FileInfo(Options.HistorySavePath);
_historyFileLastSavedSize = fileInfo.Length;
}
catch (DirectoryNotFoundException)
{
// Try making the directory, but just once
if (retry)
{
retry = false;
Directory.CreateDirectory(Path.GetDirectoryName(Options.HistorySavePath));
goto retry_after_creating_directory;
}
}
}
finally
{
if (historyLines != null)
{
// Populate new history from other sessions to the history queue after we are done
// with writing the specified range to the file.
// We do it at this point to make sure the range of history items from 'start' to
// 'end' do not get changed before the writing to the file.
UpdateHistoryFromFile(historyLines, fromDifferentSession: true, fromInitialRead: false);
}
}
});
}
/// <summary>
/// Helper method to read the incremental part of the history file.
/// Note: the call to this method should be guarded by the mutex that protects the history file.
/// </summary>
private List<string> ReadHistoryFileIncrementally()
{
var fileInfo = new FileInfo(Options.HistorySavePath);
if (fileInfo.Exists && fileInfo.Length != _historyFileLastSavedSize)
{
var historyLines = new List<string>();
using (var fs = new FileStream(Options.HistorySavePath, FileMode.Open))
using (var sr = new StreamReader(fs))
{
fs.Seek(_historyFileLastSavedSize, SeekOrigin.Begin);
while (!sr.EndOfStream)
{
historyLines.Add(sr.ReadLine());
}
}
_historyFileLastSavedSize = fileInfo.Length;
return historyLines.Count > 0 ? historyLines : null;
}
return null;
}
private bool MaybeReadHistoryFile()
{
if (Options.HistorySaveStyle == HistorySaveStyle.SaveIncrementally)
{
return WithHistoryFileMutexDo(1000, () =>
{
List<string> historyLines = ReadHistoryFileIncrementally();
if (historyLines != null)
{
UpdateHistoryFromFile(historyLines, fromDifferentSession: true, fromInitialRead: false);
}
});
}
// true means no errors, not that we actually read the file
return true;
}
private void ReadHistoryFile()
{
if (File.Exists(Options.HistorySavePath))
{
WithHistoryFileMutexDo(1000, () =>
{
var historyLines = ReadHistoryLinesImpl(Options.HistorySavePath, Options.MaximumHistoryCount);
UpdateHistoryFromFile(historyLines, fromDifferentSession: false, fromInitialRead: true);
var fileInfo = new FileInfo(Options.HistorySavePath);
_historyFileLastSavedSize = fileInfo.Length;
});
}
static IEnumerable<string> ReadHistoryLinesImpl(string path, int historyCount)
{
const long offset_1mb = 1048576;
const long offset_05mb = 524288;
// 1mb content contains more than 34,000 history lines for a typical usage, which should be
// more than enough to cover 20,000 history records (a history record could be a multi-line
// command). Similarly, 0.5mb content should be enough to cover 10,000 history records.
// We optimize the file reading when the history count falls in those ranges. If the history
// count is even larger, which should be very rare, we just read all lines.
long offset = historyCount switch
{
<= 10000 => offset_05mb,
<= 20000 => offset_1mb,
_ => 0,
};
using var fs = new FileStream(path, FileMode.Open);
using var sr = new StreamReader(fs);
if (offset > 0 && fs.Length > offset)
{
// When the file size is larger than the offset, we only read that amount of content from the end.
fs.Seek(-offset, SeekOrigin.End);
// After seeking, the current position may point at the middle of a history record, or even at a
// byte within a UTF-8 character (history file is saved with UTF-8 encoding). So, let's ignore the
// first line read from that position.
sr.ReadLine();
string line;
while ((line = sr.ReadLine()) is not null)
{
if (!line.EndsWith("`", StringComparison.Ordinal))
{
// A complete history record is guaranteed to start from the next line.
break;
}
}
}
// Read lines in the streaming way, so it won't consume to much memory even if we have to
// read all lines from a large history file.
while (!sr.EndOfStream)
{
yield return sr.ReadLine();
}
}
}
void UpdateHistoryFromFile(IEnumerable<string> historyLines, bool fromDifferentSession, bool fromInitialRead)
{
var sb = new StringBuilder();
foreach (var line in historyLines)
{
if (line.EndsWith("`", StringComparison.Ordinal))
{
sb.Append(line, 0, line.Length - 1);
sb.Append('\n');
}
else if (sb.Length > 0)
{
sb.Append(line);
var l = sb.ToString();
var editItems = new List<EditItem> {EditItemInsertString.Create(l, 0)};
MaybeAddToHistory(l, editItems, 1, fromDifferentSession, fromInitialRead);
sb.Clear();
}
else
{
var editItems = new List<EditItem> {EditItemInsertString.Create(line, 0)};
MaybeAddToHistory(line, editItems, 1, fromDifferentSession, fromInitialRead);
}
}
}
private static bool IsOnLeftSideOfAnAssignment(Ast ast, out Ast rhs)
{
bool result = false;
rhs = null;
do
{
if (ast.Parent is AssignmentStatementAst assignment)
{
rhs = assignment.Right;
result = ReferenceEquals(assignment.Left, ast);
break;
}
ast = ast.Parent;
}
while (ast.Parent is not null);
return result;
}
private static bool IsRightSideOfAnAssignmentSafe(Ast rhs)
{
if (rhs is PipelineAst)
{
// Right hand side is a pipeline.
return true;
}
if (rhs is CommandExpressionAst cmdExprAst && cmdExprAst.Expression is MemberExpressionAst or InvokeMemberExpressionAst)
{
// Right hand side is a member access, or method invocation.
return true;
}
return false;
}
private static bool IsSecretMgmtCommand(StringConstantExpressionAst strConst, out CommandAst command)
{
command = null;
bool result = false;
if (strConst.Parent is CommandAst cmdAst && ReferenceEquals(cmdAst.CommandElements[0], strConst) && s_SecretMgmtCommands.Contains(strConst.Value))
{
result = true;
command = cmdAst;
}
return result;
}
private static bool IsSafePropertyUsage(Ast member)
{
bool result = false;
if (member.Parent is MemberExpressionAst memberExpr)
{
// - If the property is NOT on the left side of an assignment, then it's safe.
// - Otherwise, if the right-hand side is a pipeline or a variable, then we consider it safe.
result = !IsOnLeftSideOfAnAssignment(memberExpr, out Ast rhs)
|| rhs is PipelineAst
|| (rhs is CommandExpressionAst cmdExpr && cmdExpr.Expression is VariableExpressionAst);
}
return result;
}
private static ExpressionAst GetArgumentForParameter(CommandParameterAst param)
{
if (param.Argument is not null)
{
return param.Argument;
}
var command = (CommandAst)param.Parent;
int index = 1;
for (; index < command.CommandElements.Count; index++)
{
if (ReferenceEquals(command.CommandElements[index], param))
{
break;
}
}
int argIndex = index + 1;
if (argIndex < command.CommandElements.Count
&& command.CommandElements[argIndex] is ExpressionAst arg)
{
return arg;
}
return null;
}
private static bool IsCloudTokenOrSecretAccess(StringConstantExpressionAst arg2Ast, out CommandAst command)
{
bool result = false;
command = arg2Ast.Parent as CommandAst;
if (command is not null && command.CommandElements.Count >= 3
&& command.CommandElements[0] is StringConstantExpressionAst nameAst
&& command.CommandElements[1] is StringConstantExpressionAst arg1Ast
&& command.CommandElements[2] == arg2Ast)
{
string name = nameAst.Value;
string arg1 = arg1Ast.Value;
string arg2 = arg2Ast.Value;
if (string.Equals(name, "gcloud", StringComparison.OrdinalIgnoreCase))
{
result = string.Equals(arg1, "auth", StringComparison.OrdinalIgnoreCase) &&
string.Equals(arg2, "print-access-token", StringComparison.OrdinalIgnoreCase);
}
else if (string.Equals(name, "az", StringComparison.OrdinalIgnoreCase))
{
result = string.Equals(arg1, "account", StringComparison.OrdinalIgnoreCase) &&
string.Equals(arg2, "get-access-token", StringComparison.OrdinalIgnoreCase);
}
else if (string.Equals(name, "kubectl", StringComparison.OrdinalIgnoreCase))
{
result = (string.Equals(arg1, "get", StringComparison.OrdinalIgnoreCase) || string.Equals(arg1, "describe", StringComparison.OrdinalIgnoreCase))
&& (string.Equals(arg2, "secrets", StringComparison.OrdinalIgnoreCase) || string.Equals(arg2, "secret", StringComparison.OrdinalIgnoreCase));
}
}
if (!result)
{
command = null;
}
return result;
}
public static AddToHistoryOption GetDefaultAddToHistoryOption(string line)
{
if (string.IsNullOrEmpty(line))
{
return AddToHistoryOption.SkipAdding;
}
Match match = s_sensitivePattern.Match(line);
if (ReferenceEquals(match, Match.Empty))
{
return AddToHistoryOption.MemoryAndFile;
}
// The input contains at least one match of some sensitive patterns, so now we need to further
// analyze the input using the ASTs to see if it should actually be considered sensitive.
bool isSensitive = false;
ParseError[] parseErrors = _singleton._parseErrors;
// We need to compare the text here, instead of simply checking whether or not '_ast' is null.
// This is because we may need to update from history file in the middle of editing an input,
// and in that case, the '_ast' may be not-null, but it was not parsed from 'line'.
Ast ast = string.Equals(_singleton._ast?.Extent.Text, line)
? _singleton._ast
: Parser.ParseInput(line, out _, out parseErrors);
if (parseErrors != null && parseErrors.Length > 0)
{
// If the input has any parsing errors, we cannot reliably analyze the AST. We just consider
// it sensitive in this case, given that it contains matches of our sensitive pattern.
return AddToHistoryOption.MemoryOnly;
}
do
{
int start = match.Index;
int end = start + match.Length;
IEnumerable<Ast> asts = ast.FindAll(
ast => ast.Extent.StartOffset <= start && ast.Extent.EndOffset >= end,
searchNestedScriptBlocks: true);
Ast innerAst = asts.Last();
switch (innerAst)
{
case VariableExpressionAst:
// It's a variable with sensitive name. Using the variable is fine, but assigning to
// the variable could potentially expose sensitive content.
// If it appears on the left-hand-side of an assignment, and the right-hand-side is
// not a command invocation, we consider it sensitive.
// e.g. `$token = Get-Secret` vs. `$token = 'token-text'` or `$token, $url = ...`
isSensitive = IsOnLeftSideOfAnAssignment(innerAst, out Ast rhs) && !IsRightSideOfAnAssignmentSafe(rhs);
if (!isSensitive)
{
match = match.NextMatch();
}
break;
case StringConstantExpressionAst strConst:
isSensitive = true;
if (IsSecretMgmtCommand(strConst, out CommandAst command)
|| IsCloudTokenOrSecretAccess(strConst, out command))
{
// If it's one of the secret management commands that we can ignore, we consider it safe.
isSensitive = false;
// And we can safely skip the whole command text in this case.
match = s_sensitivePattern.Match(line, command.Extent.EndOffset);
}
else if (IsSafePropertyUsage(strConst))
{
isSensitive = false;
match = match.NextMatch();
}
break;
case CommandParameterAst param:
// Special-case the '-AsPlainText' parameter.
if (string.Equals(param.ParameterName, "AsPlainText"))
{
isSensitive = true;
break;
}
ExpressionAst arg = GetArgumentForParameter(param);
if (arg is null)
{
// If no argument is found following the parameter, then it could be a switching parameter
// such as '-UseDefaultPassword' or '-SaveToken', which we assume will not expose sensitive information.
match = match.NextMatch();
}
else if (arg is VariableExpressionAst)
{
// Argument is a variable. It's fine to use a variable for a senstive parameter.
// e.g. `Invoke-WebRequest -Token $token`
match = s_sensitivePattern.Match(line, arg.Extent.EndOffset);
}
else if (arg is ParenExpressionAst paren
&& paren.Pipeline is PipelineAst pipeline
&& pipeline.PipelineElements[0] is not CommandExpressionAst)
{
// Argument is a command invocation, such as `Invoke-WebRequest -Token (Get-Secret)`.
match = match.NextMatch();
}
else
{
// We consider all other arguments sensitive.
isSensitive = true;
}
break;
default:
isSensitive = true;
break;
}
}
while (!isSensitive && !ReferenceEquals(match, Match.Empty));
return isSensitive ? AddToHistoryOption.MemoryOnly : AddToHistoryOption.MemoryAndFile;
}
/// <summary>
/// Add a command to the history - typically used to restore
/// history from a previous session.
/// </summary>
public static void AddToHistory(string command)
{
command = command.Replace("\r\n", "\n");
var editItems = new List<EditItem> {EditItemInsertString.Create(command, 0)};
_singleton.MaybeAddToHistory(command, editItems, 1);
}
/// <summary>
/// Clears history in PSReadLine. This does not affect PowerShell history.
/// </summary>
public static void ClearHistory(ConsoleKeyInfo? key = null, object arg = null)
{
_singleton._history?.Clear();
_singleton._recentHistory?.Clear();
_singleton._currentHistoryIndex = 0;
}
/// <summary>
/// Return a collection of history items.
/// </summary>
public static HistoryItem[] GetHistoryItems()
{
return _singleton._history.ToArray();
}
enum HistoryMoveCursor { ToEnd, ToBeginning, DontMove }
private void UpdateFromHistory(HistoryMoveCursor moveCursor)
{
string line;
if (_currentHistoryIndex == _history.Count)
{
line = _savedCurrentLine.CommandLine;
_edits = new List<EditItem>(_savedCurrentLine._edits);
_undoEditIndex = _savedCurrentLine._undoEditIndex;
_editGroupStart = _savedCurrentLine._editGroupStart;
}
else
{
line = _history[_currentHistoryIndex].CommandLine;
_edits = new List<EditItem>(_history[_currentHistoryIndex]._edits);
_undoEditIndex = _history[_currentHistoryIndex]._undoEditIndex;
_editGroupStart = _history[_currentHistoryIndex]._editGroupStart;
}
_buffer.Clear();
_buffer.Append(line);
switch (moveCursor)
{
case HistoryMoveCursor.ToEnd:
_current = Math.Max(0, _buffer.Length + ViEndOfLineFactor);
break;
case HistoryMoveCursor.ToBeginning:
_current = 0;
break;
default:
if (_current > _buffer.Length)
{
_current = Math.Max(0, _buffer.Length + ViEndOfLineFactor);
}
break;
}
using var _ = _prediction.DisableScoped();
Render();
}
private void SaveCurrentLine()
{
// We're called before any history operation - so it's convenient
// to check if we need to load history from another sessions now.
MaybeReadHistoryFile();
_anyHistoryCommandCount += 1;
if (_savedCurrentLine.CommandLine == null)
{
_savedCurrentLine.CommandLine = _buffer.ToString();
_savedCurrentLine._edits = _edits;
_savedCurrentLine._undoEditIndex = _undoEditIndex;
_savedCurrentLine._editGroupStart = _editGroupStart;
}
}
private void HistoryRecall(int direction)
{
if (_recallHistoryCommandCount == 0 && LineIsMultiLine())
{
MoveToLine(direction);
return;
}
if (Options.HistoryNoDuplicates && _recallHistoryCommandCount == 0)
{
_hashedHistory = new Dictionary<string, int>();
}
int count = Math.Abs(direction);
direction = direction < 0 ? -1 : +1;
int newHistoryIndex = _currentHistoryIndex;
while (count > 0)
{
newHistoryIndex += direction;
if (newHistoryIndex < 0 || newHistoryIndex >= _history.Count)
{
break;
}
if (_history[newHistoryIndex].FromOtherSession)
{
continue;
}
if (Options.HistoryNoDuplicates)
{
var line = _history[newHistoryIndex].CommandLine;
if (!_hashedHistory.TryGetValue(line, out var index))
{
_hashedHistory.Add(line, newHistoryIndex);
--count;
}
else if (newHistoryIndex == index)
{
--count;
}
}
else
{
--count;
}
}
_recallHistoryCommandCount += 1;
if (newHistoryIndex >= 0 && newHistoryIndex <= _history.Count)
{
_currentHistoryIndex = newHistoryIndex;
var moveCursor = InViCommandMode() && !_options.HistorySearchCursorMovesToEnd
? HistoryMoveCursor.ToBeginning
: HistoryMoveCursor.ToEnd;
UpdateFromHistory(moveCursor);
}
}
/// <summary>
/// Replace the current input with the 'previous' item from PSReadLine history.
/// </summary>
public static void PreviousHistory(ConsoleKeyInfo? key = null, object arg = null)
{
TryGetArgAsInt(arg, out var numericArg, -1);
if (numericArg > 0)
{
numericArg = -numericArg;
}
if (UpdateListSelection(numericArg))
{
return;
}
_singleton.SaveCurrentLine();
_singleton.HistoryRecall(numericArg);
}
/// <summary>
/// Replace the current input with the 'next' item from PSReadLine history.
/// </summary>
public static void NextHistory(ConsoleKeyInfo? key = null, object arg = null)
{
TryGetArgAsInt(arg, out var numericArg, +1);
if (UpdateListSelection(numericArg))
{
return;
}
_singleton.SaveCurrentLine();
_singleton.HistoryRecall(numericArg);
}
private void HistorySearch(int direction)
{
if (_searchHistoryCommandCount == 0)
{
if (LineIsMultiLine())
{
MoveToLine(direction);
return;
}
_searchHistoryPrefix = _buffer.ToString(0, _current);
_emphasisStart = 0;
_emphasisLength = _current;
if (Options.HistoryNoDuplicates)
{
_hashedHistory = new Dictionary<string, int>();
}
}
_searchHistoryCommandCount += 1;
int count = Math.Abs(direction);
direction = direction < 0 ? -1 : +1;