Skip to content
Merged
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
90 changes: 61 additions & 29 deletions README.md

Large diffs are not rendered by default.

21 changes: 20 additions & 1 deletion src/TermRest.Cli/CliApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ internal static class CliApp
/// <summary>Cancelled by the first Ctrl+C or SIGTERM while <c>send</c> or <c>run</c> works (see <see cref="Stop"/>).</summary>
private static readonly CancellationTokenSource Stopping = new();

private static Action? s_interrupt;

/// <summary>
/// Takes the next Ctrl+C in place of <see cref="Stopping"/>, once: <c>send</c> stops a response that streams with it,
/// keeping what arrived. Null: Ctrl+C stops the command.
/// </summary>
internal static Action? Interrupt
{
get => Volatile.Read(ref s_interrupt);
set => Volatile.Write(ref s_interrupt, value);
}

public static async Task<int> RunAsync(string[] args)
{
var insecure = new Option<bool>("--insecure", "-k") { Description = "Do not verify server TLS certificates", Recursive = true };
Expand Down Expand Up @@ -71,10 +83,17 @@ public static async Task<int> RunAsync(string[] args)
/// <summary>
/// The first Ctrl+C (or SIGTERM: a cancelled CI job) stops <c>send</c> and <c>run</c>, which still save their recording
/// and write their report, however long that takes (System.CommandLine would end the process 2 seconds after the
/// signal); another one ends TermRest at once.
/// signal); another one ends TermRest at once. A Ctrl+C that <see cref="Interrupt"/> takes does neither.
/// </summary>
private static void Stop(PosixSignalContext context)
{
if (context.Signal == PosixSignal.SIGINT && Interlocked.Exchange(ref s_interrupt, null) is { } interrupt)
{
context.Cancel = true;
interrupt();
return;
}

context.Cancel = !Stopping.IsCancellationRequested;
Stopping.Cancel();
}
Expand Down
39 changes: 39 additions & 0 deletions src/TermRest.Cli/ConsolePassword.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Text;

namespace TermRest.Cli;

/// <summary>Reads a password typed in the terminal, without showing it.</summary>
internal static class ConsolePassword
{
/// <summary>The password typed after <paramref name="prompt"/> (written to stderr), or null when there is no terminal to type it in.</summary>
public static string? Read(string prompt)
{
if (Console.IsInputRedirected)
{
return null;
}

Console.Error.Write(prompt);
var password = new StringBuilder();
while (true)
{
var key = Console.ReadKey(intercept: true);
if (key.Key == ConsoleKey.Enter)
{
break;
}

if (key.Key == ConsoleKey.Backspace)
{
password.Length = Math.Max(0, password.Length - 1);
}
else if (key.KeyChar != '\0' && !char.IsControl(key.KeyChar))
{
password.Append(key.KeyChar);
}
}

Console.Error.WriteLine();
return password.ToString();
}
}
8 changes: 5 additions & 3 deletions src/TermRest.Cli/ConvertCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,13 @@ private static int ConvertCollection(string path, string? to, string? output, in
return 2;
}

var warningsBefore = source.LoadWarnings.Count;
TextFile.WriteAtomic(file, source.ExportV21Json(), newFileMode: TextFile.CopyMode(path)); // as private as its source
Output.Status($"✓ {source.AllRequests().Count()} request(s) written to {file}", true);
if (Directory.EnumerateFiles(path, "*.example.yaml", SearchOption.AllDirectories).Any())
var exampleCount = source.AllRequests().Sum(r => source.GetExamples(r).Count);
Output.Status($"✓ {source.AllRequests().Count()} request(s){(exampleCount > 0 ? $" and {exampleCount} example(s)" : "")} written to {file}", true);
foreach (var unreadable in source.LoadWarnings.Skip(warningsBefore))
{
Output.Info(" Saved examples (*.example.yaml) are not included in the v2.1 file.");
Output.Warning($"Example left out: {unreadable}");
}

if (source.CredentialSetsLeftOutOfV21() is { Count: > 0 } owners)
Expand Down
55 changes: 55 additions & 0 deletions src/TermRest.Cli/RequestOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ internal sealed class RequestOptions
Description = "Also send body and form-data files from outside the workspace folder (default: only where allowed for the workspace in the full-screen UI, Tools › Settings…)",
};

public Option<string?> Proxy { get; } = new("--proxy", "-x")
{
Description = "The proxy for every request: a URL (http://host:port), \"system\" (the OS's settings, HTTPS_PROXY) or \"none\" " +
"(default: the workspace's, once allowed in the full-screen UI)",
};

public Option<string?> ProxyUser { get; } = new("--proxy-user", "-U")
{
Description = "The proxy's user name and password: user:password, or user to be asked for the password (DOMAIN\\user for NTLM). " +
"Default: those in the proxy's URL or kept in the full-screen UI (Tools › Settings › Proxy sign-in), else your own sign-in for NTLM and Negotiate proxies",
};

public void AddTo(Command command)
{
command.Options.Add(Environment);
Expand All @@ -67,6 +79,8 @@ public void AddTo(Command command)
command.Options.Add(ScriptOrder);
command.Options.Add(NoScripts);
command.Options.Add(AllowOutsideFiles);
command.Options.Add(Proxy);
command.Options.Add(ProxyUser);
}

/// <summary>
Expand Down Expand Up @@ -194,6 +208,47 @@ public bool SaveRecording(ParseResult parseResult, RequestRunner runner, Request
}

runner.ConfigureProxy();
if (parseResult.GetValue(Proxy) is { } proxyOverride)
{
var value = proxyOverride.Trim();
if (WorkspaceSettings.IsProxyUrl(value) && !value.Contains("://", StringComparison.Ordinal))
{
value = "http://" + value; // host:port, as curl takes it
}

if (WorkspaceSettings.IsProxyUrl(value) && !(Uri.TryCreate(value, UriKind.Absolute, out var proxyUri) && proxyUri.Scheme is "http" or "https" or "socks4" or "socks4a" or "socks5"))
{
Output.Error($"--proxy expects a URL (http://host:port), \"system\" or \"none\", got '{PostmanUrl.MaskCredentials(value)}'.");
runner.Dispose();
return null;
}

runner.ProxyOverride = value;
}

if (parseResult.GetValue(ProxyUser) is { } proxyUser)
{
var colon = proxyUser.IndexOf(':', StringComparison.Ordinal);
var user = colon < 0 ? proxyUser : proxyUser[..colon];
var password = colon < 0 ? ConsolePassword.Read($"Proxy password for {user}: ") : proxyUser[(colon + 1)..];
if (user.Trim().Length == 0 || password is null)
{
Output.Error(password is null
? "--proxy-user: give the password as user:password, as there is no terminal to type it in."
: "--proxy-user expects user:password, or user to be asked for the password.");
runner.Dispose();
return null;
}

runner.ProxyCredentialOverride = ProxyCredentialStore.Credential(user.Trim(), password);
}

if (runner.ProxyCredentials.LoadError is { } credentialsProblem)
{
Output.Warning(credentialsProblem);
Output.Info(" The proxy user names and passwords kept in the full-screen UI are not used until the file is fixed.");
}

if (runner.BlockedProxy is { } proxy)
{
Output.Warning($"The proxy in {workspace.SettingsPath} ({PostmanUrl.MaskCredentials(proxy.Trim())}) is not used, as a cloned repository could send " +
Expand Down
Loading
Loading