From a4a39938ff360be262bbee53ebf4d9e465c08c8a Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Tue, 17 Nov 2026 18:44:45 -0700 Subject: [PATCH 1/2] Core, CLI and TUI: OAuth 2.0 token acquisition An OAuth 2.0 auth helper fetches its access token itself, from any authorization server that follows the standard (RFC 6749), when a request that uses it is sent: client credentials, password, and authorization code with or without PKCE (SHA-256 or plain). Signing in opens the sign-in page in the browser; a loopback callback URL (localhost, 127.0.0.1 or [::1], or none for a free port) is received by TermRest itself (RFC 8252), and otherwise the address the browser ended on is pasted, its state checked. The client authenticates with HTTP Basic or in the form, as in Postman, or with a JWT client assertion (RFC 7523, private_key_jwt: TermRest's x-clientAssertion settings) signed with a registered client certificate's key, in RS, PS or ES 256/384/512, naming the certificate by its thumbprints (x5t#S256, x5t), and optionally a key ID and the chain (x5c). Tokens are kept in memory for the session, one per set of settings, and refreshed with the refresh token when they expire (a new one is fetched if the refresh is refused). Token requests go with the workspace's SSL verification, proxy, CA bundle and client certificate, follow no redirects, send no cookies and are not recorded; one that fails stops the request with the server's error. Until the token URL is set, the access token stored in the collection is sent, as before. Postman's extra token, auth and refresh parameters are sent. In the UI, the Auth tab's OAuth 2.0 form scrolls, shows the current token and when it expires, and has Get new token and Forget token; signing in waits in a dialog that opens the browser again, copies the address, or takes the address pasted. termrest send fetches tokens as it goes (the sign-in address is printed on stderr). Copy as cURL and send --curl add a token fetched earlier, or warn that there is none. A client certificate may have no URL patterns: it goes to no server, and signs client assertions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/TermRest.Cli/ConsoleSignIn.cs | 82 +++ src/TermRest.Cli/RequestOptions.cs | 1 + src/TermRest.Cli/SendCommand.cs | 4 +- src/TermRest.Cli/ValidateAndCertsCommands.cs | 2 +- src/TermRest.Core/Auth/AuthApplier.cs | 19 +- src/TermRest.Core/Auth/ClientAssertion.cs | 141 +++++ src/TermRest.Core/Auth/LoopbackRedirect.cs | 237 ++++++++ src/TermRest.Core/Auth/OAuth2Settings.cs | 300 ++++++++++ src/TermRest.Core/Auth/OAuth2SignIn.cs | 34 ++ src/TermRest.Core/Auth/OAuth2Token.cs | 212 +++++++ src/TermRest.Core/Auth/OAuth2Tokens.cs | 556 ++++++++++++++++++ src/TermRest.Core/Auth/SystemBrowser.cs | 87 +++ src/TermRest.Core/Http/PreparedRequest.cs | 9 + src/TermRest.Core/Http/RequestPreparer.cs | 47 +- .../Workspace/RequestRunner.Scripts.cs | 2 + src/TermRest.Core/Workspace/RequestRunner.cs | 66 +++ .../Dialogs/CertificatesDialog.cs | 8 +- src/TermRest.Tui/Dialogs/SignInDialog.cs | 146 +++++ src/TermRest.Tui/MainWindow.cs | 121 ++++ src/TermRest.Tui/Views/AuthEditor.cs | 418 +++++++++++-- src/TermRest.Tui/Views/RequestEditor.cs | 34 ++ src/TermRest.Tui/Views/ResponseView.cs | 7 +- tests/TermRest.Cli.Tests/CommandLineTests.cs | 26 + .../Infrastructure/TestServer.cs | 21 +- .../Infrastructure/OAuthServer.cs | 269 +++++++++ tests/TermRest.Core.Tests/OAuth2Tests.cs | 480 +++++++++++++++ tests/TermRest.Tui.Tests/MainWindowTests.cs | 209 ++++++- .../TermRest.Tui.Tests.csproj | 3 +- 28 files changed, 3465 insertions(+), 76 deletions(-) create mode 100644 src/TermRest.Cli/ConsoleSignIn.cs create mode 100644 src/TermRest.Core/Auth/ClientAssertion.cs create mode 100644 src/TermRest.Core/Auth/LoopbackRedirect.cs create mode 100644 src/TermRest.Core/Auth/OAuth2Settings.cs create mode 100644 src/TermRest.Core/Auth/OAuth2SignIn.cs create mode 100644 src/TermRest.Core/Auth/OAuth2Token.cs create mode 100644 src/TermRest.Core/Auth/OAuth2Tokens.cs create mode 100644 src/TermRest.Core/Auth/SystemBrowser.cs create mode 100644 src/TermRest.Tui/Dialogs/SignInDialog.cs create mode 100644 tests/TermRest.Core.Tests/Infrastructure/OAuthServer.cs create mode 100644 tests/TermRest.Core.Tests/OAuth2Tests.cs diff --git a/src/TermRest.Cli/ConsoleSignIn.cs b/src/TermRest.Cli/ConsoleSignIn.cs new file mode 100644 index 0000000..e41cb66 --- /dev/null +++ b/src/TermRest.Cli/ConsoleSignIn.cs @@ -0,0 +1,82 @@ +using TermRest.Core.Auth; + +namespace TermRest.Cli; + +/// +/// Signing in for an OAuth 2.0 authorization code on the command line: the browser opens the sign-in page (its URL is +/// printed too, for a browser elsewhere), and returns the code to TermRest's loopback redirect URI, or the user pastes the +/// URL it ended on (a redirect URI elsewhere, or a browser on another machine, as over SSH). All on stderr: stdout is +/// the response's. +/// +internal sealed class ConsoleSignIn : IOAuth2Interaction +{ + /// A line being read from stdin; one at a time, kept for the next sign-in when this one ended without it. + private Task? _reading; + + public async Task SignInAsync(OAuth2SignIn signIn, CancellationToken cancellationToken) + { + var interactive = !Console.IsInputRedirected; + var opened = SystemBrowser.TryOpen(signIn.AuthorizationUrl); + var url = signIn.AuthorizationUrl.AbsoluteUri; + Output.Info(opened ? $"Sign in in the browser that opened, or at:\n {url}" : $"Sign in at:\n {url}"); + if (signIn.Redirect is not { } redirect) + { + if (!interactive) + { + throw new OAuth2Exception($"OAuth 2.0: after the sign-in, the browser goes to {signIn.RedirectUri}, which is not a loopback address TermRest " + + "listens on, and there is no terminal to paste the URL it ends on."); + } + + Output.Info($"The browser then goes to {signIn.RedirectUri}: paste the URL it ends on (its address bar) and press Enter."); + while (true) + { + var line = await ReadLineAsync(cancellationToken).ConfigureAwait(false); + if (line is null || line.Trim().Length > 0) + { + return line; + } + } + } + + if (!interactive) + { + // In CI nobody signs in: no need to wait for it. + if (!opened) + { + throw new OAuth2Exception("OAuth 2.0: signing in needs a browser, and TermRest could not open one (nor is there a terminal to paste the URL it ends on)."); + } + + Output.Info($"Waiting for the browser to return to {signIn.RedirectUri} …"); + return await redirect.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + Output.Info($"Waiting for the browser to return to {signIn.RedirectUri} … (with a browser on another machine, paste the URL it ends on and press Enter)"); + while (true) + { + var reading = _reading ??= Task.Run(Console.In.ReadLine, CancellationToken.None); + if (await Task.WhenAny((Task)redirect, reading).WaitAsync(cancellationToken).ConfigureAwait(false) != reading) + { + return await redirect.ConfigureAwait(false); + } + + _reading = null; + if (await reading.ConfigureAwait(false) is not { } line) + { + return await redirect.WaitAsync(cancellationToken).ConfigureAwait(false); // stdin closed: the browser it is + } + + if (line.Trim().Length > 0) + { + return line; + } + } + } + + private async Task ReadLineAsync(CancellationToken cancellationToken) + { + var reading = _reading ??= Task.Run(Console.In.ReadLine, CancellationToken.None); + var line = await reading.WaitAsync(cancellationToken).ConfigureAwait(false); + _reading = null; + return line; + } +} diff --git a/src/TermRest.Cli/RequestOptions.cs b/src/TermRest.Cli/RequestOptions.cs index 288c587..9c44410 100644 --- a/src/TermRest.Cli/RequestOptions.cs +++ b/src/TermRest.Cli/RequestOptions.cs @@ -180,6 +180,7 @@ public bool SaveRecording(ParseResult parseResult, RequestRunner runner, Request StrictSslOverride = parseResult.GetValue(insecure) ? false : null, TimeoutOverrideMs = parseResult.GetValue(Timeout), ScriptsEnabled = !parseResult.GetValue(NoScripts), + OAuth2Interaction = new ConsoleSignIn(), }; if (runner.ScriptsEnabled) diff --git a/src/TermRest.Cli/SendCommand.cs b/src/TermRest.Cli/SendCommand.cs index 28aa390..512704b 100644 --- a/src/TermRest.Cli/SendCommand.cs +++ b/src/TermRest.Cli/SendCommand.cs @@ -20,7 +20,7 @@ public static Command Create(Option insecure) var raw = new Option("--raw") { Description = "Print the body as received (no JSON/XML pretty printing); with --filter, the values on one line" }; var filter = new Option("--filter") { Description = "Print only the values a JSONPath query (RFC 9535) selects in a JSON body, as an array: --filter '$.items[?@.price < 10].id'" }; var fail = new Option("--fail", "-f") { Description = "Exit with code 22 when the HTTP status is 400 or higher" }; - var curl = new Option("--curl") { Description = "Print the request as a cURL command instead of sending it (scripts do not run)" }; + var curl = new Option("--curl") { Description = "Print the request as a cURL command instead of sending it (scripts do not run, no OAuth 2.0 token is fetched)" }; var noHistory = new Option("--no-history") { Description = "Do not record this request in the workspace history" }; var options = new RequestOptions(); command.Arguments.Add(collection); @@ -89,7 +89,9 @@ public static Command Create(Option insecure) var spec = match.Node.ReadSpec(); if (parseResult.GetValue(curl)) { + // Nothing is sent, so no OAuth 2.0 token is fetched: a warning says the command has none. var prepared = runner.Prepare(match.Collection, match.Node, spec); + runner.AddCachedToken(prepared); PrintWarnings(prepared); if (prepared.Errors.Count > 0) { diff --git a/src/TermRest.Cli/ValidateAndCertsCommands.cs b/src/TermRest.Cli/ValidateAndCertsCommands.cs index 6dd283f..b27cbd1 100644 --- a/src/TermRest.Cli/ValidateAndCertsCommands.cs +++ b/src/TermRest.Cli/ValidateAndCertsCommands.cs @@ -188,7 +188,7 @@ public static Command Create() foreach (var entry in workspace.Certificates.Entries) { Console.Out.WriteLine($"{entry.Name}{(entry.Disabled ? " (disabled)" : "")}"); - Console.Out.WriteLine($" matches: {string.Join(", ", entry.Matches)}"); + Console.Out.WriteLine($" matches: {(entry.Matches.Count == 0 ? "none (sent to no server; it can sign OAuth 2.0 client assertions)" : string.Join(", ", entry.Matches))}"); Console.Out.WriteLine($" source: {entry.DescribeSource()}"); try { diff --git a/src/TermRest.Core/Auth/AuthApplier.cs b/src/TermRest.Core/Auth/AuthApplier.cs index 6bf53a1..ff26b42 100644 --- a/src/TermRest.Core/Auth/AuthApplier.cs +++ b/src/TermRest.Core/Auth/AuthApplier.cs @@ -27,6 +27,12 @@ public sealed class AppliedAuth /// Resolved credentials (passwords, tokens, key values) that must not end up in history or logs. public List Secrets { get; } = []; + + /// + /// OAuth 2.0 settings to fetch the access token with before the request is sent (see ); the + /// token is added then. Null for other auth, and for an OAuth 2.0 helper that has a token set but no URLs to fetch one. + /// + public OAuth2Settings? OAuth2 { get; set; } } public static class AuthApplier @@ -118,15 +124,24 @@ public static AppliedAuth Apply(AuthSpec? auth, VariableResolver variables, ISet case "oauth2": { + // With URLs to fetch a token from, one is fetched (or the one fetched earlier taken) when the request is sent. + if (OAuth2Settings.Read(auth, value => variables.Resolve(value, unresolved), out var notFetched) is { } settings) + { + result.OAuth2 = settings; + result.Secrets.AddRange(settings.Secrets); + result.Description = $"OAuth 2.0, {settings.GrantName}"; + break; + } + var token = Get("accessToken"); result.Secrets.Add(token); if (token.Length == 0) { - result.Warnings.Add("OAuth 2.0: no access token is set. Paste a token in the Auth tab (token acquisition is not implemented yet)."); + result.Warnings.Add($"OAuth 2.0: there is no access token, and none is fetched: {notFetched}. The request was sent without one."); break; } - var prefix = auth.Get("headerPrefix") is { } p ? variables.Resolve(p, unresolved) : "Bearer"; + var prefix = OAuth2Settings.HeaderPrefixOf(auth, value => variables.Resolve(value, unresolved)); if (string.Equals(auth.Get("addTokenTo"), "queryParams", StringComparison.OrdinalIgnoreCase)) { result.QueryParameters.Add(new("access_token", token)); diff --git a/src/TermRest.Core/Auth/ClientAssertion.cs b/src/TermRest.Core/Auth/ClientAssertion.cs new file mode 100644 index 0000000..386527b --- /dev/null +++ b/src/TermRest.Core/Auth/ClientAssertion.cs @@ -0,0 +1,141 @@ +using System.Buffers.Text; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text.Json; +using TermRest.Core.Certificates; + +namespace TermRest.Core.Auth; + +/// +/// Client assertions (RFC 7523; private_key_jwt of OpenID Connect): a short-lived JWT the client signs with the +/// private key of its certificate, which the token endpoint checks with the certificate (or public key) registered for +/// the client. Okta, Auth0, Keycloak, Ping, Microsoft Entra ID and other servers take them. +/// +public static class ClientAssertion +{ + /// The client_assertion_type of a JWT assertion. + public const string AssertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; + + /// How long an assertion is valid: long enough for its token request, too short to be replayed later. + public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5); + + /// The JWS algorithms assertions are signed with: RSA (PKCS #1 v1.5 and PSS) and ECDSA. + public static readonly string[] Algorithms = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"]; + + /// + /// A signed assertion for (its issuer and subject) to (the token + /// endpoint), valid from for . Its header names the certificate by its + /// SHA-256 and SHA-1 thumbprints (x5t#S256, x5t), and (kid) and the + /// certificate chain (x5c) when asked for. Without an : RS256 for an RSA key, and for + /// an EC key the one of its curve (ES256 for P-256 …). Throws when it cannot sign. + /// + /// The certificate's name in the registry (for messages). + public static string Create(LoadedCertificate certificate, string name, string clientId, string audience, string? algorithm, string? keyId, bool withChain, + DateTimeOffset now) + { + var leaf = certificate.Certificate; + try + { + using var rsa = leaf.GetRSAPrivateKey(); + using var ecdsa = rsa is null ? leaf.GetECDsaPrivateKey() : null; + if (rsa is null && ecdsa is null) + { + throw new OAuth2Exception($"OAuth 2.0: certificate '{name}' has no RSA or EC private key to sign the client assertion with."); + } + + var curve = ecdsa?.KeySize switch + { + 256 => "ES256", + 384 => "ES384", + 521 => "ES512", + _ => null, + }; + algorithm = string.IsNullOrWhiteSpace(algorithm) ? rsa is not null ? "RS256" : curve : algorithm.Trim().ToUpperInvariant(); + if (algorithm is null || !Algorithms.Contains(algorithm, StringComparer.Ordinal)) + { + throw new OAuth2Exception(algorithm is null + ? $"OAuth 2.0: the EC key of certificate '{name}' is not on a curve JWS signs with (P-256, P-384 or P-521)." + : $"OAuth 2.0: '{algorithm}' is not an algorithm TermRest signs client assertions with ({string.Join(", ", Algorithms)})."); + } + + if (algorithm[0] == 'E' ? ecdsa is null || curve != algorithm : rsa is null) + { + throw new OAuth2Exception(rsa is not null + ? $"OAuth 2.0: certificate '{name}' has an RSA key, which signs with RS256, RS384, RS512, PS256, PS384 or PS512, not {algorithm}." + : $"OAuth 2.0: certificate '{name}' has an EC key{(curve is null ? "" : $", which signs with {curve}")}, not with {algorithm}."); + } + + var hash = algorithm[2..] switch + { + "256" => HashAlgorithmName.SHA256, + "384" => HashAlgorithmName.SHA384, + _ => HashAlgorithmName.SHA512, + }; + var header = Json(writer => + { + writer.WriteString("alg", algorithm); + writer.WriteString("typ", "JWT"); + writer.WriteString("x5t#S256", Base64Url.EncodeToString(leaf.GetCertHash(HashAlgorithmName.SHA256))); + writer.WriteString("x5t", Base64Url.EncodeToString(leaf.GetCertHash())); + if (!string.IsNullOrWhiteSpace(keyId)) + { + writer.WriteString("kid", keyId.Trim()); + } + + if (withChain) + { + writer.WriteStartArray("x5c"); + writer.WriteStringValue(Convert.ToBase64String(leaf.RawData)); + foreach (var issuer in certificate.Chain) + { + if (issuer.Thumbprint != leaf.Thumbprint) + { + writer.WriteStringValue(Convert.ToBase64String(issuer.RawData)); + } + } + + writer.WriteEndArray(); + } + }); + var seconds = now.ToUnixTimeSeconds(); + var payload = Json(writer => + { + writer.WriteString("aud", audience); + writer.WriteString("iss", clientId); + writer.WriteString("sub", clientId); + writer.WriteString("jti", Guid.NewGuid().ToString()); + writer.WriteNumber("iat", seconds); + writer.WriteNumber("nbf", seconds); + writer.WriteNumber("exp", seconds + (long)Lifetime.TotalSeconds); + }); + var signingInput = $"{Base64Url.EncodeToString(header)}.{Base64Url.EncodeToString(payload)}"; + var data = System.Text.Encoding.ASCII.GetBytes(signingInput); + + // JWS wants an ECDSA signature as r and s side by side (IEEE P1363), as SignData gives it. + var signature = rsa is not null + ? rsa.SignData(data, hash, algorithm[0] == 'P' ? RSASignaturePadding.Pss : RSASignaturePadding.Pkcs1) + : ecdsa!.SignData(data, hash, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + return $"{signingInput}.{Base64Url.EncodeToString(signature)}"; + } + catch (CryptographicException ex) + { + // A key in a store that asks for a PIN, or does not allow signing, among others. + throw new OAuth2Exception($"OAuth 2.0: certificate '{name}' could not sign the client assertion: {ex.Message}"); + } + } + + private static byte[] Json(Action write) + { + using var stream = new MemoryStream(); + + // As other JWT libraries write it: a '+' of a base64 certificate, a '&' of a URL as they are, not as \u002B. + using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping })) + { + writer.WriteStartObject(); + write(writer); + writer.WriteEndObject(); + } + + return stream.ToArray(); + } +} diff --git a/src/TermRest.Core/Auth/LoopbackRedirect.cs b/src/TermRest.Core/Auth/LoopbackRedirect.cs new file mode 100644 index 0000000..801837d --- /dev/null +++ b/src/TermRest.Core/Auth/LoopbackRedirect.cs @@ -0,0 +1,237 @@ +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Text; + +namespace TermRest.Core.Auth; + +/// +/// Receives the authorization response of a sign-in on a loopback redirect URI (http://localhost:port/path, +/// http://127.0.0.1…, http://[::1]…), as RFC 8252 has native apps do: the browser is redirected there with +/// the code, and shows a page that says the sign-in is done. +/// +public sealed class LoopbackRedirect : IDisposable +{ + /// The longest request head read: a redirect's URL with its code and state is far shorter. + private const int MaxHead = 32 * 1024; + + private readonly List _listeners; + private readonly string _path; + private readonly string _origin; + + private LoopbackRedirect(List listeners, string redirectUri, string origin, string path) + { + _listeners = listeners; + RedirectUri = redirectUri; + _origin = origin; + _path = path; + } + + /// The redirect URI it listens on (for an empty one, http://127.0.0.1:port/ with the port it chose). + public string RedirectUri { get; } + + /// + /// Starts listening on : null when it is not an http URL of a loopback host, which the + /// browser goes to elsewhere (the user pastes the URL it ends on instead). An empty one listens on a free port of + /// 127.0.0.1. Throws when the port cannot be listened on (another program has it). + /// + public static LoopbackRedirect? Start(string redirectUri) + { + IPAddress[] addresses; + int port; + string path; + if (redirectUri.Length == 0) + { + (addresses, port, path) = ([IPAddress.Loopback], 0, "/"); + } + else + { + if (!Uri.TryCreate(redirectUri, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttp || uri.UserInfo.Length > 0) + { + return null; + } + + // localhost may be either address to the browser. + if (string.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) + { + addresses = [IPAddress.Loopback, IPAddress.IPv6Loopback]; + } + else if (IPAddress.TryParse(uri.Host.Trim('[', ']'), out var address) && IPAddress.IsLoopback(address)) + { + addresses = [address]; + } + else + { + return null; + } + + (port, path) = (uri.Port, uri.AbsolutePath); + } + + var listeners = new List(); + SocketException? failure = null; + foreach (var address in addresses) + { + var listener = new TcpListener(address, port); + try + { + listener.Start(); + listeners.Add(listener); + port = ((IPEndPoint)listener.LocalEndpoint).Port; // the other address listens on the same port + } + catch (SocketException ex) + { + listener.Dispose(); + failure ??= ex; + } + } + + if (listeners.Count == 0) + { + throw new OAuth2Exception($"OAuth 2.0: TermRest could not listen on {(redirectUri.Length == 0 ? "a loopback port" : redirectUri)} for the sign-in's response: {failure!.Message}"); + } + + var origin = redirectUri.Length == 0 ? $"http://127.0.0.1:{port}" : new Uri(redirectUri).GetLeftPart(UriPartial.Authority); + return new LoopbackRedirect(listeners, redirectUri.Length == 0 ? origin + "/" : redirectUri, origin, path); + } + + /// + /// The URL the browser was redirected to (its query holds the response's code or error), once a request for the + /// redirect URI's path comes; requests for other paths (a favicon) get a 404. Throws + /// when cancelled. + /// + public async Task ReceiveAsync(CancellationToken cancellationToken) + { + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var accepting = _listeners.Select(listener => AcceptAsync(listener, received, stop.Token)).ToList(); + try + { + return await received.Task.WaitAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + await stop.CancelAsync().ConfigureAwait(false); + await Task.WhenAll(accepting).ConfigureAwait(false); + } + } + + private async Task AcceptAsync(TcpListener listener, TaskCompletionSource received, CancellationToken cancellationToken) + { + var connections = new List(); + while (!cancellationToken.IsCancellationRequested) + { + TcpClient client; + try + { + client = await listener.AcceptTcpClientAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is OperationCanceledException or ObjectDisposedException or SocketException) + { + break; + } + + // Each on its own: a browser opens connections it may send nothing on. + connections.Add(HandleAsync(client, received, cancellationToken)); + } + + await Task.WhenAll(connections).ConfigureAwait(false); + } + + private async Task HandleAsync(TcpClient client, TaskCompletionSource received, CancellationToken cancellationToken) + { + using (client) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + try + { + if (await RespondAsync(client.GetStream(), timeout.Token).ConfigureAwait(false) is { } url) + { + received.TrySetResult(url); + } + } + catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException or ObjectDisposedException) + { + // The browser went away, or it is over. + } + } + } + + /// Reads a request and answers it; the URL it was for when it brings the authorization response. + private async Task RespondAsync(NetworkStream stream, CancellationToken cancellationToken) + { + var buffer = new byte[MaxHead]; + var length = 0; + int end; + while ((end = buffer.AsSpan(0, length).IndexOf("\r\n\r\n"u8)) < 0) + { + if (length == buffer.Length) + { + await WriteAsync(stream, "431 Request Header Fields Too Large", "Request too large", null, cancellationToken).ConfigureAwait(false); + return null; + } + + var read = await stream.ReadAsync(buffer.AsMemory(length), cancellationToken).ConfigureAwait(false); + if (read == 0) + { + return null; + } + + length += read; + } + + var lineEnd = buffer.AsSpan(0, end).IndexOf("\r\n"u8); + var parts = Encoding.ASCII.GetString(buffer, 0, lineEnd < 0 ? end : lineEnd).Split(' '); + var target = parts.Length == 3 ? parts[1] : ""; + var query = target.IndexOf('?', StringComparison.Ordinal); + var path = query < 0 ? target : target[..query]; + if (parts.Length != 3 || parts[0] != "GET" || !string.Equals(path.TrimEnd('/'), _path.TrimEnd('/'), StringComparison.Ordinal)) + { + await WriteAsync(stream, "404 Not Found", "Not found", null, cancellationToken).ConfigureAwait(false); + return null; + } + + // A request without a response in it (the page loaded again) is not the one waited for. + var fields = OAuth2Response.ParseForm(query < 0 ? "" : target[(query + 1)..]); + if (!fields.ContainsKey("code") && !fields.ContainsKey("error")) + { + await WriteAsync(stream, "400 Bad Request", "No authorization response", "This address has no authorization code or error.", cancellationToken).ConfigureAwait(false); + return null; + } + + if (fields.TryGetValue("error", out var error)) + { + var description = fields.GetValueOrDefault("error_description"); + await WriteAsync(stream, "200 OK", "Sign-in failed", $"{error}{(string.IsNullOrEmpty(description) ? "" : ": " + description)}", cancellationToken).ConfigureAwait(false); + } + else + { + await WriteAsync(stream, "200 OK", "Signed in", "TermRest received the sign-in. You can close this tab and go back to TermRest.", cancellationToken).ConfigureAwait(false); + } + + return _origin + target; + } + + private static async Task WriteAsync(NetworkStream stream, string status, string title, string? text, CancellationToken cancellationToken) + { + var page = Encoding.UTF8.GetBytes( + $"TermRest: {WebUtility.HtmlEncode(title)}" + + $"

{WebUtility.HtmlEncode(title)}

" + + $"{(text is null ? "" : $"

{WebUtility.HtmlEncode(text)}

")}"); + var head = Encoding.ASCII.GetBytes( + $"HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {page.Length.ToString(CultureInfo.InvariantCulture)}\r\n" + + "Cache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; style-src 'unsafe-inline'\r\n" + + "Connection: close\r\n\r\n"); + await stream.WriteAsync(head, cancellationToken).ConfigureAwait(false); + await stream.WriteAsync(page, cancellationToken).ConfigureAwait(false); + } + + public void Dispose() + { + foreach (var listener in _listeners) + { + listener.Dispose(); + } + } +} diff --git a/src/TermRest.Core/Auth/OAuth2Settings.cs b/src/TermRest.Core/Auth/OAuth2Settings.cs new file mode 100644 index 0000000..a7668ed --- /dev/null +++ b/src/TermRest.Core/Auth/OAuth2Settings.cs @@ -0,0 +1,300 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json.Nodes; +using TermRest.Core.Certificates; +using TermRest.Core.Json; +using TermRest.Core.Model; + +namespace TermRest.Core.Auth; + +/// An OAuth 2.0 grant (Postman's grant_type). +public enum OAuth2Grant +{ + AuthorizationCode, + AuthorizationCodeWithPkce, + ClientCredentials, + Password, + Implicit, +} + +/// How the client authenticates to the token endpoint (Postman's client_authentication). +public enum OAuth2ClientAuthentication +{ + /// HTTP Basic with the client ID and secret (Postman's header, its default). + BasicHeader, + + /// The client ID and secret in the form (Postman's body). + Body, + + /// + /// A JWT signed with the private key of a registered certificate (private_key_jwt of OpenID Connect, RFC 7523): + /// a TermRest addition. + /// + PrivateKeyJwt, +} + +/// Where an extra parameter of a token, authorization or refresh request goes (Postman's send_as). +public enum OAuth2ParameterTarget +{ + Body, + Header, + Url, +} + +/// An extra parameter of a token, authorization or refresh request (Postman's advanced options), resolved. +public sealed record OAuth2Parameter(string Key, string Value, OAuth2ParameterTarget Target); + +/// +/// The settings of an OAuth 2.0 auth helper (Postman's oauth2 parameters) a token is fetched with, their variables +/// resolved: see . Postman's keys, and TermRest's for a client assertion signed with a certificate +/// (client_authentication: private_key_jwt): x-clientAssertionCertificate (the name of a certificate in the +/// workspace's registry), x-clientAssertionAlgorithm, x-clientAssertionKeyId, x-clientAssertionChain +/// and x-clientAssertionAudience. +/// +public sealed class OAuth2Settings +{ + /// The values of client_authentication: Postman's, and TermRest's private_key_jwt. + public static readonly string[] ClientAuthenticationValues = ["header", "body", "private_key_jwt"]; + + /// The values of grant_type (Postman's), in the order of . + public static readonly string[] GrantTypes = ["authorization_code", "authorization_code_with_pkce", "client_credentials", "password_credentials", "implicit"]; + + private OAuth2Settings() + { + } + + public OAuth2Grant Grant { get; private init; } + + public string AccessTokenUrl { get; private init; } = ""; + + public string AuthUrl { get; private init; } = ""; + + /// The callback URL; empty: TermRest listens on a loopback port of its choosing (see ). + public string RedirectUri { get; private init; } = ""; + + public string ClientId { get; private init; } = ""; + + public string ClientSecret { get; private init; } = ""; + + public string Scope { get; private init; } = ""; + + public string Username { get; private init; } = ""; + + public string Password { get; private init; } = ""; + + /// The state sent with the authorization request; empty: a random one. + public string State { get; private init; } = ""; + + /// The PKCE code verifier; empty: a random one. + public string CodeVerifier { get; private init; } = ""; + + /// The PKCE code challenge method: S256 or plain. + public string ChallengeMethod { get; private init; } = "S256"; + + public OAuth2ClientAuthentication ClientAuthentication { get; private init; } + + /// The name of the registered certificate that signs the client assertion. + public string AssertionCertificate { get; private init; } = ""; + + /// The JWS algorithm of the client assertion (RS256, PS256, ES256 …); empty: chosen for the key (see ). + public string AssertionAlgorithm { get; private init; } = ""; + + /// The kid of the client assertion's header; empty: none. + public string AssertionKeyId { get; private init; } = ""; + + /// Whether the client assertion's header holds the certificate chain (x5c). + public bool AssertionChain { get; private init; } + + /// The audience of the client assertion; empty: the URL of the token endpoint it goes to. + public string AssertionAudience { get; private init; } = ""; + + /// The certificate that signs the client assertion, loaded when the request was prepared (see ). + public LoadedCertificate? SigningCertificate { get; set; } + + /// Where a refresh token is redeemed; empty: . + public string RefreshTokenUrl { get; private init; } = ""; + + public IReadOnlyList TokenRequestParams { get; private init; } = []; + + public IReadOnlyList AuthRequestParams { get; private init; } = []; + + public IReadOnlyList RefreshRequestParams { get; private init; } = []; + + /// The token goes in the access_token query parameter rather than the Authorization header. + public bool AddToQuery { get; private init; } + + /// What precedes the token in the Authorization header (Bearer); empty: the token alone. + public string HeaderPrefix { get; private init; } = "Bearer"; + + /// + /// What identifies the token these settings fetch (a hash of everything that goes into it, secrets too): tokens are + /// cached under it. The state, code verifier and where the token goes don't count. + /// + public string CacheKey => field ??= ComputeCacheKey(); + + public bool IsAuthorizationCode => Grant is OAuth2Grant.AuthorizationCode or OAuth2Grant.AuthorizationCodeWithPkce; + + public string GrantName => Describe(Grant); + + /// The credentials among them (the client secret, the password), which are kept out of recordings and logs. + public IEnumerable Secrets => new[] { ClientSecret, Password }.Where(s => s.Length > 0); + + public static string Describe(OAuth2Grant grant) => grant switch + { + OAuth2Grant.AuthorizationCode => "authorization code", + OAuth2Grant.AuthorizationCodeWithPkce => "authorization code with PKCE", + OAuth2Grant.ClientCredentials => "client credentials", + OAuth2Grant.Password => "password", + _ => "implicit", + }; + + /// The grant a grant_type names; Postman's default (authorization code) for none, null for one it has not. + public static OAuth2Grant? ParseGrant(string? grantType) => grantType?.Trim().ToLowerInvariant() switch + { + null or "" or "authorization_code" => OAuth2Grant.AuthorizationCode, + "authorization_code_with_pkce" => OAuth2Grant.AuthorizationCodeWithPkce, + "client_credentials" => OAuth2Grant.ClientCredentials, + "password_credentials" or "password" => OAuth2Grant.Password, + "implicit" => OAuth2Grant.Implicit, + _ => null, + }; + + /// + /// The settings of (an oauth2 auth helper) a token is fetched with, their values resolved + /// by : a token is fetched when its URLs are set (the access token URL; for authorization + /// code, the auth URL too). Null when they are not, as when Postman writes the helper with a token pasted in it, or for + /// the implicit grant: says why, and the token set in it (accessToken) is used. + /// Only the settings its grant uses are resolved, so others name no unresolved variables. + /// + public static OAuth2Settings? Read(AuthSpec auth, Func resolve, out string notFetched) + { + string Trimmed(string key) => resolve(auth.Get(key)).Trim(); + + var grantType = auth.Get("grant_type"); + if (ParseGrant(grantType) is not { } grant) + { + notFetched = $"its grant type '{grantType}' is not one TermRest knows"; + return null; + } + + if (grant == OAuth2Grant.Implicit) + { + // Its token comes back in the URL's fragment, where the browser keeps it: RFC 9700 retires it. + notFetched = "the implicit grant is not supported (the OAuth 2.0 Security Best Current Practice retires it): use authorization code with PKCE"; + return null; + } + + var code = grant is OAuth2Grant.AuthorizationCode or OAuth2Grant.AuthorizationCodeWithPkce; + var tokenUrl = Trimmed("accessTokenUrl"); + var authUrl = code ? Trimmed("authUrl") : ""; + if (tokenUrl.Length == 0 || (code && authUrl.Length == 0)) + { + notFetched = tokenUrl.Length == 0 ? "its access token URL is empty" : "its auth URL is empty"; + return null; + } + + notFetched = ""; + var clientAuthentication = auth.Get("client_authentication")?.Trim().ToLowerInvariant() switch + { + "body" => OAuth2ClientAuthentication.Body, + "private_key_jwt" => OAuth2ClientAuthentication.PrivateKeyJwt, + _ => OAuth2ClientAuthentication.BasicHeader, + }; + var signed = clientAuthentication == OAuth2ClientAuthentication.PrivateKeyJwt; + var pkce = grant == OAuth2Grant.AuthorizationCodeWithPkce; + var password = grant == OAuth2Grant.Password; + var settings = new OAuth2Settings + { + Grant = grant, + AccessTokenUrl = tokenUrl, + AuthUrl = authUrl, + RedirectUri = code ? Trimmed("redirect_uri") : "", + ClientId = Trimmed("clientId"), + ClientSecret = signed ? "" : resolve(auth.Get("clientSecret")), + Scope = Trimmed("scope"), + Username = password ? resolve(auth.Get("username")) : "", + Password = password ? resolve(auth.Get("password")) : "", + State = code ? resolve(auth.Get("state")) : "", + CodeVerifier = pkce ? Trimmed("code_verifier") : "", + ChallengeMethod = pkce && string.Equals(auth.Get("challengeAlgorithm")?.Trim(), "plain", StringComparison.OrdinalIgnoreCase) ? "plain" : "S256", + ClientAuthentication = clientAuthentication, + AssertionCertificate = signed ? Trimmed("x-clientAssertionCertificate") : "", + AssertionAlgorithm = signed ? Trimmed("x-clientAssertionAlgorithm").ToUpperInvariant() : "", + AssertionKeyId = signed ? Trimmed("x-clientAssertionKeyId") : "", + AssertionChain = signed && string.Equals(auth.Get("x-clientAssertionChain")?.Trim(), "true", StringComparison.OrdinalIgnoreCase), + AssertionAudience = signed ? Trimmed("x-clientAssertionAudience") : "", + RefreshTokenUrl = Trimmed("refreshTokenUrl"), + TokenRequestParams = ReadParameters(auth, "tokenRequestParams", resolve), + AuthRequestParams = code ? ReadParameters(auth, "authRequestParams", resolve) : [], + RefreshRequestParams = ReadParameters(auth, "refreshRequestParams", resolve), + AddToQuery = string.Equals(auth.Get("addTokenTo"), "queryParams", StringComparison.OrdinalIgnoreCase), + HeaderPrefix = HeaderPrefixOf(auth, resolve), + }; + return settings; + } + + /// + /// What precedes the token in the Authorization header: headerPrefix without the white space around it (Postman + /// writes "Bearer " too), Bearer when it is not set. + /// + public static string HeaderPrefixOf(AuthSpec auth, Func resolve) => + auth.Get("headerPrefix") is { } prefix ? resolve(prefix).Trim() : "Bearer"; + + /// + /// The enabled extra parameters in (a list of {key, value, enabled, send_as}, as Postman + /// writes them), resolved; those without a key are left out. + /// + private static List ReadParameters(AuthSpec auth, string key, Func resolve) + { + var parameters = new List(); + if (auth.Params.FirstOrDefault(p => p.Key == key)?.Value is not JsonArray list) + { + return parameters; + } + + foreach (var item in list.OfType()) + { + var name = resolve(item["key"].GetString()).Trim(); + if (item["enabled"].GetBool() == false || name.Length == 0) + { + continue; + } + + var target = item["send_as"].GetString() switch + { + "request_header" => OAuth2ParameterTarget.Header, + "request_url" => OAuth2ParameterTarget.Url, + _ => OAuth2ParameterTarget.Body, + }; + parameters.Add(new OAuth2Parameter(name, resolve(item["value"].GetString()), target)); + } + + return parameters; + } + + private string ComputeCacheKey() + { + var text = new StringBuilder(); + void Add(string value) => text.Append(value.Length).Append(':').Append(value).Append('|'); + + foreach (var value in (string[])[Grant.ToString(), AccessTokenUrl, AuthUrl, RedirectUri, ClientId, ClientSecret, Scope, Username, Password, + ClientAuthentication.ToString(), AssertionCertificate, AssertionAlgorithm, AssertionKeyId, AssertionChain ? "chain" : "", AssertionAudience, + RefreshTokenUrl]) + { + Add(value); + } + + foreach (var (name, parameters) in (ReadOnlySpan<(string, IReadOnlyList)>)[("token", TokenRequestParams), ("auth", AuthRequestParams), ("refresh", RefreshRequestParams)]) + { + Add(name); + foreach (var parameter in parameters) + { + Add(parameter.Target.ToString()); + Add(parameter.Key); + Add(parameter.Value); + } + } + + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString()))); + } +} diff --git a/src/TermRest.Core/Auth/OAuth2SignIn.cs b/src/TermRest.Core/Auth/OAuth2SignIn.cs new file mode 100644 index 0000000..0742c65 --- /dev/null +++ b/src/TermRest.Core/Auth/OAuth2SignIn.cs @@ -0,0 +1,34 @@ +namespace TermRest.Core.Auth; + +/// A sign-in for an authorization code: where the user signs in, and where the browser returns. +public sealed class OAuth2SignIn +{ + /// The authorization request: the page of the authorization server the user signs in on. + public required Uri AuthorizationUrl { get; init; } + + /// The redirect URI the browser returns to with the authorization response (the code). + public required string RedirectUri { get; init; } + + /// + /// Completes with the URL the browser returned to, received on the loopback redirect URI (see + /// ); null when the redirect URI is elsewhere, so that the user pastes that URL. It fails + /// with when no response came in time. + /// + public Task? Redirect { get; init; } +} + +/// How the user signs in for an OAuth 2.0 authorization code: the full-screen UI and the command line each have theirs. +public interface IOAuth2Interaction +{ + /// + /// Has the user sign in at (in their browser) and returns the URL the + /// browser returned to with the authorization response: the one receives, or one the + /// user pastes (when the browser runs elsewhere, as over SSH). Null when the user gives up. + /// + Task SignInAsync(OAuth2SignIn signIn, CancellationToken cancellationToken); + + /// A token request goes to (the UI can say so while it waits). + void RequestingToken(string endpoint) + { + } +} diff --git a/src/TermRest.Core/Auth/OAuth2Token.cs b/src/TermRest.Core/Auth/OAuth2Token.cs new file mode 100644 index 0000000..7cfe488 --- /dev/null +++ b/src/TermRest.Core/Auth/OAuth2Token.cs @@ -0,0 +1,212 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using TermRest.Core.Http; +using TermRest.Core.Json; + +namespace TermRest.Core.Auth; + +/// Why an OAuth 2.0 token could not be had (a token request or sign-in failed); the message is the request's error. +public sealed class OAuth2Exception(string message) : Exception(message); + +/// An OAuth 2.0 access token a token endpoint issued (RFC 6749, section 5.1). +public sealed class OAuth2Token +{ + public required string AccessToken { get; init; } + + public string? TokenType { get; init; } + + public string? RefreshToken { get; init; } + + public string? IdToken { get; init; } + + /// The scope granted, when the server says (it may grant less than asked for). + public string? Scope { get; init; } + + public required DateTimeOffset ObtainedAt { get; init; } + + /// When it expires (expires_in); null when the server does not say: it is used until a new one is asked for. + public DateTimeOffset? ExpiresAt { get; init; } + + /// + /// Whether it can still be sent at : until it expires, less a margin (a minute, or a tenth of its + /// lifetime for a short-lived one) so that it does not expire on its way. + /// + public bool IsFresh(DateTimeOffset now) + { + if (ExpiresAt is not { } expires) + { + return true; + } + + var margin = TimeSpan.FromTicks(Math.Clamp((expires - ObtainedAt).Ticks / 10, 0, TimeSpan.TicksPerMinute)); + return now < expires - margin; + } + + /// When it expires, said for : "expires in 59 min", "expired", "no expiry given". + public string DescribeExpiry(DateTimeOffset now) + { + if (ExpiresAt is not { } expires) + { + return "no expiry given"; + } + + var left = expires - now; + return left <= TimeSpan.Zero ? "expired" + : left < TimeSpan.FromMinutes(1) ? $"expires in {left.TotalSeconds:0} s" + : left < TimeSpan.FromHours(2) ? $"expires in {left.TotalMinutes:0} min" + : left < TimeSpan.FromDays(2) ? $"expires in {left.TotalHours:0} h" + : $"expires {expires.ToLocalTime():yyyy-MM-dd HH:mm}"; + } + + /// + /// The token in a token endpoint's successful response (its , see ); + /// a refresh that returns no new refresh token keeps . Null without an access token. + /// + internal static OAuth2Token? From(IReadOnlyDictionary fields, DateTimeOffset now, string? previousRefreshToken) + { + if (fields.GetValueOrDefault("access_token") is not { Length: > 0 } accessToken) + { + return null; + } + + // A number, or a number in a string (as some servers write it). + var expiresIn = fields.GetValueOrDefault("expires_in") is { } text + && double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var seconds) && seconds > 0 && seconds < TimeSpan.MaxValue.TotalSeconds / 2 + ? TimeSpan.FromSeconds(seconds) + : (TimeSpan?)null; + return new OAuth2Token + { + AccessToken = accessToken, + TokenType = fields.GetValueOrDefault("token_type"), + RefreshToken = fields.GetValueOrDefault("refresh_token") is { Length: > 0 } refreshToken ? refreshToken : previousRefreshToken, + IdToken = fields.GetValueOrDefault("id_token"), + Scope = fields.GetValueOrDefault("scope"), + ObtainedAt = now, + ExpiresAt = now + expiresIn, + }; + } +} + +/// Where a token a request got came from. +public enum OAuth2TokenOrigin +{ + /// Fetched earlier, and still fresh. + Cached, + + /// Fetched now. + Fetched, + + /// Refreshed now, with the refresh token of the one fetched earlier. + Refreshed, +} + +/// A token a request got, where it came from, and the token endpoint it came from. +/// The token endpoint's URL, without its query (see ). +/// How the token request went (status and time): "200 in 85 ms"; null for a cached token. +public sealed record OAuth2Result(OAuth2Token Token, OAuth2TokenOrigin Origin, string Endpoint, string? Exchange = null) +{ + /// What the request's auth was, for its timeline: the grant, and where its token came from (no secret). + public string Describe(OAuth2Settings settings, DateTimeOffset now) => Origin switch + { + OAuth2TokenOrigin.Fetched => $"OAuth 2.0, {settings.GrantName}: new token from {Endpoint} ({Exchange}), {Token.DescribeExpiry(now)}", + OAuth2TokenOrigin.Refreshed => $"OAuth 2.0, {settings.GrantName}: token refreshed at {Endpoint} ({Exchange}), {Token.DescribeExpiry(now)}", + _ => $"OAuth 2.0, {settings.GrantName}: token from {Endpoint}, fetched {Token.ObtainedAt.ToLocalTime():HH:mm:ss}, {Token.DescribeExpiry(now)}", + }; +} + +/// Reads what a token endpoint answers. +internal static class OAuth2Response +{ + /// + /// The fields of a token endpoint's response: a JSON object's string and number members (RFC 6749, section 5.1), or a + /// form (as GitHub answers a client that does not accept JSON). Null for anything else (an HTML error page). + /// + public static Dictionary? ReadFields(byte[] body) + { + var text = Encoding.UTF8.GetString(body).Trim(); + if (text.StartsWith('{')) + { + try + { + using var document = JsonDocument.Parse(text); + if (document.RootElement is not { ValueKind: JsonValueKind.Object } root) + { + return null; + } + + var fields = new Dictionary(StringComparer.Ordinal); + foreach (var property in root.EnumerateObject()) + { + if (property.Value.ValueKind == JsonValueKind.String) + { + fields[property.Name] = property.Value.GetString()!; + } + else if (property.Value.ValueKind == JsonValueKind.Number) + { + fields[property.Name] = property.Value.GetRawText(); + } + } + + return fields; + } + catch (JsonException) + { + return null; + } + } + + if (text.Length == 0 || text.Contains('<', StringComparison.Ordinal) || !text.Contains('=', StringComparison.Ordinal) || text.Any(char.IsWhiteSpace)) + { + return null; + } + + return ParseForm(text); + } + + /// The fields of a form or query (a=1&b=x%20y; a '+' is a space); a field named twice keeps its first value. + public static Dictionary ParseForm(string text) + { + var fields = new Dictionary(StringComparer.Ordinal); + foreach (var pair in text.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var equals = pair.IndexOf('=', StringComparison.Ordinal); + var key = Decode(equals < 0 ? pair : pair[..equals]); + fields.TryAdd(key, equals < 0 ? "" : Decode(pair[(equals + 1)..])); + } + + return fields; + + static string Decode(string value) + { + try + { + return Uri.UnescapeDataString(value.Replace('+', ' ')); + } + catch (UriFormatException) + { + return value; + } + } + } + + /// + /// What a failed token request's response says: its error and error_description (RFC 6749, section 5.2), + /// or the start of a text body; empty when it says nothing. + /// + public static string DescribeError(ResponseSnapshot response, IReadOnlyDictionary? fields) + { + if (fields?.GetValueOrDefault("error") is { Length: > 0 } error) + { + return fields.GetValueOrDefault("error_description") is { Length: > 0 } description ? $"{error}: {description}" : error; + } + + if (!BodyFormatter.LooksLikeText(response.Body, response.ContentType)) + { + return ""; + } + + var text = string.Join(' ', Encoding.UTF8.GetString(response.Body).Split((char[])['\r', '\n', '\t'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + return text.Length <= 300 ? text : text[..300] + " …"; + } +} diff --git a/src/TermRest.Core/Auth/OAuth2Tokens.cs b/src/TermRest.Core/Auth/OAuth2Tokens.cs new file mode 100644 index 0000000..d40b4a9 --- /dev/null +++ b/src/TermRest.Core/Auth/OAuth2Tokens.cs @@ -0,0 +1,556 @@ +using System.Buffers.Text; +using System.Security.Cryptography; +using System.Text; +using TermRest.Core.Http; + +namespace TermRest.Core.Auth; + +/// What OAuth 2.0 token requests go out with: who sends them, the request a token is for, and how the user signs in. +public sealed class OAuth2Context +{ + public required HttpExecutor Executor { get; init; } + + /// + /// The request the token is for: token requests trust its CA bundle and go with the client certificate it selects for + /// their URL (mutual TLS), and their warnings go to it. + /// + public required PreparedRequest Request { get; init; } + + /// The settings requests go with (SSL verification, proxy, timeout …): token requests go with them too. + public required ExecutionDefaults Defaults { get; init; } + + public IOAuth2Interaction? Interaction { get; init; } +} + +/// +/// Fetches OAuth 2.0 access tokens (client credentials, password, and authorization code with or without PKCE, which +/// has the user sign in with a browser), and keeps them in memory, never in a file, until they expire; then they are +/// refreshed with their refresh token if they came with one. The client authenticates with its secret (Basic or in the +/// form) or a client assertion its certificate signs (). Token requests carry the client's +/// credentials: they are neither recorded (history, recordings) nor redirected. +/// +public sealed class OAuth2Tokens +{ + /// How long a token request may take when no timeout is set for requests. + public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(60); + + private readonly Dictionary _entries = new(StringComparer.Ordinal); + private readonly Lock _gate = new(); + + public TimeProvider Time { get; set; } = TimeProvider.System; + + /// How long a sign-in may take until the browser returns to the loopback redirect URI. + public TimeSpan SignInTimeout { get; set; } = TimeSpan.FromMinutes(5); + + /// The token cached for , fresh or not; null when none was fetched (or it was forgotten). + public OAuth2Token? Find(OAuth2Settings settings) + { + lock (_gate) + { + return _entries.GetValueOrDefault(settings.CacheKey)?.Token; + } + } + + /// The token cached for while it is fresh (see ); null otherwise. + public OAuth2Token? Peek(OAuth2Settings settings) => Find(settings) is { } token && token.IsFresh(Time.GetUtcNow()) ? token : null; + + /// Forgets the token cached for : the next request fetches a new one. False when there was none. + public bool Forget(OAuth2Settings settings) + { + lock (_gate) + { + if (_entries.GetValueOrDefault(settings.CacheKey) is not { Token: not null } entry) + { + return false; + } + + entry.Token = null; + return true; + } + } + + /// + /// The token for : the cached one while it is fresh, else one refreshed with its refresh token + /// or else a new one (: a new one in any case). Requests for the same settings wait for each + /// other, so that they share the token. Throws when none can be had, and + /// when cancelled. + /// + public async Task GetAsync(OAuth2Settings settings, OAuth2Context context, bool fetchNew = false, CancellationToken cancellationToken = default) + { + Entry entry; + lock (_gate) + { + if (!_entries.TryGetValue(settings.CacheKey, out var existing)) + { + _entries[settings.CacheKey] = existing = new Entry(); + } + + entry = existing; + } + + await entry.Turn.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var cached = Find(settings); + if (!fetchNew && cached is not null && cached.IsFresh(Time.GetUtcNow())) + { + return new OAuth2Result(cached, OAuth2TokenOrigin.Cached, Display(settings.AccessTokenUrl)); + } + + if (!fetchNew && cached?.RefreshToken is { Length: > 0 } refreshToken) + { + try + { + var refreshed = await RefreshAsync(settings, refreshToken, context, cancellationToken).ConfigureAwait(false); + Keep(entry, refreshed.Token); + return refreshed; + } + catch (OAuth2Exception ex) + { + // Expired or revoked: signing in again, or asking for a new token, is what's left. + context.Request.Warnings.Add($"{ex.Message} A new token was asked for instead."); + Keep(entry, null); + } + } + + try + { + var fetched = await FetchAsync(settings, context, cancellationToken).ConfigureAwait(false); + Keep(entry, fetched.Token); + return fetched; + } + catch (OAuth2Exception) + { + if (cached is not null && !cached.IsFresh(Time.GetUtcNow())) + { + Keep(entry, null); + } + + throw; + } + } + finally + { + entry.Turn.Release(); + } + } + + /// + /// Adds the token of to as its + /// settings say (the Authorization header, or the access_token query parameter), as the auth helpers add theirs, + /// and says where it came from in its auth description. The token is one of its secrets. + /// + public void Apply(PreparedRequest request, OAuth2Result result) + { + var settings = request.OAuth2 ?? throw new InvalidOperationException("The request fetches no OAuth 2.0 token."); + var token = result.Token.AccessToken; + request.OAuth2Token = result; + request.AddSecretValues([token]); + request.AuthDescription = result.Describe(settings, Time.GetUtcNow()); + if (token.AsSpan().IndexOfAny('\r', '\n', '\0') >= 0) + { + request.Errors.Add("OAuth 2.0: the access token has a line break or NUL character, so it can't be sent."); + return; + } + + if (settings.AddToQuery) + { + // As the preparer adds an auth helper's parameter: it replaces one of the same name, encoded, at the end. + var url = request.Url; + var start = url.IndexOf('?', StringComparison.Ordinal); + var pairs = start < 0 || start == url.Length - 1 ? [] : url[(start + 1)..].Split('&').ToList(); + if (pairs.RemoveAll(pair => (pair.IndexOf('=', StringComparison.Ordinal) is var equals and >= 0 ? pair[..equals] : pair) == "access_token") > 0) + { + request.Warnings.Add("The auth helper replaced the 'access_token' query parameter."); + } + + var encoded = Uri.EscapeDataString(token); + request.AddSecretValues([encoded]); + pairs.Add("access_token=" + encoded); + request.Url = (start < 0 ? url : url[..start]) + "?" + string.Join('&', pairs); + if (Uri.TryCreate(request.Url, UriKind.Absolute, out var uri)) + { + request.Uri = uri; + } + + return; + } + + if (request.Headers.RemoveAll(h => string.Equals(h.Key, "Authorization", StringComparison.OrdinalIgnoreCase)) > 0) + { + request.Warnings.Add("The auth helper replaced the 'Authorization' header."); + } + + request.Headers.Add(new("Authorization", settings.HeaderPrefix.Length == 0 ? token : $"{settings.HeaderPrefix} {token}")); + request.AuthHeaderNames.Add("Authorization"); + } + + /// A URL as messages and the timeline show it: without its query (which can hold a key) and user info. + public static string Display(string url) => Uri.TryCreate(url, UriKind.Absolute, out var uri) ? Display(uri) : url; + + /// + public static string Display(Uri uri) => $"{uri.Scheme}://{uri.Authority}{uri.AbsolutePath}"; + + /// + /// The code in an authorization response: the URL the browser returned to (as pasted from its address bar), or its + /// query alone; servers may put it in the fragment too. Throws for an error response, one + /// without a code, and one whose state is not (not the response to this sign-in: forged). + /// + internal static string ReadAuthorizationResponse(string response, string state) + { + response = response.Trim(); + var hash = response.IndexOf('#', StringComparison.Ordinal); + var query = response.IndexOf('?', StringComparison.Ordinal); + var end = hash < 0 ? response.Length : hash; + var queryText = query >= 0 && query < end ? response[(query + 1)..end] + : query < 0 && hash < 0 && !response.Contains("://", StringComparison.Ordinal) ? response + : ""; + var fields = OAuth2Response.ParseForm(queryText); + if (hash >= 0) + { + foreach (var (key, value) in OAuth2Response.ParseForm(response[(hash + 1)..])) + { + fields.TryAdd(key, value); + } + } + + if (fields.GetValueOrDefault("error") is { Length: > 0 } error) + { + var description = fields.GetValueOrDefault("error_description"); + throw new OAuth2Exception($"OAuth 2.0: the authorization server did not sign you in: {error}{(string.IsNullOrEmpty(description) ? "" : ": " + description)}"); + } + + if (fields.GetValueOrDefault("state") != state) + { + throw new OAuth2Exception("OAuth 2.0: the authorization response is not the one to this sign-in (its state differs), so no token was asked for."); + } + + return fields.GetValueOrDefault("code") is { Length: > 0 } code + ? code + : throw new OAuth2Exception("OAuth 2.0: the authorization response has no code."); + } + + private void Keep(Entry entry, OAuth2Token? token) + { + lock (_gate) + { + entry.Token = token; + } + } + + private async Task FetchAsync(OAuth2Settings settings, OAuth2Context context, CancellationToken cancellationToken) + { + var form = new List>(); + switch (settings.Grant) + { + case OAuth2Grant.ClientCredentials: + form.Add(new("grant_type", "client_credentials")); + AddScope(form, settings); + break; + case OAuth2Grant.Password: + form.Add(new("grant_type", "password")); + form.Add(new("username", settings.Username)); + form.Add(new("password", settings.Password)); + AddScope(form, settings); + break; + case OAuth2Grant.AuthorizationCode or OAuth2Grant.AuthorizationCodeWithPkce: + { + var (code, redirectUri, verifier) = await SignInAsync(settings, context, cancellationToken).ConfigureAwait(false); + form.Add(new("grant_type", "authorization_code")); + form.Add(new("code", code)); + form.Add(new("redirect_uri", redirectUri)); + if (verifier is not null) + { + form.Add(new("code_verifier", verifier)); + } + + break; + } + + default: + throw new OAuth2Exception($"OAuth 2.0: TermRest does not fetch tokens for the {settings.GrantName} grant."); + } + + return await RequestTokenAsync(settings, settings.AccessTokenUrl, form, settings.TokenRequestParams, null, context, cancellationToken).ConfigureAwait(false); + } + + /// Redeems a refresh token (RFC 6749, section 6) for the same scope. + private Task RefreshAsync(OAuth2Settings settings, string refreshToken, OAuth2Context context, CancellationToken cancellationToken) + { + var form = new List> { new("grant_type", "refresh_token"), new("refresh_token", refreshToken) }; + AddScope(form, settings); + var url = settings.RefreshTokenUrl.Length > 0 ? settings.RefreshTokenUrl : settings.AccessTokenUrl; + return RequestTokenAsync(settings, url, form, settings.RefreshRequestParams, refreshToken, context, cancellationToken); + } + + private static void AddScope(List> form, OAuth2Settings settings) + { + if (settings.Scope.Length > 0) + { + form.Add(new("scope", settings.Scope)); + } + } + + /// + /// Has the user sign in for an authorization code (RFC 6749, section 4.1; with PKCE, RFC 7636): the browser opens the + /// authorization request, and returns to the redirect URI, where TermRest listens when it is a loopback address. + /// + private async Task<(string Code, string RedirectUri, string? Verifier)> SignInAsync(OAuth2Settings settings, OAuth2Context context, CancellationToken cancellationToken) + { + if (context.Interaction is not { } interaction) + { + throw new OAuth2Exception($"OAuth 2.0: the {settings.GrantName} grant has you sign in with a browser, which TermRest can't do here."); + } + + var state = settings.State.Length > 0 ? settings.State : RandomValue(16); + string? verifier = null; + string? challenge = null; + if (settings.Grant == OAuth2Grant.AuthorizationCodeWithPkce) + { + verifier = settings.CodeVerifier.Length > 0 ? settings.CodeVerifier : RandomValue(32); + challenge = settings.ChallengeMethod == "plain" ? verifier : Base64Url.EncodeToString(SHA256.HashData(Encoding.ASCII.GetBytes(verifier))); + } + + using var loopback = LoopbackRedirect.Start(settings.RedirectUri); + var redirectUri = loopback?.RedirectUri ?? settings.RedirectUri; + var url = AuthorizationUrl(settings, redirectUri, state, challenge); + using var waiting = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + waiting.CancelAfter(SignInTimeout); + var redirect = loopback?.ReceiveAsync(waiting.Token); + string? response; + try + { + response = await interaction.SignInAsync(new OAuth2SignIn { AuthorizationUrl = url, RedirectUri = redirectUri, Redirect = redirect }, cancellationToken) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested && waiting.IsCancellationRequested) + { + var timeout = SignInTimeout.TotalMinutes >= 1 ? $"{SignInTimeout.TotalMinutes:0.#} minutes" : $"{SignInTimeout.TotalSeconds:0.#} seconds"; + throw new OAuth2Exception($"OAuth 2.0: the browser did not return to {redirectUri} within {timeout}, so no token was asked for."); + } + finally + { + // A URL pasted instead: the listener stops. + if (redirect is not null) + { + await waiting.CancelAsync().ConfigureAwait(false); + try + { + await redirect.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + } + } + + if (response is null) + { + throw new OAuth2Exception("OAuth 2.0: signing in was cancelled, so no token was asked for."); + } + + return (ReadAuthorizationResponse(response, state), redirectUri, verifier); + } + + /// The authorization request (RFC 6749, section 4.1.1): the auth URL with the request in its query. + private static Uri AuthorizationUrl(OAuth2Settings settings, string redirectUri, string state, string? challenge) + { + var parameters = new List> { new("response_type", "code"), new("client_id", settings.ClientId), new("redirect_uri", redirectUri) }; + AddScope(parameters, settings); + parameters.Add(new("state", state)); + if (challenge is not null) + { + parameters.Add(new("code_challenge", challenge)); + parameters.Add(new("code_challenge_method", settings.ChallengeMethod)); + } + + // An authorization request has only the URL to carry them. + Override(parameters, settings.AuthRequestParams); + var text = WithQuery(settings.AuthUrl, parameters); + return Uri.TryCreate(text, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp) + ? uri + : throw new OAuth2Exception($"OAuth 2.0: the auth URL '{settings.AuthUrl}' is not an http(s) URL."); + } + + /// Sends a token request (RFC 6749, section 3.2) and reads the token it returns. + /// The refresh token redeemed (kept when the response has no new one); null for a new token. + private async Task RequestTokenAsync(OAuth2Settings settings, string url, List> form, IReadOnlyList extra, + string? refreshToken, OAuth2Context context, CancellationToken cancellationToken) + { + var headers = new List>(); + AddClientAuthentication(settings, url, form, headers); + + // As in Postman: the extra parameters replace the request's own of the same name. + Override(form, extra.Where(p => p.Target == OAuth2ParameterTarget.Body)); + var extraHeaders = extra.Where(p => p.Target == OAuth2ParameterTarget.Header).ToList(); + headers.RemoveAll(h => extraHeaders.Any(p => string.Equals(p.Key, h.Key, StringComparison.OrdinalIgnoreCase))); + headers.AddRange(extraHeaders.Select(p => new KeyValuePair(p.Key, p.Value))); + var query = extra.Where(p => p.Target == OAuth2ParameterTarget.Url).Select(p => new KeyValuePair(p.Key, p.Value)).ToList(); + + var request = BuildRequest(WithQuery(url, query), headers, form, context); + var endpoint = Display(request.Uri!); + context.Interaction?.RequestingToken(endpoint); + var exchange = await context.Executor.SendAsync(request, cancellationToken).ConfigureAwait(false); + foreach (var warning in request.Warnings) + { + context.Request.Warnings.Add($"OAuth 2.0 token request: {warning}"); + } + + if (exchange.Cancelled) + { + throw new OperationCanceledException(cancellationToken); + } + + if (exchange.Response is not { } response) + { + throw new OAuth2Exception($"OAuth 2.0: the token request to {endpoint} failed: {exchange.ErrorMessage}"); + } + + var status = $"{response.StatusCode} {response.ReasonPhrase}".TrimEnd(); + if (response.StatusCode is >= 300 and < 400) + { + var location = response.GetHeader("Location") is { Length: > 0 } target ? $" (to {Display(target)})" : ""; + throw new OAuth2Exception($"OAuth 2.0: the token endpoint {endpoint} answered {status}{location}: token requests, which carry the client's credentials, are not redirected."); + } + + var fields = OAuth2Response.ReadFields(response.Body); + if (response.StatusCode < 300 && fields is not null && OAuth2Token.From(fields, Time.GetUtcNow(), refreshToken) is { } token) + { + return new OAuth2Result(token, refreshToken is null ? OAuth2TokenOrigin.Fetched : OAuth2TokenOrigin.Refreshed, endpoint, + $"{response.StatusCode} in {HttpExchange.Format(exchange.Timing.Total)}"); + } + + var reason = OAuth2Response.DescribeError(response, fields); + throw new OAuth2Exception(response.StatusCode < 300 + ? $"OAuth 2.0: the token endpoint {endpoint} answered {status} without an access token{(reason.Length > 0 ? ": " + reason : ".")}" + : $"OAuth 2.0: the token request to {endpoint} failed: {status}{(reason.Length > 0 ? " — " + reason : "")}"); + } + + /// + /// How the client authenticates (RFC 6749, section 2.3): a client assertion its certificate signs, its secret in the form, + /// or (by default) HTTP Basic with its ID and secret, as Postman and curl send them. A client without a secret (a public + /// one, as with PKCE) names itself in the form instead: some servers refuse Basic with an empty password. + /// + private void AddClientAuthentication(OAuth2Settings settings, string url, List> form, List> headers) + { + switch (settings.ClientAuthentication) + { + case OAuth2ClientAuthentication.PrivateKeyJwt: + if (settings.SigningCertificate is not { } certificate) + { + throw new OAuth2Exception($"OAuth 2.0: certificate '{settings.AssertionCertificate}', which signs the client assertion, is not loaded."); + } + + if (settings.ClientId.Length == 0) + { + throw new OAuth2Exception("OAuth 2.0: a client assertion names the client: enter its client ID."); + } + + form.Add(new("client_id", settings.ClientId)); + form.Add(new("client_assertion_type", ClientAssertion.AssertionType)); + form.Add(new("client_assertion", ClientAssertion.Create(certificate, settings.AssertionCertificate, settings.ClientId, + settings.AssertionAudience.Length > 0 ? settings.AssertionAudience : url, settings.AssertionAlgorithm, settings.AssertionKeyId, + settings.AssertionChain, Time.GetUtcNow()))); + break; + case OAuth2ClientAuthentication.Body: + if (settings.ClientId.Length > 0) + { + form.Add(new("client_id", settings.ClientId)); + } + + if (settings.ClientSecret.Length > 0) + { + form.Add(new("client_secret", settings.ClientSecret)); + } + + break; + default: + if (settings.ClientSecret.Length > 0) + { + headers.Add(new("Authorization", "Basic " + AuthApplier.BasicToken(settings.ClientId, settings.ClientSecret))); + } + else if (settings.ClientId.Length > 0) + { + form.Add(new("client_id", settings.ClientId)); + } + + break; + } + } + + /// + /// A token request: a form POSTed with the settings requests go with (SSL verification, proxy, CA bundle), and the + /// client certificate the request the token is for selects for its URL. No cookies go with it or come from it. + /// + private static PreparedRequest BuildRequest(string url, List> headers, List> form, OAuth2Context context) + { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp)) + { + throw new OAuth2Exception($"OAuth 2.0: the token URL '{Display(url)}' is not an http(s) URL."); + } + + if (headers.Any(h => h.Key.Length == 0 || $"{h.Key}{h.Value}".AsSpan().IndexOfAny('\r', '\n', '\0') >= 0)) + { + throw new OAuth2Exception("OAuth 2.0: a header of the token request is empty or has a line break or NUL character."); + } + + var defaults = context.Defaults; + var request = new PreparedRequest + { + Method = "POST", + Url = url, + Uri = uri, + Body = new PreparedBody { Kind = PreparedBodyKind.FormUrlEncoded, Fields = form, ContentType = "application/x-www-form-urlencoded" }, + AuthDescription = "OAuth 2.0 client", + StrictSsl = defaults.StrictSsl, + ExtraTrustedCertificates = context.Request.ExtraTrustedCertificates, + FollowRedirects = false, + UseCookies = false, + Timeout = defaults.Timeout ?? DefaultTimeout, + Proxy = defaults.Proxy, + HttpVersion = defaults.HttpVersion, + MaxResponseBytes = Math.Min(defaults.MaxResponseBytes, 1024 * 1024), + }; + request.Headers.Add(new("Accept", "application/json")); + request.Headers.AddRange(headers); + if (uri.Scheme == Uri.UriSchemeHttps) + { + request.ClientCertificate = context.Request.ClientCertificateSelector?.Invoke(uri); + } + + return request; + } + + /// Removes the parameters of the names has, and adds its own (all of them: a name may come more than once). + private static void Override(List> parameters, IEnumerable extra) + { + var added = extra.ToList(); + parameters.RemoveAll(p => added.Any(e => e.Key == p.Key)); + parameters.AddRange(added.Select(e => new KeyValuePair(e.Key, e.Value))); + } + + /// with added to its query (before its fragment). + private static string WithQuery(string url, List> parameters) + { + if (parameters.Count == 0) + { + return url; + } + + var hash = url.IndexOf('#', StringComparison.Ordinal); + var (head, fragment) = hash < 0 ? (url, "") : (url[..hash], url[hash..]); + var separator = !head.Contains('?', StringComparison.Ordinal) ? "?" : head.EndsWith('?') || head.EndsWith('&') ? "" : "&"; + return head + separator + string.Join('&', parameters.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}")) + fragment; + } + + /// A random value for a state or code verifier: base64url, which RFC 7636 allows in a verifier. + private static string RandomValue(int bytes) => Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(bytes)); + + private sealed class Entry + { + /// One request at a time fetches or refreshes the token; those that wait take it then. + public SemaphoreSlim Turn { get; } = new(1, 1); + + public OAuth2Token? Token { get; set; } + } +} diff --git a/src/TermRest.Core/Auth/SystemBrowser.cs b/src/TermRest.Core/Auth/SystemBrowser.cs new file mode 100644 index 0000000..0992a9a --- /dev/null +++ b/src/TermRest.Core/Auth/SystemBrowser.cs @@ -0,0 +1,87 @@ +using System.ComponentModel; +using System.Diagnostics; + +namespace TermRest.Core.Auth; + +/// Opens a URL in the user's default browser. +public static class SystemBrowser +{ + /// + /// Opens (an http or https URL only) in the default browser: through the shell on Windows, with + /// open on macOS, and elsewhere with the commands in BROWSER, xdg-open, or on WSL wslview + /// or Windows' explorer.exe. False when none could: the user then opens it (there is no browser over SSH). + /// What the commands write goes nowhere, so that it doesn't land in the full-screen UI. + /// + public static bool TryOpen(Uri url) + { + if (!url.IsAbsoluteUri || (url.Scheme != Uri.UriSchemeHttp && url.Scheme != Uri.UriSchemeHttps)) + { + return false; + } + + var text = url.AbsoluteUri; + if (OperatingSystem.IsWindows()) + { + return Start(new ProcessStartInfo(text) { UseShellExecute = true }, wait: false); + } + + // The URL is the script's argument ($1), never part of the script. + var commands = new List<(string Script, bool AnyExitCode)>(); + if (OperatingSystem.IsMacOS()) + { + commands.Add(("open \"$1\"", false)); + } + else + { + foreach (var browser in (Environment.GetEnvironmentVariable("BROWSER") ?? "").Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + commands.Add((browser.Contains("%s", StringComparison.Ordinal) ? browser.Replace("%s", "\"$1\"", StringComparison.Ordinal) : $"{browser} \"$1\"", false)); + } + + commands.Add(("xdg-open \"$1\"", false)); + if (Environment.GetEnvironmentVariable("WSL_DISTRO_NAME") is not null) + { + commands.Add(("wslview \"$1\"", false)); + commands.Add(("explorer.exe \"$1\"", true)); // which exits with 1 when it opened it + } + } + + foreach (var (script, anyExitCode) in commands) + { + var start = new ProcessStartInfo("/bin/sh") { UseShellExecute = false }; + foreach (var argument in (string[])["-c", $"{script} /dev/null 2>&1", "sh", text]) + { + start.ArgumentList.Add(argument); + } + + if (Start(start, wait: true, anyExitCode)) + { + return true; + } + } + + return false; + } + + /// + /// Wait a little for it to exit, and take an exit code other than 0 as a failure (not found, no browser); one still + /// running then is opening the browser (some xdg-opens wait for the browser to close). + /// + private static bool Start(ProcessStartInfo start, bool wait, bool anyExitCode = false) + { + try + { + using var process = Process.Start(start); + if (process is null) + { + return !wait; // the shell opened it in a running browser + } + + return !wait || !process.WaitForExit(TimeSpan.FromSeconds(3)) || anyExitCode || process.ExitCode == 0; + } + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or PlatformNotSupportedException) + { + return false; + } + } +} diff --git a/src/TermRest.Core/Http/PreparedRequest.cs b/src/TermRest.Core/Http/PreparedRequest.cs index b4ccc65..2a1c06c 100644 --- a/src/TermRest.Core/Http/PreparedRequest.cs +++ b/src/TermRest.Core/Http/PreparedRequest.cs @@ -275,6 +275,15 @@ public sealed class PreparedRequest /// public Model.AuthSpec? AuthUsed { get; set; } + /// + /// OAuth 2.0 settings the access token is fetched with before the request is sent (see + /// ); null when its auth needs no token fetched. + /// + public Auth.OAuth2Settings? OAuth2 { get; set; } + + /// The token added for (see ); null until it is. + public Auth.OAuth2Result? OAuth2Token { get; set; } + public ClientCertificateSelection? ClientCertificate { get; set; } /// diff --git a/src/TermRest.Core/Http/RequestPreparer.cs b/src/TermRest.Core/Http/RequestPreparer.cs index df30ec6..b85997f 100644 --- a/src/TermRest.Core/Http/RequestPreparer.cs +++ b/src/TermRest.Core/Http/RequestPreparer.cs @@ -88,8 +88,14 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st prepared.AuthDescription = auth.Description; prepared.Credential = auth.Credential; prepared.CredentialSchemes = auth.CredentialSchemes; + prepared.OAuth2 = auth.OAuth2; prepared.Warnings.AddRange(auth.Warnings); prepared.AddSecretValues(auth.Secrets); + if (auth.OAuth2 is { ClientAuthentication: OAuth2ClientAuthentication.PrivateKeyJwt } oauth) + { + LoadSigningCertificate(oauth, prepared); + } + foreach (var (key, value) in auth.QueryParameters) { // As in Postman, the helper's parameter replaces one of the same name and is encoded: a & would otherwise end the @@ -144,9 +150,9 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st } // Credentials in the URL (https://user:password@host) go as Basic auth, as curl and Postman send them: .NET would - // leave them out. An Authorization header or an auth helper takes precedence. + // leave them out. An Authorization header or an auth helper takes precedence (an OAuth 2.0 token fetched later too). if (prepared.Uri is { UserInfo.Length: > 0 } withCredentials && prepared.GetHeader("Authorization") is null - && auth.Headers.Count == 0 && auth.QueryParameters.Count == 0 && auth.Credential is null) + && auth.Headers.Count == 0 && auth.QueryParameters.Count == 0 && auth.Credential is null && auth.OAuth2 is null) { AddUrlCredentials(prepared, withCredentials.UserInfo); } @@ -268,6 +274,43 @@ private static string WithScheme(string url) return Variables.Resolve(value); } + /// + /// Loads the certificate that signs an OAuth 2.0 client assertion: the entry of the workspace's certificate registry of + /// that name (it need match no URL). One that can't be loaded is an error: the request is not sent. + /// + private void LoadSigningCertificate(OAuth2Settings settings, PreparedRequest prepared) + { + var name = settings.AssertionCertificate; + if (name.Length == 0) + { + prepared.Errors.Add("OAuth 2.0: choose the certificate that signs the client assertion (private_key_jwt)."); + return; + } + + var named = certificates?.Registry.Entries.Where(e => string.Equals(e.Name, name, StringComparison.OrdinalIgnoreCase)).ToList() ?? []; + if (named.FirstOrDefault(e => !e.Disabled) is not { } entry) + { + prepared.Errors.Add(named.Count > 0 + ? $"OAuth 2.0: certificate '{name}', which signs the client assertion, is turned off in the workspace's client certificates." + : $"OAuth 2.0: the workspace has no client certificate named '{name}' to sign the client assertion with (Tools › Client certificates…)."); + return; + } + + try + { + var loaded = certificates!.Load(entry, certificates.Registry.BaseDirectory, ResolveSecret, defaults.FilesFolder); + settings.SigningCertificate = loaded; + if (loaded.Summary is { IsExpired: true } summary) + { + prepared.Warnings.Add($"Certificate '{entry.Name}', which signs the client assertion, expired on {summary.NotAfter:yyyy-MM-dd}."); + } + } + catch (CertificateLoadException ex) + { + prepared.Errors.Add($"OAuth 2.0: certificate '{entry.Name}', which signs the client assertion, could not be loaded: {ex.Message}"); + } + } + private System.Security.Cryptography.X509Certificates.X509Certificate2Collection? LoadTrust(List warnings) { if (string.IsNullOrWhiteSpace(defaults.CaBundlePath)) diff --git a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs index 10795fb..ed8daab 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs @@ -211,6 +211,7 @@ public async Task SendAsync(PostmanCollection collection, RequestN if (plan.IsEmpty && plan.Error is null && plan.Notes.Count == 0) { var request = Prepare(environment, collection, node, spec, spec, null); + await AuthorizeAsync(request, cancellationToken).ConfigureAwait(true); prepared?.Invoke(request); return await SendAsync(environment, request, cancellationToken).ConfigureAwait(true); } @@ -257,6 +258,7 @@ public async Task SendAsync(PostmanCollection collection, RequestN } var ready = Prepare(environment, collection, node, working, source, local); + await AuthorizeAsync(ready, cancellationToken).ConfigureAwait(true); prepared?.Invoke(ready); var exchange = await Executor.SendAsync(ready, cancellationToken).ConfigureAwait(true); exchange.Scripts = results; diff --git a/src/TermRest.Core/Workspace/RequestRunner.cs b/src/TermRest.Core/Workspace/RequestRunner.cs index 04af991..2b25498 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.cs @@ -1,3 +1,4 @@ +using TermRest.Core.Auth; using TermRest.Core.Certificates; using TermRest.Core.History; using TermRest.Core.Http; @@ -77,6 +78,12 @@ public RequestRunner(ApiWorkspace workspace) /// While set, every sent request is also recorded into a HAR file (see ). public RequestRecorder? Recorder { get; set; } + /// The OAuth 2.0 tokens requests fetched, kept (in memory only) for the session. + public OAuth2Tokens OAuth2Tokens { get; } = new(); + + /// How the user signs in for an OAuth 2.0 authorization code; null: such tokens are not fetched. + public IOAuth2Interaction? OAuth2Interaction { get; set; } + /// Largest response body kept with a history entry. public int HistoryMaxBodyBytes { get; set; } = 256 * 1024; @@ -208,12 +215,71 @@ public Task SendAsync(PreparedRequest prepared, CancellationToken private async Task SendAsync(PostmanEnvironment? environment, PreparedRequest prepared, CancellationToken cancellationToken) { // No ConfigureAwait(false): UI callers resume on their own thread, which also records the entry. + await AuthorizeAsync(prepared, cancellationToken).ConfigureAwait(true); var exchange = await Executor.SendAsync(prepared, cancellationToken).ConfigureAwait(true); Record(exchange, environment?.Name); Recorder?.Record(exchange, environment?.Name); return exchange; } + /// + /// The OAuth 2.0 token for a prepared request whose auth fetches one (see ): the one + /// fetched earlier while it is fresh, else one refreshed or fetched now (: a new one in any + /// case). Throws when none can be had. + /// + public Task GetTokenAsync(PreparedRequest request, bool fetchNew = false, CancellationToken cancellationToken = default) => + OAuth2Tokens.GetAsync( + request.OAuth2 ?? throw new ArgumentException("The request fetches no OAuth 2.0 token.", nameof(request)), + new OAuth2Context { Executor = Executor, Request = request, Defaults = CreateDefaults(), Interaction = OAuth2Interaction }, + fetchNew, + cancellationToken); + + /// + /// Adds to a prepared request whose auth fetches an OAuth 2.0 token the one fetched earlier, while it is fresh, without + /// fetching one (a cURL command sends nothing). False when there is none: a warning says the request lacks it. + /// + public bool AddCachedToken(PreparedRequest request) + { + if (request.OAuth2 is not { } settings || request.OAuth2Token is not null) + { + return request.OAuth2Token is not null; + } + + if (OAuth2Tokens.Peek(settings) is not { } token) + { + request.Warnings.Add($"OAuth 2.0: no token was fetched yet, so the command has no access token: TermRest fetches one from " + + $"{OAuth2Tokens.Display(settings.AccessTokenUrl)} when it sends the request."); + return false; + } + + OAuth2Tokens.Apply(request, new OAuth2Result(token, OAuth2TokenOrigin.Cached, OAuth2Tokens.Display(settings.AccessTokenUrl))); + return true; + } + + /// + /// Adds the OAuth 2.0 token a prepared request needs, fetching it if it must (see ): one that + /// can't be had is an error of the request, which is not sent then. Cancelled, it adds nothing: the request is cancelled. + /// + private async Task AuthorizeAsync(PreparedRequest request, CancellationToken cancellationToken) + { + if (request.OAuth2 is null || request.OAuth2Token is not null || request.Errors.Count > 0) + { + return; + } + + try + { + OAuth2Tokens.Apply(request, await GetTokenAsync(request, cancellationToken: cancellationToken).ConfigureAwait(true)); + } + catch (OAuth2Exception ex) + { + request.Errors.Add(ex.Message); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + } + public Task SendAsync(PostmanCollection collection, RequestNode? node, HttpRequestSpec spec, CancellationToken cancellationToken = default) => SendAsync(collection, node, spec, null, cancellationToken); diff --git a/src/TermRest.Tui/Dialogs/CertificatesDialog.cs b/src/TermRest.Tui/Dialogs/CertificatesDialog.cs index b93509b..60e7d7c 100644 --- a/src/TermRest.Tui/Dialogs/CertificatesDialog.cs +++ b/src/TermRest.Tui/Dialogs/CertificatesDialog.cs @@ -229,6 +229,8 @@ internal static class CertificateEntryDialog var matches = Ui.AddRow(dialog, "URL patterns", new TextField { Text = entry.Matches.Count > 0 ? string.Join(", ", entry.Matches) : suggestion }, y); y += 1; dialog.Add(new Label { Text = "Comma separated, e.g. https://*.contoso.com/*, https://api.contoso.com:8443/*", X = 20, Y = y }); + y += 1; + dialog.Add(Ui.Hint("None: it goes to no server, and can sign OAuth 2.0 client assertions (as any can).", 20, y)); y += 2; var kind = Ui.AddRow(dialog, "Source", new OptionSelector @@ -320,11 +322,7 @@ internal static class CertificateEntryDialog return "Enter a name."; } - if (entry.Matches.Count == 0) - { - return "Enter at least one URL pattern (for example https://api.contoso.com/*)."; - } - + // Without URL patterns it is sent to no server: it signs OAuth 2.0 client assertions. var invalid = entry.Matches.FirstOrDefault(m => !UrlMatchPattern.TryParse(m, out _)); if (invalid is not null) { diff --git a/src/TermRest.Tui/Dialogs/SignInDialog.cs b/src/TermRest.Tui/Dialogs/SignInDialog.cs new file mode 100644 index 0000000..adc4331 --- /dev/null +++ b/src/TermRest.Tui/Dialogs/SignInDialog.cs @@ -0,0 +1,146 @@ +using Terminal.Gui.App; +using Terminal.Gui.ViewBase; +using Terminal.Gui.Views; +using TermRest.Core.Auth; +using TermRest.Tui.Views; + +namespace TermRest.Tui.Dialogs; + +/// +/// Signing in for an OAuth 2.0 authorization code in the full-screen UI. The browser opens the sign-in page, and a dialog +/// waits for it to return to TermRest's loopback redirect URI, closing by itself when it does. It also takes the address +/// the browser ended on, pasted: for a redirect URI elsewhere, or a browser on another machine (as over SSH). +/// +/// The UI the dialog shows in; null once it is closed. +/// Says that a token is being fetched (called on the UI thread). +/// Opens the sign-in page in a browser; false when it can't (default: ). +internal sealed class SignInDialog(Func app, Action status, Func? openBrowser = null) : IOAuth2Interaction +{ + private readonly Func _openBrowser = openBrowser ?? SystemBrowser.TryOpen; + + public Task SignInAsync(OAuth2SignIn signIn, CancellationToken cancellationToken) + { + if (app() is not { } ui) + { + return Task.FromResult(null); + } + + // Shown from the main loop, whichever thread asks: the token is fetched off it. + var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + ui.AddTimeout(TimeSpan.Zero, () => + { + try + { + Show(ui, signIn, result, cancellationToken); + } + catch (Exception ex) + { + result.TrySetException(ex); + } + + return false; + }); + return result.Task; + } + + public void RequestingToken(string endpoint) => app()?.AddTimeout(TimeSpan.Zero, () => + { + status($"Fetching an OAuth 2.0 token from {endpoint} …"); + return false; + }); + + private void Show(IApplication app, OAuth2SignIn signIn, TaskCompletionSource result, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + result.TrySetCanceled(cancellationToken); + return; + } + + var url = signIn.AuthorizationUrl.AbsoluteUri; + var host = signIn.AuthorizationUrl.Host; + var opened = _openBrowser(signIn.AuthorizationUrl); + using var dialog = new Dialog { Title = "Sign in (OAuth 2.0)", Width = Dim.Percent(85) }; + dialog.Add(Ui.Hint(opened ? $"Sign in to {host} in the browser that opened, or at this address:" : $"Open this address in a browser and sign in to {host}:", 1, 1)); + var address = new TextArea { X = 1, Y = 2, Width = Dim.Fill(1), Height = 3, ReadOnly = true, WordWrap = true }; + address.SetText(url); + var waiting = signIn.Redirect is not null; + var pasted = new TextField { X = 1, Y = 8, Width = Dim.Fill(1) }; + + // The field first: it has the focus (the address is there to be copied). + dialog.Add( + pasted, + address, + Ui.Hint(waiting ? $"Waiting for the browser to return to {signIn.RedirectUri} …" : $"Once you are signed in, the browser goes to {signIn.RedirectUri}.", 1, 6), + Ui.Hint(waiting ? "With a browser on another machine, paste the address it ends on:" : "Paste the address it ends on (its address bar), then OK:", 1, 7)); + var copy = new Button { Text = "Copy address" }; + Ui.OnPress(copy, () => Ui.CopyToClipboard(app, url)); + var open = new Button { Text = "Open browser" }; + Ui.OnPress(open, () => _openBrowser(signIn.AuthorizationUrl)); + dialog.AddButton(copy); + dialog.AddButton(open); + dialog.AddButton(new Button { Text = "Cancel" }); + dialog.AddButton(new Button { Text = "OK" }); + + // What ends the wait: the browser came back (or did not in time), or the request was cancelled. Checked from the main + // loop: Terminal.Gui runs timeouts (this dialog is shown from one) under a lock, so one added from another thread + // would wait for the dialog to close. + string? received = null; + Exception? failed = null; + var polling = app.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + if (signIn.Redirect is { IsCompleted: true } redirect) + { + if (redirect.IsCompletedSuccessfully) + { + received = redirect.Result; + } + else + { + failed = redirect.Exception?.InnerException ?? new OperationCanceledException(); + } + } + else if (!cancellationToken.IsCancellationRequested) + { + return true; + } + + dialog.RequestStop(); + return false; + }); + + pasted.SetFocus(); + try + { + // OK with nothing pasted goes on waiting. + do + { + app.Run(dialog); + } + while (received is null && failed is null && !cancellationToken.IsCancellationRequested && !dialog.Canceled && pasted.Text.Trim().Length == 0); + } + finally + { + if (polling is not null) + { + app.RemoveTimeout(polling); + } + } + if (received is not null) + { + result.TrySetResult(received); + } + else if (cancellationToken.IsCancellationRequested) + { + result.TrySetCanceled(cancellationToken); + } + else if (failed is not null) + { + result.TrySetException(failed); + } + else + { + result.TrySetResult(dialog.Canceled ? null : pasted.Text.Trim()); + } + } +} diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index 1c90221..77ec47c 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -4,6 +4,7 @@ using Terminal.Gui.Input; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; +using TermRest.Core.Auth; using TermRest.Core.History; using TermRest.Core.Http; using TermRest.Core.Import; @@ -113,6 +114,10 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) { DescribeCertificate = DescribeCertificate, DescribeInheritedAuth = DescribeInheritedAuth, + DescribeToken = DescribeToken, + + // Any registered certificate can sign an OAuth 2.0 client assertion, also one that matches no URL. + CertificateNames = () => [.. _workspace.Certificates.Entries.Select(e => e.Name).Where(n => n.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase)], // Where a relative body file is looked for when sending: the folder of the collection sending it. BaseDirectory = () => (_collection ?? _scratch)?.BaseDirectory ?? Environment.CurrentDirectory, @@ -195,10 +200,15 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) _history.DeleteRequested += (_, entry) => DeleteHistoryEntry(entry); _editor.Modified += (_, _) => UpdateTitles(); _editor.SendRequested += (_, _) => Send(); + _editor.GetTokenRequested += (_, _) => GetNewToken(); + _editor.ForgetTokenRequested += (_, _) => ForgetToken(); _editor.ManageCertificatesRequested += (_, _) => ShowCertificates(); _editor.CurlPasted += (_, command) => ImportCurl(command, intoCurrent: true); _response.Notice += (_, message) => Notify(message); + // The user signs in for an OAuth 2.0 authorization code in a dialog of this window, while it runs. + _runner.OAuth2Interaction = new SignInDialog(() => _closed ? null : App, ShowTokenProgress); + var first = workspace.Collections.SelectMany(c => c.AllRequests()).FirstOrDefault(); if (first is not null) { @@ -562,6 +572,7 @@ private async Task SendAsync() { _editor.SetSending(false); _response.ShowExchange(exchange); + _editor.RefreshTokenStatus(); // an OAuth 2.0 token may have been fetched for it } var recordedAs = recorder is not null && ReferenceEquals(recorder, _runner.Recorder) && recorder.Count > recordedBefore ? recorder.Count : (int?)null; @@ -1366,6 +1377,114 @@ static string Describe(AuthSpec auth) => auth.CredentialSets is { } sets return "No folder or collection auth is set, so no auth is sent."; } + /// What the Auth tab says of the OAuth 2.0 token of the request's auth, as it is now (its settings may have changed). + private string DescribeToken() + { + var prepared = _runner.Prepare(_collection ?? (_scratch ??= PostmanCollection.Create("Scratch")), SendContext, _editor.Spec); + if (prepared.OAuth2 is not { } settings) + { + return "None is fetched until the URLs are set."; + } + + if (prepared.Errors.FirstOrDefault(e => e.StartsWith("OAuth 2.0: ", StringComparison.Ordinal)) is { } problem) + { + return "⚠ " + problem["OAuth 2.0: ".Length..]; + } + + if (_runner.OAuth2Tokens.Find(settings) is not { } token) + { + return "None yet: fetched when sent."; + } + + var now = _runner.OAuth2Tokens.Time.GetUtcNow(); + var expiry = token.DescribeExpiry(now); + return token.IsFresh(now) ? $"Fetched {token.ObtainedAt.ToLocalTime():HH:mm:ss}, {expiry}." + : $"{char.ToUpperInvariant(expiry[0])}{expiry[1..]}: {(token.RefreshToken is null ? "a new one is fetched" : "refreshed")} when sent."; + } + + /// + /// The Auth tab's Get new token: fetches a token for the request's OAuth 2.0 settings now, signing in if they say so. + /// No exception may leave this async void method (see ). + /// + private async void GetNewToken() + { + try + { + var prepared = _runner.Prepare(_collection ?? (_scratch ??= PostmanCollection.Create("Scratch")), SendContext, _editor.Spec); + if (prepared.OAuth2 is not { } settings) + { + Ui.Error(App!, "Get new token", "No token can be fetched until the URLs are set: the token URL, and for an authorization code the auth URL."); + return; + } + + if (prepared.Errors.FirstOrDefault(e => e.StartsWith("OAuth 2.0: ", StringComparison.Ordinal)) is { } problem) + { + Ui.Error(App!, "Get new token", problem); + return; + } + + Notify($"Fetching an OAuth 2.0 token from {OAuth2Tokens.Display(settings.AccessTokenUrl)} …"); + OAuth2Result result; + try + { + result = await _runner.GetTokenAsync(prepared, fetchNew: true, _closing.Token); + } + catch (OAuth2Exception ex) + { + if (!_closed) + { + Notify(""); + Ui.Error(App!, "Get new token", ex.Message); + _editor.RefreshTokenStatus(); + } + + return; + } + catch (OperationCanceledException) + { + return; // the window closed + } + + if (!_closed) + { + Notify($"✓ New OAuth 2.0 token from {result.Endpoint} ({result.Exchange}), {result.Token.DescribeExpiry(_runner.OAuth2Tokens.Time.GetUtcNow())}"); + _editor.RefreshTokenStatus(); + } + } + catch (Exception ex) + { + TuiApp.ReportUnexpectedError(IsRunning ? App : null, ex); + } + } + + /// The Auth tab's Forget token: the next request fetches a new one. + private void ForgetToken() + { + var prepared = _runner.Prepare(_collection ?? (_scratch ??= PostmanCollection.Create("Scratch")), SendContext, _editor.Spec); + Notify(prepared.OAuth2 is { } settings && _runner.OAuth2Tokens.Forget(settings) + ? "OAuth 2.0 token forgotten: the next request fetches a new one." + : "No OAuth 2.0 token was fetched for these settings."); + _editor.RefreshTokenStatus(); + } + + /// Says that an OAuth 2.0 token is being fetched: where the response goes while a request waits for it, else in the status bar. + private void ShowTokenProgress(string text) + { + if (_closed) + { + return; + } + + if (_sending is not null) + { + _response.ShowProgress($"{text} (Esc or Send to cancel)"); + } + else + { + Notify(text); + } + } + private string EnvironmentLabel() => $"Env: {(_workspace.ActiveEnvironment is { } active ? _workspace.DisplayName(active) : "none")}"; // ----- workspace --------------------------------------------------------------------------- @@ -1534,6 +1653,8 @@ private void CopyAsCurl() string curl; try { + // Nothing is sent: an OAuth 2.0 token is the one fetched earlier, if there is one (a warning says so otherwise). + _runner.AddCachedToken(prepared); curl = CurlExporter.Export(prepared); } catch (NotSupportedException ex) diff --git a/src/TermRest.Tui/Views/AuthEditor.cs b/src/TermRest.Tui/Views/AuthEditor.cs index f36b6a7..9f786fe 100644 --- a/src/TermRest.Tui/Views/AuthEditor.cs +++ b/src/TermRest.Tui/Views/AuthEditor.cs @@ -1,6 +1,8 @@ +using System.Collections.ObjectModel; using Terminal.Gui.Input; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; +using TermRest.Core.Auth; using TermRest.Core.Model; using TermRest.Tui.Dialogs; @@ -9,6 +11,8 @@ namespace TermRest.Tui.Views; /// Auth tab: pick an auth type on the left, fill its fields on the right. internal sealed class AuthEditor : View { + private const int LabelWidth = 16; + private static readonly (string? Type, string Label)[] Choices = [ (null, "Inherit auth from parent"), @@ -18,16 +22,27 @@ private static readonly (string? Type, string Label)[] Choices = ("apikey", "API Key"), ("digest", "Digest Auth"), ("ntlm", "NTLM"), - ("oauth2", "OAuth 2.0 (access token)"), + ("oauth2", "OAuth 2.0"), ]; + /// How the OAuth 2.0 grants (, in that order) are shown. + private static readonly string[] GrantLabels = ["Authorization code", "Authorization code (PKCE)", "Client credentials", "Password credentials", "Implicit (not fetched)"]; + + private static readonly string[] AlgorithmLabels = ["For the key", .. ClientAssertion.Algorithms]; + private readonly ListView _types; - private readonly View _fields; + private readonly ScrollingForm _fields; private readonly Dictionary _byType = new(StringComparer.OrdinalIgnoreCase); - private readonly System.Collections.ObjectModel.ObservableCollection _labels = []; + private readonly ObservableCollection _labels = []; + + /// The controls of the settings shown, by key: the one in focus keeps it when the fields are built again. + private readonly Dictionary _controls = new(StringComparer.Ordinal); private AuthSpec? _auth; private string? _unsupportedType; private bool _loading; + private bool _statusPending; + private int _y; + private Label? _tokenStatus; public AuthEditor() { @@ -47,17 +62,32 @@ public AuthEditor() SelectType(index); } }; - _fields = new View { X = Pos.Right(_types) + 1, Y = 0, Width = Dim.Fill(), Height = Dim.Fill(), CanFocus = true }; + _fields = new ScrollingForm { X = Pos.Right(_types) + 1, Y = 0, Width = Dim.Fill(), Height = Dim.Fill() }; Add(_types, _fields); } public event EventHandler? Changed; + /// Get new token was pressed: an OAuth 2.0 token is fetched now (see ). + public event EventHandler? GetTokenRequested; + + /// Forget token was pressed: the OAuth 2.0 token fetched for the settings is forgotten. + public event EventHandler? ForgetTokenRequested; + /// Text describing what "inherit" resolves to (supplied by the main window). public Func? DescribeInherited { get; set; } + /// What the OAuth 2.0 token of the settings shown is: none yet, fetched, expired (supplied by the main window). + public Func? DescribeToken { get; set; } + + /// The names of the workspace's client certificates, which can sign OAuth 2.0 client assertions. + public Func>? CertificateNames { get; set; } + public AuthSpec? Auth => _auth; + /// What the OAuth 2.0 token line says (for tests); empty for other auth. + internal string TokenStatus => _tokenStatus?.Text ?? ""; + /// Describes again the auth the request inherits (it was added to a collection, or moved to another folder). public void RefreshInherited() { @@ -67,6 +97,15 @@ public void RefreshInherited() } } + /// Says again what the OAuth 2.0 token is (it was fetched or forgotten). + public void RefreshTokenStatus() + { + if (_tokenStatus is not null) + { + _tokenStatus.Text = DescribeToken?.Invoke() ?? ""; + } + } + public void Load(AuthSpec? auth) { _loading = true; @@ -132,6 +171,11 @@ private void SelectType(int index) { existing.Set("in", "header"); } + else if (type == "oauth2") + { + // Postman's default (authorization code) has the user sign in; the grant APIs are most often tested with is this. + existing.Set("grant_type", "client_credentials"); + } _byType[type] = existing; _auth = existing; @@ -153,48 +197,9 @@ private void BuildFields() view.Dispose(); } - var y = 0; - void Note(string text) - { - // A note may name a folder or a collection (the auth inherited from it): shown as written. - _fields.Add(new Label { HotKeySpecifier = Ui.NoHotKey, Text = text, X = 0, Y = y, Width = Dim.Fill() }); - y += 2; - } - - TextField Field(string label, string key, bool secret = false) - { - _fields.Add(new Label { Text = label, X = 0, Y = y }); - var field = new TextField { X = 16, Y = y, Width = Dim.Fill(1), Text = _auth?.Get(key) ?? "", Secret = secret }; - field.TextChanged += (_, _) => - { - if (!_loading && _auth is not null) - { - _auth.Set(key, field.Text); - Changed?.Invoke(this, EventArgs.Empty); - } - }; - _fields.Add(field); - y += 2; - return field; - } - - void Choice(string label, string key, string[] values, string[] labels) - { - _fields.Add(new Label { Text = label, X = 0, Y = y }); - var current = Array.IndexOf(values, _auth?.Get(key) ?? values[0]); - var selector = new OptionSelector { X = 16, Y = y, Labels = labels, Orientation = Orientation.Horizontal, Value = Math.Max(0, current) }; - selector.ValueChanged += (_, e) => - { - if (!_loading && _auth is not null && e.NewValue is int i) - { - _auth.Set(key, values[i]); - Changed?.Invoke(this, EventArgs.Empty); - } - }; - _fields.Add(selector); - y += 2; - } - + _controls.Clear(); + _tokenStatus = null; + _y = 0; switch (_auth?.Type) { case null: @@ -227,17 +232,326 @@ void Choice(string label, string key, string[] values, string[] labels) Choice("Add to", "in", ["header", "query"], ["Header", "Query params"]); break; case "oauth2": - Field("Access token", "accessToken", secret: true); - Field("Header prefix", "headerPrefix"); - Choice("Add token to", "addTokenTo", ["header", "queryParams"], ["Header", "Query params"]); - Note("Paste a token; built-in token acquisition (incl. Entra ID with certificates) is on the roadmap."); + BuildOAuth2(); break; default: Note($"'{AuthSpec.DisplayName(_auth.Type)}' is preserved in the collection but not applied when sending yet."); break; } - _fields.Add(new Label { Text = "Fields may use {{variables}}.", X = 0, Y = y + 1 }); + _fields.Add(new Label { Text = "Fields may use {{variables}}.", X = 0, Y = _y + 1 }); + _fields.SetContentHeight(_y + 2); + _fields.Viewport = _fields.Viewport with { Y = 0 }; _fields.SetNeedsLayout(); } -} + + /// + /// The OAuth 2.0 settings, a line each (they scroll when they don't fit), as Postman has them: the current token (the + /// one fetched, with Get new token and Forget token; a token to send when none is fetched; where it goes), then what a + /// new one is fetched with (the grant and its settings), and what empty fields mean. + /// + private void BuildOAuth2() + { + var grant = OAuth2Settings.ParseGrant(_auth!.Get("grant_type")); + var code = grant is OAuth2Grant.AuthorizationCode or OAuth2Grant.AuthorizationCodeWithPkce; + var fetched = grant is not (null or OAuth2Grant.Implicit); + var notes = new List(); + if (fetched) + { + // No shadows: the token's state is on the next line. + var getToken = new Button { Text = "Get new token", X = 0, Y = _y, ShadowStyle = null }; + getToken.Accepting += (_, e) => + { + e.Handled = true; + GetTokenRequested?.Invoke(this, EventArgs.Empty); + }; + var forget = new Button { Text = "Forget token", X = Pos.Right(getToken) + 1, Y = _y, ShadowStyle = null }; + forget.Accepting += (_, e) => + { + e.Handled = true; + ForgetTokenRequested?.Invoke(this, EventArgs.Empty); + }; + _fields.Add(getToken, forget); + _y++; + _tokenStatus = new Label { HotKeySpecifier = Ui.NoHotKey, X = LabelWidth, Y = _y, Width = Dim.Fill(1), Height = 1, Text = DescribeToken?.Invoke() ?? "" }; + _fields.Add(new Label { Text = "Token", X = 0, Y = _y }, _tokenStatus); + _y++; + } + + Field("Access token", "accessToken", secret: true, step: 1); + Field("Header prefix", "headerPrefix", step: 1, initial: "Bearer"); + Choice("Add token to", "addTokenTo", ["header", "queryParams"], ["Header", "Query params"], step: 1); + notes.Add("The access token is sent when no token is fetched (its URLs are empty); a token fetched is kept in memory only."); + _y++; + + DropDown("Grant type", "grant_type", OAuth2Settings.GrantTypes, GrantLabels, rebuild: true); + if (grant is null) + { + notes.Add($"No token is fetched with grant type '{_auth.Get("grant_type")}' (it is kept)."); + } + else if (grant == OAuth2Grant.Implicit) + { + notes.Add("No token is fetched with the implicit grant (retired by OAuth 2.0's security practice): use PKCE."); + } + + if (fetched) + { + Field("Token URL", "accessTokenUrl", step: 1); + } + + if (code || grant == OAuth2Grant.Implicit) + { + Field("Auth URL", "authUrl", step: 1); + Field("Callback URL", "redirect_uri", step: 1); + } + + Field("Client ID", "clientId", step: 1); + var jwt = string.Equals(_auth.Get("client_authentication"), "private_key_jwt", StringComparison.OrdinalIgnoreCase); + if (!jwt && grant != OAuth2Grant.Implicit) + { + Field("Client secret", "clientSecret", secret: true, step: 1); + } + + Field("Scope", "scope", step: 1); + if (grant == OAuth2Grant.Password) + { + Field("Username", "username", step: 1); + Field("Password", "password", secret: true, step: 1); + } + + if (grant == OAuth2Grant.AuthorizationCodeWithPkce) + { + Choice("Code challenge", "challengeAlgorithm", ["S256", "plain"], ["SHA-256", "Plain"], step: 1); + Field("Code verifier", "code_verifier", step: 1); + } + + if (code) + { + Field("State", "state", step: 1); + notes.Add("Empty callback URL: TermRest takes the sign-in's response on a loopback port."); + notes.Add(grant == OAuth2Grant.AuthorizationCodeWithPkce ? "Empty state or code verifier: a random one." : "Empty state: a random one."); + } + + if (fetched) + { + Choice("Client auth", "client_authentication", OAuth2Settings.ClientAuthenticationValues, ["Basic header", "In body", "Signed JWT"], step: 1, rebuild: true); + if (jwt) + { + DropDown("Certificate", "x-clientAssertionCertificate", null, [.. CertificateNames?.Invoke() ?? []], editable: true); + DropDown("JWT algorithm", "x-clientAssertionAlgorithm", ["", .. ClientAssertion.Algorithms], AlgorithmLabels); + Field("JWT key ID", "x-clientAssertionKeyId", step: 1); + Field("JWT audience", "x-clientAssertionAudience", step: 1); + Check("x-clientAssertionChain", "Send the certificate chain (x5c)"); + notes.Add("The certificate signs the client assertion (Tools › Client certificates…); empty JWT audience: the token URL."); + } + + Field("Refresh URL", "refreshTokenUrl", step: 1); + notes.Add("Empty refresh URL: the token URL."); + if (((string[])["tokenRequestParams", "authRequestParams", "refreshRequestParams"]) + .Any(key => _auth.Params.FirstOrDefault(p => p.Key == key)?.Value is System.Text.Json.Nodes.JsonArray { Count: > 0 })) + { + notes.Add("The extra parameters of its token, auth or refresh requests (Postman's advanced options) go too."); + } + } + + _y++; + foreach (var note in notes) + { + Note(note, 1); + } + } + /// A line of text (it may name a folder or collection: shown as written). + private void Note(string text, int step = 2) + { + _fields.Add(new Label { HotKeySpecifier = Ui.NoHotKey, Text = text, X = 0, Y = _y, Width = Dim.Fill(1) }); + _y += step; + } + + /// Shown for a setting not set (it is not written until edited). + private void Field(string label, string key, bool secret = false, int step = 2, string? initial = null) + { + _fields.Add(new Label { Text = label, X = 0, Y = _y }); + var field = new FormField { X = LabelWidth, Y = _y, Width = Dim.Fill(1), Text = _auth?.Get(key) ?? initial ?? "", Secret = secret }; + field.TextChanged += (_, _) => + { + if (!_loading && _auth is not null) + { + _auth.Set(key, field.Text); + OnEdited(); + } + }; + _fields.Add(field); + _controls[key] = field; + _y += step; + } + + private void Choice(string label, string key, string[] values, string[] labels, int step = 2, bool rebuild = false) + { + _fields.Add(new Label { Text = label, X = 0, Y = _y }); + var current = Array.FindIndex(values, v => string.Equals(v, _auth?.Get(key) ?? values[0], StringComparison.OrdinalIgnoreCase)); + var selector = new OptionSelector { X = LabelWidth, Y = _y, Labels = labels, Orientation = Orientation.Horizontal, Value = Math.Max(0, current) }; + selector.ValueChanged += (_, e) => + { + if (!_loading && _auth is not null && e.NewValue is int i) + { + _auth.Set(key, values[i]); + OnEdited(rebuild ? key : null); + } + }; + _fields.Add(selector); + _controls[key] = selector; + _y += step; + } + + /// A dropdown: of shown as , or of themselves (null values). + /// Other text may be typed (a certificate not registered yet). + private void DropDown(string label, string key, string[]? values, string[] labels, bool editable = false, bool rebuild = false) + { + _fields.Add(new Label { Text = label, X = 0, Y = _y }); + var setting = _auth?.Get(key) ?? ""; + var index = values is null ? -1 : Array.FindIndex(values, v => string.Equals(v, setting.Trim(), StringComparison.OrdinalIgnoreCase)); + var dropDown = new FormDropDown + { + X = LabelWidth, + Y = _y, + Width = Dim.Fill(1), + ReadOnly = !editable, + Source = new ListWrapper(new ObservableCollection(labels)), + Text = values is null ? setting : index >= 0 ? labels[index] : setting, + }; + dropDown.TextChanged += (_, _) => + { + if (_loading || _auth is null) + { + return; + } + + var shown = Array.IndexOf(labels, dropDown.Text); + var value = values is null || shown < 0 ? dropDown.Text : values[shown]; + if (value != (_auth.Get(key) ?? "")) + { + _auth.Set(key, value); + OnEdited(rebuild ? key : null); + } + }; + _fields.Add(dropDown); + _controls[key] = dropDown; + _y++; + } + + private void Check(string key, string text) + { + var box = new CheckBox + { + Text = text, + X = LabelWidth, + Y = _y, + Value = string.Equals(_auth?.Get(key), "true", StringComparison.OrdinalIgnoreCase) ? CheckState.Checked : CheckState.UnChecked, + }; + box.ValueChanged += (_, _) => + { + if (!_loading && _auth is not null) + { + _auth.Set(key, box.Value == CheckState.Checked ? "true" : "false"); + OnEdited(); + } + }; + _fields.Add(box); + _controls[key] = box; + _y++; + } + + /// + /// The setting edited, when it changes which fields there are (the grant type …): they are built again, after the + /// control's own event, and it keeps the focus. + /// + private void OnEdited(string? rebuilt = null) + { + Changed?.Invoke(this, EventArgs.Empty); + if (rebuilt is not null) + { + Later(() => + { + BuildFields(); + if (_controls.GetValueOrDefault(rebuilt) is { } control) + { + control.SetFocus(); + } + }); + } + else if (_tokenStatus is not null && !_statusPending) + { + // The token is the one of the settings as they are now: said again once typing pauses. + _statusPending = true; + Later(() => + { + _statusPending = false; + RefreshTokenStatus(); + }, TimeSpan.FromMilliseconds(400)); + } + } + + private void Later(Action action, TimeSpan? delay = null) + { + if (App is not { } app) + { + action(); + return; + } + + app.AddTimeout(delay ?? TimeSpan.Zero, () => + { + action(); + return false; + }); + } + + /// + /// A form that scrolls when it is taller than its space: with the wheel (over its fields and labels too), its scroll + /// bar, and to the field in focus. + /// + private sealed class ScrollingForm : View + { + public ScrollingForm() + { + CanFocus = true; + ViewportSettings |= ViewportSettingsFlags.HasVerticalScrollBar; + AddCommand(Command.ScrollUp, () => ScrollVertical(-1)); + AddCommand(Command.ScrollDown, () => ScrollVertical(1)); + MouseBindings.ReplaceCommands(MouseFlags.WheeledUp, Command.ScrollUp); + MouseBindings.ReplaceCommands(MouseFlags.WheeledDown, Command.ScrollDown); + } + + protected override void OnFocusedChanged(View? previousFocused, View? focused) + { + base.OnFocusedChanged(previousFocused, focused); + if (focused is null || focused.SuperView != this) + { + return; + } + + var viewport = Viewport; + var frame = focused.Frame; + if (frame.Y < viewport.Y) + { + Viewport = viewport with { Y = frame.Y }; + } + else if (frame.Bottom > viewport.Y + viewport.Height) + { + Viewport = viewport with { Y = frame.Bottom - viewport.Height }; + } + } + } + + /// A text field that leaves the wheel to the form: Terminal.Gui's takes a turn of it to focus itself. + private sealed class FormField : TextField + { + protected override bool OnMouseEvent(Mouse mouse) => !mouse.IsWheel && base.OnMouseEvent(mouse); + } + + /// A dropdown that leaves the wheel to the form: it would take a turn to focus itself, or change its choice. + private sealed class FormDropDown : DropDownList + { + protected override bool OnMouseEvent(Mouse mouse) => !mouse.IsWheel && base.OnMouseEvent(mouse); + } +} \ No newline at end of file diff --git a/src/TermRest.Tui/Views/RequestEditor.cs b/src/TermRest.Tui/Views/RequestEditor.cs index f8c7958..6255dd8 100644 --- a/src/TermRest.Tui/Views/RequestEditor.cs +++ b/src/TermRest.Tui/Views/RequestEditor.cs @@ -192,6 +192,40 @@ public Func? DescribeInheritedAuth set => _auth.DescribeInherited = value; } + /// What the OAuth 2.0 token of the request's auth is (supplied by the main window, which has the tokens). + public Func? DescribeToken + { + get => _auth.DescribeToken; + set => _auth.DescribeToken = value; + } + + /// The names of the workspace's client certificates, which can sign OAuth 2.0 client assertions. + public Func>? CertificateNames + { + get => _auth.CertificateNames; + set => _auth.CertificateNames = value; + } + + /// The Auth tab's Get new token was pressed. + public event EventHandler? GetTokenRequested + { + add => _auth.GetTokenRequested += value; + remove => _auth.GetTokenRequested -= value; + } + + /// The Auth tab's Forget token was pressed. + public event EventHandler? ForgetTokenRequested + { + add => _auth.ForgetTokenRequested += value; + remove => _auth.ForgetTokenRequested -= value; + } + + /// What the Auth tab says of the OAuth 2.0 token (for tests). + internal string TokenStatus => _auth.TokenStatus; + + /// Says again what the OAuth 2.0 token of the request's auth is (one was fetched or forgotten). + public void RefreshTokenStatus() => _auth.RefreshTokenStatus(); + /// Folder that the request's relative file paths start from (its collection's folder). public Func? BaseDirectory { diff --git a/src/TermRest.Tui/Views/ResponseView.cs b/src/TermRest.Tui/Views/ResponseView.cs index 8fe7977..6735f2d 100644 --- a/src/TermRest.Tui/Views/ResponseView.cs +++ b/src/TermRest.Tui/Views/ResponseView.cs @@ -237,9 +237,12 @@ public void Clear() } /// Pre-request scripts are running: the request is not prepared yet. - public void ShowRunningScripts() + public void ShowRunningScripts() => ShowProgress("Running pre-request scripts … (Esc or Send to cancel)"); + + /// Says what the request waits for before it goes (scripts, an OAuth 2.0 token). + public void ShowProgress(string text) { - _status.Text = "Running pre-request scripts … (Esc or Send to cancel)"; + _status.Text = text; _status.SchemeName = null; } diff --git a/tests/TermRest.Cli.Tests/CommandLineTests.cs b/tests/TermRest.Cli.Tests/CommandLineTests.cs index 23e4bbb..27e87ed 100644 --- a/tests/TermRest.Cli.Tests/CommandLineTests.cs +++ b/tests/TermRest.Cli.Tests/CommandLineTests.cs @@ -88,6 +88,32 @@ public async Task Send_curl_prints_no_command_for_a_request_that_cannot_be_sent( Assert.StartsWith("curl", good.Text, StringComparison.Ordinal); } + [Fact] + public async Task Send_fetches_an_oauth2_token_first_and_a_curl_command_says_it_has_none() + { + await using var server = await TestServer.StartAsync(); + static JsonObject Parameter(string key, string value) => new() { ["key"] = key, ["value"] = value, ["type"] = "string" }; + var auth = new JsonObject + { + ["type"] = "oauth2", + ["oauth2"] = new JsonArray(Parameter("grant_type", "client_credentials"), Parameter("accessTokenUrl", server.BaseUrl + "/token"), + Parameter("clientId", "cli"), Parameter("clientSecret", "{{secret}}")), + }; + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Me", "GET", server.BaseUrl + "/auth")], auth); + + var sent = await Termrest.RunAsync(["send", collection, "Me", "--var", "secret=cli-s3cret", "--verbose", "--no-history"]); + var curl = await Termrest.RunAsync(["send", collection, "Me", "--var", "secret=cli-s3cret", "--curl"]); + + Assert.True(sent.ExitCode == 0, sent.ToString()); + Assert.Equal($"Bearer {TestServer.Token}", JsonNode.Parse(sent.Text)!["authorization"]!.GetValue()); + Assert.Contains($"* Auth: OAuth 2.0, client credentials: new token from {server.BaseUrl}/token (200 in ", sent.Error, StringComparison.Ordinal); + Assert.True(curl.ExitCode == 0, curl.ToString()); + Assert.DoesNotContain("Authorization", curl.Text, StringComparison.Ordinal); + Assert.Contains($"warning: OAuth 2.0: no token was fetched yet, so the command has no access token: TermRest fetches one from {server.BaseUrl}/token when it sends the request.", + curl.Error, StringComparison.Ordinal); + Assert.Equal(2, server.Requests); // the token and the request: the cURL command sent nothing + } + [Fact] public async Task Run_and_send_fail_when_files_of_the_collection_cannot_be_read() { diff --git a/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs b/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs index 0dd4f89..7e95a02 100644 --- a/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs +++ b/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs @@ -9,8 +9,9 @@ namespace TermRest.Cli.Tests.Infrastructure; /// Minimal HTTP/1.1 server for the commands under test (plain sockets: no web framework next to termrest.dll, which /// must find its own dependencies). /bytes returns a binary body, /octets and /protobuf binary /// bodies without a NUL byte, /xlsx an Excel workbook, /large 1.5 MB of zeros, /utf8 -/// , /token a login response with , /wait no response until the -/// server stops (see ); any other path returns the request as JSON. +/// , /token a login (or OAuth 2.0 token) response with , /auth the +/// request's Authorization header, /wait no response until the server stops (see ); any +/// other path returns the request as JSON. /// internal sealed class TestServer : IAsyncDisposable { @@ -97,11 +98,12 @@ private async Task RespondAsync(TcpClient client) } // The body too, which may come with the headers, so that the connection closes cleanly. - var length = Encoding.ASCII.GetString(received.GetBuffer(), 0, end).Split("\r\n") - .Select(line => line.Split(':', 2)) - .Where(parts => parts.Length == 2 && parts[0].Trim().Equals("Content-Length", StringComparison.OrdinalIgnoreCase)) - .Select(parts => long.Parse(parts[1].Trim(), System.Globalization.CultureInfo.InvariantCulture)) + var head = Encoding.ASCII.GetString(received.GetBuffer(), 0, end).Split("\r\n"); + string? Header(string name) => head.Skip(1).Select(line => line.Split(':', 2)) + .Where(parts => parts.Length == 2 && parts[0].Trim().Equals(name, StringComparison.OrdinalIgnoreCase)) + .Select(parts => parts[1].Trim()) .FirstOrDefault(); + var length = long.Parse(Header("Content-Length") ?? "0", System.Globalization.CultureInfo.InvariantCulture); while (received.Length < end + 4 + length) { var count = await stream.ReadAsync(buffer, _stop.Token); @@ -114,7 +116,7 @@ private async Task RespondAsync(TcpClient client) } Interlocked.Increment(ref _requests); - var requestLine = Encoding.ASCII.GetString(received.ToArray()).Split("\r\n")[0].Split(' '); + var requestLine = head[0].Split(' '); var path = requestLine[1].Split('?')[0]; if (path == "/wait") { @@ -131,10 +133,11 @@ private async Task RespondAsync(TcpClient client) "/large" => (new byte[1536 * 1024], "application/octet-stream"), "/utf8" => (Encoding.UTF8.GetBytes(Utf8Json), "application/json; charset=utf-8"), "/token" => (Encoding.UTF8.GetBytes($"{{\"access_token\":\"{Token}\",\"token_type\":\"Bearer\",\"expires_in\":3600}}"), "application/json"), + "/auth" => (Encoding.UTF8.GetBytes(new JsonObject { ["authorization"] = Header("Authorization") }.ToJsonString()), "application/json"), _ => (Encoding.UTF8.GetBytes(new JsonObject { ["method"] = requestLine[0], ["path"] = path }.ToJsonString()), "application/json"), }; - var head = $"HTTP/1.1 200 OK\r\nContent-Type: {type}\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n"; - await stream.WriteAsync(Encoding.ASCII.GetBytes(head), _stop.Token); + var status = $"HTTP/1.1 200 OK\r\nContent-Type: {type}\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n"; + await stream.WriteAsync(Encoding.ASCII.GetBytes(status), _stop.Token); await stream.WriteAsync(body, _stop.Token); } catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException) diff --git a/tests/TermRest.Core.Tests/Infrastructure/OAuthServer.cs b/tests/TermRest.Core.Tests/Infrastructure/OAuthServer.cs new file mode 100644 index 0000000..ca79788 --- /dev/null +++ b/tests/TermRest.Core.Tests/Infrastructure/OAuthServer.cs @@ -0,0 +1,269 @@ +using System.Buffers.Text; +using System.Collections.Concurrent; +using System.Net; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using TermRest.Core.Json; + +namespace TermRest.Core.Tests.Infrastructure; + +/// +/// An OAuth 2.0 authorization server for tests. /authorize issues authorization codes (redirecting the browser to +/// the redirect URI); /token issues tokens for the client credentials, password, authorization code (with PKCE) +/// and refresh token grants, checking how the client authenticates: Basic, its secret in the form, or a client assertion +/// that 's key signed. /echo reflects a request's Authorization header and query, +/// as the API the tokens are for. +/// +public sealed class OAuthServer : IAsyncDisposable +{ + public const string ClientId = "termrest-client"; + public const string ClientSecret = "client-s3cret-value"; + public const string Username = "ada"; + public const string Password = "ada-pa55word"; + + private readonly WebApplication _app; + private readonly ConcurrentDictionary _codes = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _refreshTokens = new(StringComparer.Ordinal); + private int _issued; + + private OAuthServer(WebApplication app, Uri baseUri) + { + _app = app; + BaseUri = baseUri; + } + + public Uri BaseUri { get; } + + /// The token requests it received. + public ConcurrentQueue TokenRequests { get; } = new(); + + /// The client assertions it verified: their header and claims. + public ConcurrentQueue<(JsonObject Header, JsonObject Claims)> Assertions { get; } = new(); + + /// The certificate whose key signs client assertions; null: they are refused. + public X509Certificate2? AssertionCertificate { get; set; } + + /// The expires_in of the tokens it issues; null: none. + public int? ExpiresIn { get; set; } = 3600; + + public bool IssueRefreshTokens { get; set; } = true; + + /// The access tokens it issued, in order. + public ConcurrentQueue AccessTokens { get; } = new(); + + public string Url(string path) => new Uri(BaseUri, path).ToString(); + + /// Forgets the refresh tokens it issued, as a server does when they expire or are revoked. + public void RevokeRefreshTokens() => _refreshTokens.Clear(); + + public static async Task StartAsync() + { + var builder = WebApplication.CreateSlimBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.ConfigureKestrel(kestrel => kestrel.Listen(IPAddress.Loopback, 0)); + var app = builder.Build(); + OAuthServer? server = null; + app.MapGet("/authorize", (HttpContext ctx) => server!.Authorize(ctx)); + + // Typed: a lambda that takes the HttpContext and returns a task would be a RequestDelegate, its result never written. + app.MapPost("/token", (Func>)(ctx => server!.TokenAsync(ctx))); + app.MapPost("/moved", (HttpContext ctx) => Results.Redirect(server!.Url("token"), preserveMethod: true)); + app.MapGet("/echo", (HttpContext ctx) => Results.Json(new JsonObject + { + ["authorization"] = ctx.Request.Headers.Authorization.ToString(), + ["query"] = ctx.Request.QueryString.Value, + })); + await app.StartAsync(); + var address = app.Services.GetRequiredService().Features.Get()!.Addresses.First(); + server = new OAuthServer(app, new Uri(address.Replace("127.0.0.1", "localhost", StringComparison.Ordinal) + "/")); + return server; + } + + private IResult Authorize(HttpContext ctx) + { + var query = ctx.Request.Query; + var redirect = query["redirect_uri"].ToString(); + if (query["client_id"] != ClientId || redirect.Length == 0) + { + return Results.BadRequest("unknown client or no redirect_uri"); + } + + string Back(string parameters) => $"{redirect}{(redirect.Contains('?', StringComparison.Ordinal) ? "&" : "?")}{parameters}&state={Uri.EscapeDataString(query["state"].ToString())}"; + if (query["response_type"] != "code") + { + return Results.Redirect(Back("error=unsupported_response_type")); + } + + if (query["login_hint"] == "nobody") + { + return Results.Redirect(Back("error=access_denied&error_description=" + Uri.EscapeDataString("The user said no."))); + } + + var code = "code-" + Guid.NewGuid().ToString("N"); + _codes[code] = new IssuedCode(redirect, query["code_challenge"].ToString(), query["code_challenge_method"].ToString(), query["scope"].ToString()); + return Results.Redirect(Back("code=" + code)); + } + + private async Task TokenAsync(HttpContext ctx) + { + var form = (await ctx.Request.ReadFormAsync()).ToDictionary(f => f.Key, f => f.Value.ToString(), StringComparer.Ordinal); + var headers = ctx.Request.Headers.ToDictionary(h => h.Key.ToLowerInvariant(), h => h.Value.ToString(), StringComparer.Ordinal); + TokenRequests.Enqueue(new TokenRequest(form, headers, ctx.Request.QueryString.Value ?? "")); + + // How the client authenticated: confidential (Basic, secret, assertion) or public (its ID alone). + var confidential = false; + string? client; + var authorization = ctx.Request.Headers.Authorization.ToString(); + if (authorization.StartsWith("Basic ", StringComparison.Ordinal)) + { + var pair = Encoding.UTF8.GetString(Convert.FromBase64String(authorization[6..])).Split(':', 2); + if (pair is not [ClientId, ClientSecret]) + { + return Error(401, "invalid_client", "Client authentication failed."); + } + + (client, confidential) = (pair[0], true); + } + else if (form.GetValueOrDefault("client_assertion_type") is { } assertionType) + { + if (assertionType != "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" || Verify(form.GetValueOrDefault("client_assertion")) is not { } subject) + { + return Error(401, "invalid_client", "The client assertion is not valid."); + } + + (client, confidential) = (subject, true); + } + else if (form.GetValueOrDefault("client_secret") is { } secret) + { + if (form.GetValueOrDefault("client_id") != ClientId || secret != ClientSecret) + { + return Error(401, "invalid_client", "Client authentication failed."); + } + + (client, confidential) = (ClientId, true); + } + else + { + client = form.GetValueOrDefault("client_id"); + } + + switch (form.GetValueOrDefault("grant_type")) + { + case "client_credentials" when confidential: + return Issue(form.GetValueOrDefault("scope")); + case "client_credentials": + return Error(401, "invalid_client", "The client did not authenticate."); + case "password" when form.GetValueOrDefault("username") == Username && form.GetValueOrDefault("password") == Password: + return Issue(form.GetValueOrDefault("scope")); + case "password": + return Error(400, "invalid_grant", "Wrong user name or password."); + case "authorization_code": + { + if (client != ClientId || !_codes.TryRemove(form.GetValueOrDefault("code") ?? "", out var issued) || issued.RedirectUri != form.GetValueOrDefault("redirect_uri")) + { + return Error(400, "invalid_grant", "Unknown code, or another redirect_uri."); + } + + var verifier = form.GetValueOrDefault("code_verifier"); + if (issued.Challenge.Length > 0 + ? verifier is null || issued.Challenge != (issued.Method == "plain" ? verifier : Base64Url.EncodeToString(SHA256.HashData(Encoding.ASCII.GetBytes(verifier)))) + : !confidential) + { + return Error(400, "invalid_grant", "PKCE verification failed."); + } + + return Issue(issued.Scope); + } + + case "refresh_token" when _refreshTokens.TryRemove(form.GetValueOrDefault("refresh_token") ?? "", out _): + return Issue(form.GetValueOrDefault("scope")); + case "refresh_token": + return Error(400, "invalid_grant", "The refresh token expired."); + default: + return Error(400, "unsupported_grant_type", null); + } + } + + /// A client assertion's subject when its signature and claims are good; null otherwise. + private string? Verify(string? assertion) + { + if (AssertionCertificate is not { } certificate || assertion?.Split('.') is not [var header, var claims, var signature]) + { + return null; + } + + var head = (JsonObject)JsonNode.Parse(Base64Url.DecodeFromChars(header))!; + var payload = (JsonObject)JsonNode.Parse(Base64Url.DecodeFromChars(claims))!; + var algorithm = head["alg"].GetString() ?? ""; + var hash = algorithm.EndsWith("384", StringComparison.Ordinal) ? HashAlgorithmName.SHA384 : algorithm.EndsWith("512", StringComparison.Ordinal) ? HashAlgorithmName.SHA512 : HashAlgorithmName.SHA256; + var data = Encoding.ASCII.GetBytes($"{header}.{claims}"); + var bytes = Base64Url.DecodeFromChars(signature); + using var rsa = certificate.GetRSAPublicKey(); + using var ecdsa = certificate.GetECDsaPublicKey(); + var valid = algorithm[0] switch + { + 'R' => rsa?.VerifyData(data, bytes, hash, RSASignaturePadding.Pkcs1) == true, + 'P' => rsa?.VerifyData(data, bytes, hash, RSASignaturePadding.Pss) == true, + 'E' => ecdsa?.VerifyData(data, bytes, hash) == true, + _ => false, + }; + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + if (!valid || payload["aud"].GetString() != Url("token") || payload["iss"].GetString() != payload["sub"].GetString() + || payload["exp"]!.GetValue() <= now || payload["nbf"]!.GetValue() > now + 60 + || head["x5t#S256"].GetString() != Base64Url.EncodeToString(certificate.GetCertHash(HashAlgorithmName.SHA256))) + { + return null; + } + + Assertions.Enqueue((head, payload)); + return payload["sub"].GetString(); + } + + private IResult Issue(string? scope) + { + var number = Interlocked.Increment(ref _issued); + var token = new JsonObject { ["access_token"] = $"at-{number}-{Guid.NewGuid():N}", ["token_type"] = "Bearer" }; + AccessTokens.Enqueue(token["access_token"]!.GetValue()); + if (ExpiresIn is { } seconds) + { + token["expires_in"] = seconds; + } + + if (IssueRefreshTokens) + { + var refreshToken = $"rt-{number}-{Guid.NewGuid():N}"; + _refreshTokens[refreshToken] = true; + token["refresh_token"] = refreshToken; + } + + if (!string.IsNullOrEmpty(scope)) + { + token["scope"] = scope; + } + + return Results.Content(token.ToJsonString(), "application/json"); + } + + private static IResult Error(int status, string error, string? description) => + Results.Content(new JsonObject { ["error"] = error, ["error_description"] = description }.ToJsonString(), "application/json", statusCode: status); + + public async ValueTask DisposeAsync() + { + await _app.StopAsync(); + await _app.DisposeAsync(); + } + + /// A token request as it came: its form, its headers (names in lower case) and its query. + public sealed record TokenRequest(Dictionary Form, Dictionary Headers, string Query); + + private sealed record IssuedCode(string RedirectUri, string Challenge, string Method, string Scope); +} diff --git a/tests/TermRest.Core.Tests/OAuth2Tests.cs b/tests/TermRest.Core.Tests/OAuth2Tests.cs new file mode 100644 index 0000000..c80bcc6 --- /dev/null +++ b/tests/TermRest.Core.Tests/OAuth2Tests.cs @@ -0,0 +1,480 @@ +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Text.Json.Nodes; +using TermRest.Core.Auth; +using TermRest.Core.Certificates; +using TermRest.Core.History; +using TermRest.Core.Http; +using TermRest.Core.Json; +using TermRest.Core.Model; +using TermRest.Core.Postman; +using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Workspace; +using Xunit; + +namespace TermRest.Core.Tests; + +/// OAuth 2.0 tokens fetched for requests (grants, client authentication, sign-in, caching, refresh) from a test authorization server. +public sealed class OAuth2Tests +{ + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + + private static AuthSpec OAuth2(OAuthServer server, string grant, params (string Key, string Value)[] settings) + { + var auth = new AuthSpec { Type = "oauth2" }; + auth.Set("grant_type", grant); + auth.Set("accessTokenUrl", server.Url("token")); + auth.Set("clientId", OAuthServer.ClientId); + auth.Set("clientSecret", OAuthServer.ClientSecret); + foreach (var (key, value) in settings) + { + auth.Set(key, value); + } + + return auth; + } + + /// Adds extra parameters (tokenRequestParams …) as Postman writes them. + private static void AddParameters(AuthSpec auth, string key, params (string Key, string Value, string SendAs, bool Enabled)[] parameters) => + auth.Params.Add(new AuthParam + { + Key = key, + Type = "any", + Value = new JsonArray([.. parameters.Select(p => (JsonNode)new JsonObject { ["key"] = p.Key, ["value"] = p.Value, ["enabled"] = p.Enabled, ["send_as"] = p.SendAs })]), + }); + + private static (ApiWorkspace Workspace, PostmanCollection Collection) NewWorkspace() + { + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + return (workspace, workspace.CreateCollection("API")); + } + + private static HttpRequestSpec Echo(OAuthServer server, AuthSpec auth) => new() { Url = server.Url("echo"), Auth = auth }; + + private static string? Authorization(HttpExchange exchange) + { + Assert.True(exchange.IsSuccess, exchange.ErrorMessage); + return JsonNode.Parse(exchange.Response!.Body)!["authorization"].GetString(); + } + + private static int FreePort() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + return ((IPEndPoint)listener.LocalEndpoint).Port; + } + + [Fact] + public async Task A_client_credentials_token_is_fetched_once_with_basic_auth_and_kept_out_of_the_history() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(TestFiles.NewTempDirectory(), "history"), 10) }; + var spec = Echo(server, OAuth2(server, "client_credentials", ("scope", "orders.read orders.write"))); + + var first = await runner.SendAsync(collection, null, spec, _ct); + var second = await runner.SendAsync(collection, null, spec, _ct); + + var token = Assert.Single(server.AccessTokens); + Assert.Equal($"Bearer {token}", Authorization(first)); + Assert.Equal($"Bearer {token}", Authorization(second)); + var request = Assert.Single(server.TokenRequests); + Assert.Equal("Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{OAuthServer.ClientId}:{OAuthServer.ClientSecret}")), request.Headers["authorization"]); + Assert.Equal("application/json", request.Headers["accept"]); + Assert.Equal(new Dictionary { ["grant_type"] = "client_credentials", ["scope"] = "orders.read orders.write" }, request.Form); + Assert.StartsWith($"OAuth 2.0, client credentials: new token from {server.Url("token")} (200 in ", first.Request.AuthDescription, StringComparison.Ordinal); + Assert.StartsWith($"OAuth 2.0, client credentials: token from {server.Url("token")}, fetched ", second.Request.AuthDescription, StringComparison.Ordinal); + Assert.EndsWith(", expires in 60 min", second.Request.AuthDescription, StringComparison.Ordinal); + + // Token requests are not recorded; the requests that are have the token and the client secret masked. + var entries = runner.History!.Load(); + Assert.Equal(2, entries.Count); + Assert.All(entries, entry => Assert.Equal("Bearer ***", entry.SentHeaders.Single(h => h.Key == "Authorization").Value)); + var recorded = File.ReadAllText(runner.History.FilePath) + Encoding.UTF8.GetString(runner.History.ReadBody(entries[0])!); + Assert.DoesNotContain(token, recorded, StringComparison.Ordinal); + Assert.DoesNotContain(OAuthServer.ClientSecret, recorded, StringComparison.Ordinal); + } + + [Fact] + public async Task The_password_grant_can_send_the_client_secret_in_the_form() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.LocalVariables["password"] = OAuthServer.Password; + var auth = OAuth2(server, "password_credentials", ("username", OAuthServer.Username), ("password", "{{password}}"), ("client_authentication", "body")); + + var exchange = await runner.SendAsync(collection, null, Echo(server, auth), _ct); + + Assert.Equal($"Bearer {Assert.Single(server.AccessTokens)}", Authorization(exchange)); + var request = Assert.Single(server.TokenRequests); + Assert.False(request.Headers.ContainsKey("authorization")); + Assert.Equal(new Dictionary + { + ["grant_type"] = "password", + ["username"] = OAuthServer.Username, + ["password"] = OAuthServer.Password, + ["client_id"] = OAuthServer.ClientId, + ["client_secret"] = OAuthServer.ClientSecret, + }, request.Form); + Assert.Contains(OAuthServer.Password, exchange.Request.SecretValues); + Assert.Contains(OAuthServer.ClientSecret, exchange.Request.SecretValues); + } + + [Fact] + public async Task The_token_goes_in_the_query_or_after_the_header_prefix_as_the_auth_says() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + + var inQuery = await runner.SendAsync(collection, null, + new HttpRequestSpec { Url = server.Url("echo?access_token=old&page=2"), Auth = OAuth2(server, "client_credentials", ("addTokenTo", "queryParams")) }, _ct); + + var token = Assert.Single(server.AccessTokens); + Assert.Equal("", Authorization(inQuery)); + Assert.Equal($"?page=2&access_token={token}", JsonNode.Parse(inQuery.Response!.Body)!["query"].GetString()); + Assert.Equal("The auth helper replaced the 'access_token' query parameter.", Assert.Single(inQuery.Request.Warnings)); + Assert.Equal(server.Url("echo?page=2&access_token=***"), inQuery.Request.Redact(inQuery.Request.Url)); + + // Where the token goes is not part of what it is fetched with: the same token goes after another prefix + // ("Token ", which Postman writes with its space), in place of the request's own Authorization header. + var inHeader = await runner.SendAsync(collection, null, new HttpRequestSpec + { + Url = server.Url("echo"), + Headers = [new() { Key = "Authorization", Value = "Basic abc" }], + Auth = OAuth2(server, "client_credentials", ("headerPrefix", "Token ")), + }, _ct); + + Assert.Equal($"Token {token}", Authorization(inHeader)); + Assert.Equal("The auth helper replaced the 'Authorization' header.", Assert.Single(inHeader.Request.Warnings)); + Assert.Single(server.TokenRequests); + } + + [Fact] + public async Task Extra_token_request_parameters_go_in_the_form_a_header_or_the_url_and_replace_those_of_the_same_name() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.LocalVariables["audience"] = "https://api.example.com"; + var auth = OAuth2(server, "client_credentials", ("scope", "read")); + AddParameters(auth, "tokenRequestParams", + ("audience", "{{audience}}", "request_body", true), + ("scope", "write", "request_body", true), + ("X-Tenant", "contoso", "request_header", true), + ("api-version", "2", "request_url", true), + ("ignored", "x", "request_body", false)); + + var exchange = await runner.SendAsync(collection, null, Echo(server, auth), _ct); + + Assert.Equal($"Bearer {Assert.Single(server.AccessTokens)}", Authorization(exchange)); + var request = Assert.Single(server.TokenRequests); + Assert.Equal(new Dictionary { ["grant_type"] = "client_credentials", ["audience"] = "https://api.example.com", ["scope"] = "write" }, request.Form); + Assert.Equal(("contoso", "?api-version=2"), (request.Headers["x-tenant"], request.Query)); + } + + [Theory] + [InlineData("S256", false)] + [InlineData("plain", true)] + public async Task Authorization_code_with_pkce_signs_in_with_the_browser_and_receives_the_code_on_a_loopback_redirect(string method, bool registeredRedirect) + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + var browser = new TestBrowser(); + using var runner = new RequestRunner(workspace) { OAuth2Interaction = browser }; + var redirect = registeredRedirect ? $"http://localhost:{FreePort()}/callback" : ""; + + // A public client: no secret, as apps that sign users in with PKCE are. + var auth = OAuth2(server, "authorization_code_with_pkce", ("authUrl", server.Url("authorize")), ("clientSecret", ""), ("challengeAlgorithm", method), + ("redirect_uri", redirect), ("scope", "openid profile")); + + var exchange = await runner.SendAsync(collection, null, Echo(server, auth), _ct); + + Assert.Equal($"Bearer {Assert.Single(server.AccessTokens)}", Authorization(exchange)); + var authorization = OAuth2Response.ParseForm(Assert.Single(browser.Opened).Query.TrimStart('?')); + var redirectUri = authorization["redirect_uri"]; + if (registeredRedirect) + { + Assert.Equal(redirect, redirectUri); + } + else + { + Assert.Matches(@"^http://127\.0\.0\.1:\d+/$", redirectUri); + } + + Assert.Equal(("code", OAuthServer.ClientId, "openid profile", method), (authorization["response_type"], authorization["client_id"], authorization["scope"], authorization["code_challenge_method"])); + Assert.True(authorization["state"].Length >= 20); + var request = Assert.Single(server.TokenRequests); + Assert.Equal(("authorization_code", redirectUri, OAuthServer.ClientId), (request.Form["grant_type"], request.Form["redirect_uri"], request.Form["client_id"])); + Assert.True(request.Form["code_verifier"].Length >= 43); + Assert.False(request.Headers.ContainsKey("authorization")); + Assert.Contains("Signed in", browser.Page, StringComparison.Ordinal); + Assert.StartsWith("OAuth 2.0, authorization code with PKCE: new token from", exchange.Request.AuthDescription, StringComparison.Ordinal); + } + + [Fact] + public async Task A_redirect_uri_elsewhere_takes_the_url_the_browser_ended_on_and_checks_its_state() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace) { OAuth2Interaction = new TestBrowser() }; + AuthSpec SignIn(string scope) => + OAuth2(server, "authorization_code", ("authUrl", server.Url("authorize")), ("redirect_uri", "https://oauth.pstmn.io/v1/callback"), ("state", "my-state"), ("scope", scope)); + + var exchange = await runner.SendAsync(collection, null, Echo(server, SignIn("a")), _ct); + + Assert.Equal($"Bearer {Assert.Single(server.AccessTokens)}", Authorization(exchange)); + var request = Assert.Single(server.TokenRequests); + Assert.Equal(("authorization_code", "https://oauth.pstmn.io/v1/callback"), (request.Form["grant_type"], request.Form["redirect_uri"])); + Assert.StartsWith("Basic ", request.Headers["authorization"], StringComparison.Ordinal); + + // A response to another sign-in (its state differs) is refused, as is the server's refusal to sign the user in. + runner.OAuth2Interaction = new TestBrowser { Tamper = url => url.Replace("state=my-state", "state=forged", StringComparison.Ordinal) }; + var forged = await runner.SendAsync(collection, null, Echo(server, SignIn("b")), _ct); + Assert.Null(forged.Response); + Assert.Equal("OAuth 2.0: the authorization response is not the one to this sign-in (its state differs), so no token was asked for.", forged.ErrorMessage); + + runner.OAuth2Interaction = new TestBrowser(); + var denied = SignIn("c"); + AddParameters(denied, "authRequestParams", ("login_hint", "nobody", "request_url", true)); + Assert.Equal("OAuth 2.0: the authorization server did not sign you in: access_denied: The user said no.", + (await runner.SendAsync(collection, null, Echo(server, denied), _ct)).ErrorMessage); + Assert.Single(server.TokenRequests); + } + + [Theory] + [InlineData("http://127.0.0.1:5000/callback?code=abc&state=s1")] + [InlineData("?code=abc&state=s1")] + [InlineData("code=abc&state=s1")] + [InlineData("https://app.example.com/callback#state=s1&code=abc")] + [InlineData(" https://oauth.pstmn.io/v1/callback?state=s1&code=abc&session_state=x\n")] + public void An_authorization_response_is_read_from_the_url_or_the_query_pasted(string pasted) => + Assert.Equal("abc", OAuth2Tokens.ReadAuthorizationResponse(pasted, "s1")); + + [Fact] + public async Task A_sign_in_times_out_or_is_cancelled_and_needs_a_way_to_sign_in() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace) { OAuth2Interaction = new TestBrowser { Wait = true } }; + runner.OAuth2Tokens.SignInTimeout = TimeSpan.FromMilliseconds(300); + var spec = Echo(server, OAuth2(server, "authorization_code_with_pkce", ("authUrl", server.Url("authorize")))); + + var timedOut = await runner.SendAsync(collection, null, spec, _ct); + + Assert.Matches(@"^OAuth 2\.0: the browser did not return to http://127\.0\.0\.1:\d+/ within 0\.3 seconds, so no token was asked for\.$", timedOut.ErrorMessage); + + runner.OAuth2Tokens.SignInTimeout = TimeSpan.FromMinutes(5); + using var cancel = CancellationTokenSource.CreateLinkedTokenSource(_ct); + cancel.CancelAfter(TimeSpan.FromMilliseconds(300)); + Assert.True((await runner.SendAsync(collection, null, spec, cancel.Token)).Cancelled); + + runner.OAuth2Interaction = null; + Assert.Equal("OAuth 2.0: the authorization code with PKCE grant has you sign in with a browser, which TermRest can't do here.", + (await runner.SendAsync(collection, null, spec, _ct)).ErrorMessage); + Assert.Empty(server.TokenRequests); + } + + [Fact] + public async Task An_expiring_token_is_refreshed_and_when_its_refresh_is_refused_a_new_one_is_fetched() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + var time = new ManualTime(DateTimeOffset.UtcNow); + runner.OAuth2Tokens.Time = time; + var auth = OAuth2(server, "password_credentials", ("username", OAuthServer.Username), ("password", OAuthServer.Password), ("scope", "profile"), + ("refreshTokenUrl", server.Url("token?refreshing=1"))); + AddParameters(auth, "refreshRequestParams", ("X-Refresh", "yes", "request_header", true)); + var spec = Echo(server, auth); + + await runner.SendAsync(collection, null, spec, _ct); + time.Now += TimeSpan.FromMinutes(59.5); // within a minute of expiring: refreshed before it goes + var refreshed = await runner.SendAsync(collection, null, spec, _ct); + + Assert.Equal(2, server.AccessTokens.Count); + Assert.Equal($"Bearer {server.AccessTokens.Last()}", Authorization(refreshed)); + var refresh = server.TokenRequests.Last(); + Assert.Equal(("refresh_token", "profile", "?refreshing=1", "yes"), (refresh.Form["grant_type"], refresh.Form["scope"], refresh.Query, refresh.Headers["x-refresh"])); + Assert.StartsWith($"OAuth 2.0, password: token refreshed at {server.Url("token")} (200 in ", refreshed.Request.AuthDescription, StringComparison.Ordinal); + + // Revoked: a new token is asked for, and a warning says why. + server.RevokeRefreshTokens(); + time.Now += TimeSpan.FromHours(2); + var fetched = await runner.SendAsync(collection, null, spec, _ct); + + Assert.Equal(3, server.AccessTokens.Count); + Assert.Equal($"Bearer {server.AccessTokens.Last()}", Authorization(fetched)); + Assert.Equal("password", server.TokenRequests.Last().Form["grant_type"]); + Assert.Equal($"OAuth 2.0: the token request to {server.Url("token")} failed: 400 Bad Request — invalid_grant: The refresh token expired. A new token was asked for instead.", + Assert.Single(fetched.Request.Warnings)); + } + + [Theory] + [InlineData("RSA", "", "RS256")] + [InlineData("RSA", "ps256", "PS256")] + [InlineData("EC", "", "ES256")] + public async Task A_client_assertion_signed_with_a_registered_certificate_authenticates_the_client(string keyType, string algorithm, string signedWith) + { + await using var server = await OAuthServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var workspace = ApiWorkspace.Open(directory); + var collection = workspace.CreateCollection("API"); + using var certificate = CreateSigner(keyType, directory); + server.AssertionCertificate = certificate; + + // Registered without URL patterns: it signs, and goes to no server. + workspace.Certificates.Entries.Add(new CertificateEntry { Name = "Signer", Cert = new FileSource { Src = "signer.pem" }, Key = new FileSource { Src = "signer.key" } }); + using var runner = new RequestRunner(workspace); + var auth = OAuth2(server, "client_credentials", ("client_authentication", "private_key_jwt"), ("x-clientAssertionCertificate", "signer"), + ("x-clientAssertionAlgorithm", algorithm), ("x-clientAssertionKeyId", "key-1"), ("x-clientAssertionChain", "true")); + + var exchange = await runner.SendAsync(collection, null, Echo(server, auth), _ct); + + Assert.Equal($"Bearer {Assert.Single(server.AccessTokens)}", Authorization(exchange)); + var request = Assert.Single(server.TokenRequests); + Assert.Equal(["client_assertion", "client_assertion_type", "client_id", "grant_type"], request.Form.Keys.Order(StringComparer.Ordinal)); + Assert.False(request.Headers.ContainsKey("authorization")); + var (header, claims) = Assert.Single(server.Assertions); + Assert.Equal((signedWith, "JWT", "key-1"), (header["alg"].GetString(), header["typ"].GetString(), header["kid"].GetString())); + Assert.Equal(Convert.ToBase64String(certificate.RawData), Assert.Single(header["x5c"]!.AsArray())!.GetString()); + Assert.Equal((OAuthServer.ClientId, OAuthServer.ClientId, server.Url("token")), (claims["iss"].GetString(), claims["sub"].GetString(), claims["aud"].GetString())); + Assert.Equal(300, claims["exp"]!.GetValue() - claims["iat"]!.GetValue()); + Assert.True(Guid.TryParse(claims["jti"].GetString(), out _)); + } + + [Fact] + public async Task A_token_that_cannot_be_had_stops_the_request() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(TestFiles.NewTempDirectory(), "history"), 10) }; + + var refused = await runner.SendAsync(collection, null, Echo(server, OAuth2(server, "client_credentials", ("clientSecret", "wrong-secret"))), _ct); + var redirected = await runner.SendAsync(collection, null, Echo(server, OAuth2(server, "client_credentials", ("accessTokenUrl", server.Url("moved")))), _ct); + var unsigned = await runner.SendAsync(collection, null, + Echo(server, OAuth2(server, "client_credentials", ("client_authentication", "private_key_jwt"), ("x-clientAssertionCertificate", "nope"))), _ct); + + Assert.Equal($"OAuth 2.0: the token request to {server.Url("token")} failed: 401 Unauthorized — invalid_client: Client authentication failed.", refused.ErrorMessage); + Assert.Equal($"OAuth 2.0: the token endpoint {server.Url("moved")} answered 307 Temporary Redirect (to {server.Url("token")}): token requests, which carry the client's credentials, are not redirected.", + redirected.ErrorMessage); + Assert.Equal("OAuth 2.0: the workspace has no client certificate named 'nope' to sign the client assertion with (Tools › Client certificates…).", unsigned.ErrorMessage); + Assert.All((HttpExchange[])[refused, redirected, unsigned], exchange => Assert.Null(exchange.Response)); + Assert.Single(server.TokenRequests); // the refused one: the redirect was not followed, and the assertion never signed + Assert.Empty(runner.History!.Load()); + } + + [Fact] + public async Task Without_urls_to_fetch_a_token_from_the_token_set_in_the_auth_is_sent() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + + // As Postman writes the helper with a token pasted in it: an authorization code grant without its URLs. + var pasted = new AuthSpec { Type = "oauth2" }; + pasted.Set("grant_type", "authorization_code"); + pasted.Set("accessTokenUrl", ""); + pasted.Set("authUrl", ""); + pasted.Set("accessToken", "pasted-token-value"); + pasted.Set("headerPrefix", "Bearer "); + var exchange = await runner.SendAsync(collection, null, Echo(server, pasted), _ct); + + Assert.Equal("Bearer pasted-token-value", Authorization(exchange)); + Assert.Equal("OAuth 2.0 access token", exchange.Request.AuthDescription); + Assert.Empty(exchange.Request.Warnings); + + // The implicit grant is not fetched (the OAuth 2.0 Security Best Current Practice retires it). + var unsent = await runner.SendAsync(collection, null, Echo(server, OAuth2(server, "implicit", ("authUrl", server.Url("authorize")))), _ct); + Assert.Equal("", Authorization(unsent)); + Assert.StartsWith("OAuth 2.0: there is no access token, and none is fetched: the implicit grant is not supported", Assert.Single(unsent.Request.Warnings), StringComparison.Ordinal); + Assert.Empty(server.TokenRequests); + } + + [Fact] + public async Task A_curl_command_gets_the_token_fetched_earlier_and_a_new_one_can_be_asked_for() + { + await using var server = await OAuthServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + var spec = Echo(server, OAuth2(server, "client_credentials")); + + var before = runner.Prepare(collection, null, spec); + Assert.False(runner.AddCachedToken(before)); + Assert.DoesNotContain("Authorization", CurlExporter.Export(before), StringComparison.Ordinal); + + await runner.SendAsync(collection, null, spec, _ct); + var after = runner.Prepare(collection, null, spec); + Assert.True(runner.AddCachedToken(after)); + Assert.Contains($"Authorization: Bearer {Assert.Single(server.AccessTokens)}", CurlExporter.Export(after), StringComparison.Ordinal); + + // Asked for (the Auth tab's Get new token), or after the one fetched is forgotten (its Clear). + var fresh = await runner.GetTokenAsync(runner.Prepare(collection, null, spec), fetchNew: true, _ct); + Assert.Equal((OAuth2TokenOrigin.Fetched, server.AccessTokens.Last()), (fresh.Origin, fresh.Token.AccessToken)); + Assert.True(runner.OAuth2Tokens.Forget(after.OAuth2!)); + Assert.Null(runner.OAuth2Tokens.Find(after.OAuth2!)); + await runner.SendAsync(collection, null, spec, _ct); + Assert.Equal(3, server.AccessTokens.Count); + } + + private static X509Certificate2 CreateSigner(string keyType, string directory) + { + using AsymmetricAlgorithm key = keyType == "EC" ? ECDsa.Create(ECCurve.NamedCurves.nistP256) : RSA.Create(2048); + var request = key is ECDsa ec + ? new CertificateRequest("CN=TermRest assertion signer", ec, HashAlgorithmName.SHA256) + : new CertificateRequest("CN=TermRest assertion signer", (RSA)key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + var now = DateTimeOffset.UtcNow; + using var certificate = request.CreateSelfSigned(now.AddMinutes(-5), now.AddDays(1)); + File.WriteAllText(Path.Combine(directory, "signer.pem"), certificate.ExportCertificatePem()); + File.WriteAllText(Path.Combine(directory, "signer.key"), key.ExportPkcs8PrivateKeyPem()); + return X509CertificateLoader.LoadCertificate(certificate.RawData); + } + + private sealed class ManualTime(DateTimeOffset now) : TimeProvider + { + public DateTimeOffset Now { get; set; } = now; + + public override DateTimeOffset GetUtcNow() => Now; + } + + /// A browser for sign-ins: it opens the authorization request and follows the server's redirect, as a user who signs in. + private sealed class TestBrowser : IOAuth2Interaction + { + public List Opened { get; } = []; + + /// The page the loopback redirect URI answered with. + public string? Page { get; private set; } + + /// Changes the URL the server redirects to (forges a response). + public Func? Tamper { get; init; } + + /// Never signs in: waits for the redirect (which then times out) or the cancellation. + public bool Wait { get; init; } + + public async Task SignInAsync(OAuth2SignIn signIn, CancellationToken cancellationToken) + { + Opened.Add(signIn.AuthorizationUrl); + if (Wait) + { + return signIn.Redirect is { } redirect ? await redirect.WaitAsync(cancellationToken) : null; + } + + using var client = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = false }); + using var authorization = await client.GetAsync(signIn.AuthorizationUrl, cancellationToken); + var location = authorization.Headers.Location?.ToString() ?? throw new InvalidOperationException(await authorization.Content.ReadAsStringAsync(cancellationToken)); + location = Tamper?.Invoke(location) ?? location; + if (signIn.Redirect is null) + { + return location; // the user pastes the URL the browser ended on + } + + using var callback = await client.GetAsync(location, cancellationToken); + Page = await callback.Content.ReadAsStringAsync(cancellationToken); + return await signIn.Redirect; + } + } +} diff --git a/tests/TermRest.Tui.Tests/MainWindowTests.cs b/tests/TermRest.Tui.Tests/MainWindowTests.cs index 7a577f2..837f800 100644 --- a/tests/TermRest.Tui.Tests/MainWindowTests.cs +++ b/tests/TermRest.Tui.Tests/MainWindowTests.cs @@ -3137,7 +3137,7 @@ public void Auth_tokens_and_key_values_are_masked_like_passwords() ui.Click("POST POST JSON"); ui.Click("Auth"); var shown = new List(); - (string Type, string Field, string Secret)[] fields = [("Bearer Token", "Token", "bearer-s3cret"), ("API Key", "Value", "apikey-s3cret"), ("OAuth 2.0 (access token)", "Access token", "oauth-s3cret")]; + (string Type, string Field, string Secret)[] fields = [("Bearer Token", "Token", "bearer-s3cret"), ("API Key", "Value", "apikey-s3cret"), ("OAuth 2.0", "Access token", "oauth-s3cret")]; foreach (var (type, field, secret) in fields) { ui.Click(type); @@ -3155,6 +3155,213 @@ public void Auth_tokens_and_key_values_are_masked_like_passwords() Assert.Equal(("oauth2", "oauth-s3cret"), (auth?.Type, auth?.Get("accessToken"))); } + /// OAuth 2.0 auth that fetches its token from (as a confidential client, unless the secret is set empty). + private static AuthSpec OAuth2(OAuthServer server, string grant, params (string Key, string Value)[] settings) + { + var auth = new AuthSpec { Type = "oauth2" }; + foreach (var (key, value) in (ReadOnlySpan<(string, string)>)[("grant_type", grant), ("accessTokenUrl", server.Url("token")), ("clientId", OAuthServer.ClientId), + ("clientSecret", OAuthServer.ClientSecret), .. settings]) + { + auth.Set(key, value); + } + + return auth; + } + + private static string? SentAuthorization(TermRest.Core.Http.HttpExchange? exchange) => + System.Text.Json.Nodes.JsonNode.Parse(exchange!.Response!.Body)!["authorization"]!.GetValue(); + + [Fact] + public void Choosing_another_oauth2_grant_shows_the_settings_it_takes() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + ui.Click("POST POST JSON"); + ui.Click("Auth"); + ui.Click("OAuth 2.0"); + var before = ui.Screen(); + ui.Click("Client credentials"); // opens the list of grants + ui.App.InjectKey(Key.CursorDown); + ui.App.InjectKey(Key.Enter); + ui.App.TimedEvents?.RunTimers(); // the fields are built again once the dropdown's own event is over + var after = ui.Screen(); + var auth = ui.Window.Editor.Spec.Auth; + var labels = Descendants(ui.Window.Editor).OfType().Select(l => l.Text).ToList(); + var focused = ui.App.Navigation?.GetFocused(); + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.End(token!); + + OnScreen("⟦ Get new token ⟧", before); + OnScreen("Client credentials", before); + Assert.Equal(("oauth2", "password_credentials"), (auth?.Type, auth?.Get("grant_type"))); + OnScreen("Password credentials", after); + Assert.Contains("Username", labels); + Assert.Contains("Password", labels); + + // The new dropdown has the focus the old one had. + Assert.NotNull(focused); + Assert.Contains(focused, Descendants(ui.Window.Editor).OfType().SelectMany(Descendants)); + } + + [Fact] + public void The_oauth2_settings_scroll_with_the_wheel_over_their_fields() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + ui.Window.Editor.Load(new HttpRequestSpec + { + Url = "https://api.example.com/me", + Auth = new AuthSpec { Type = "oauth2", Params = [new AuthParam { Key = "grant_type", Value = "authorization_code_with_pkce" }] }, + }); + ui.Click("Auth"); + var top = ui.Screen(); + var field = ui.Find("Header prefix"); + for (var i = 0; i < 30; i++) + { + ui.App.InjectMouse(new Terminal.Gui.Input.Mouse { ScreenPosition = field with { X = field.X + 20 }, Flags = Terminal.Gui.Input.MouseFlags.WheeledDown }); + } + + var bottom = ui.Screen(); + var auth = ui.Window.Editor.Spec.Auth; + ui.App.End(token!); + + OnScreen("⟦ Get new token ⟧", top); + Assert.DoesNotContain("Fields may use {{variables}}.", top, StringComparison.Ordinal); + Assert.DoesNotContain("⟦ Get new token ⟧", bottom, StringComparison.Ordinal); + OnScreen("Fields may use {{variables}}.", bottom); + Assert.Equal("authorization_code_with_pkce", auth?.Get("grant_type")); // the wheel over the grant's dropdown changed nothing + } + + [Fact] + public async Task Get_new_token_fetches_an_oauth2_token_and_forget_token_has_the_request_fetch_another() + { + await using var server = await OAuthServer.StartAsync(); + using var ui = new Harness(_directory); + string before = "", fetched = "", forgotten = "", status = ""; + TermRest.Core.Http.HttpExchange? sent = null; + + Drive(ui, () => + { + ui.Window.Editor.Load(new HttpRequestSpec { Url = server.Url("echo"), Auth = OAuth2(server, "client_credentials") }); + ui.Click("Auth"); + before = ui.Window.Editor.TokenStatus; + ui.Click("Get new token"); + }, + ("Fetched ", () => + { + fetched = ui.Window.Editor.TokenStatus; + status = ui.Window.StatusMessage; + ui.Click("Forget token"); + forgotten = ui.Window.Editor.TokenStatus; + ui.App.InjectKey(Key.F5); + }), + ("200 OK", () => + { + sent = ui.Window.ResponsePane.Exchange; + ui.Window.Editor.MarkClean(); + ui.App.RequestStop(); + })); + + Assert.Equal("None yet: fetched when sent.", before); + Assert.Matches(@"^Fetched \d\d:\d\d:\d\d, expires in 60 min\.$", fetched); + Assert.StartsWith($"✓ New OAuth 2.0 token from {server.Url("token")} (200 in ", status, StringComparison.Ordinal); + Assert.Equal("None yet: fetched when sent.", forgotten); + Assert.Equal(2, server.AccessTokens.Count); + Assert.Equal($"Bearer {server.AccessTokens.Last()}", SentAuthorization(sent)); + Assert.StartsWith("OAuth 2.0, client credentials: new token from", sent!.Request.AuthDescription, StringComparison.Ordinal); + } + + [Fact] + public async Task Signing_in_waits_in_a_dialog_that_closes_by_itself_when_the_browser_returns() + { + await using var server = await OAuthServer.StartAsync(); + using var ui = new Harness(_directory); + using var browser = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = false }); + var seen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Task? returning = null; + + // The user signs in once the dialog is up: the server sends the browser back to TermRest's loopback port. + ui.Runner.OAuth2Interaction = new SignInDialog(() => ui.App, _ => { }, url => + { + returning = Task.Run(async () => + { + await seen.Task; + var location = (await browser.GetAsync(url, TestContext.Current.CancellationToken)).Headers.Location; + await browser.GetAsync(location, TestContext.Current.CancellationToken); + }, TestContext.Current.CancellationToken); + return true; + }); + TermRest.Core.Http.HttpExchange? sent = null; + + var screens = Drive(ui, () => + { + ui.Window.Editor.Load(new HttpRequestSpec + { + Url = server.Url("echo"), + Auth = OAuth2(server, "authorization_code_with_pkce", ("authUrl", server.Url("authorize")), ("clientSecret", "")), + }); + ui.App.InjectKey(Key.F5); + }, + ("Waiting for the browser to return to http://127.0.0.1:", () => seen.SetResult()), + ("200 OK", () => + { + sent = ui.Window.ResponsePane.Exchange; + ui.Window.Editor.MarkClean(); + ui.App.RequestStop(); + })); + + await returning!; + OnScreen("Sign in to localhost in the browser that opened, or at this address:", screens[0]); + Assert.DoesNotContain("Sign in (OAuth 2.0)", screens[1], StringComparison.Ordinal); + Assert.Equal($"Bearer {Assert.Single(server.AccessTokens)}", SentAuthorization(sent)); + } + + [Fact] + public async Task The_address_the_browser_ended_on_is_pasted_into_the_sign_in_dialog() + { + await using var server = await OAuthServer.StartAsync(); + using var ui = new Harness(_directory); + using var browser = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = false }); + string? ended = null; + Task? visiting = null; + + // No browser here: the user signs in elsewhere, and copies the address of the callback page it ends on. + ui.Runner.OAuth2Interaction = new SignInDialog(() => ui.App, _ => { }, url => + { + visiting = Task.Run(async () => Volatile.Write(ref ended, (await browser.GetAsync(url, TestContext.Current.CancellationToken)).Headers.Location!.ToString()), + TestContext.Current.CancellationToken); + return false; + }); + TermRest.Core.Http.HttpExchange? sent = null; + + var screens = Drive(ui, () => + { + ui.Window.Editor.Load(new HttpRequestSpec + { + Url = server.Url("echo"), + Auth = OAuth2(server, "authorization_code", ("authUrl", server.Url("authorize")), ("redirect_uri", "https://oauth.pstmn.io/v1/callback")), + }); + ui.App.InjectKey(Key.F5); + }, + ("Paste the address it ends on", () => + { + SpinWait.SpinUntil(() => Volatile.Read(ref ended) is not null, TimeSpan.FromSeconds(10)); + ui.Type(ended!); + ui.App.InjectKey(Key.Enter); + }), + ("200 OK", () => + { + sent = ui.Window.ResponsePane.Exchange; + ui.Window.Editor.MarkClean(); + ui.App.RequestStop(); + })); + + await visiting!; + OnScreen("Open this address in a browser and sign in to localhost:", screens[0]); + OnScreen("Once you are signed in, the browser goes to https://oauth.pstmn.io/v1/callback.", screens[0]); + Assert.Equal($"Bearer {Assert.Single(server.AccessTokens)}", SentAuthorization(sent)); + } + [Fact] public void Enter_on_an_environment_value_edits_it_and_the_dialog_stays_open() { diff --git a/tests/TermRest.Tui.Tests/TermRest.Tui.Tests.csproj b/tests/TermRest.Tui.Tests/TermRest.Tui.Tests.csproj index fc99f35..ba13b7c 100644 --- a/tests/TermRest.Tui.Tests/TermRest.Tui.Tests.csproj +++ b/tests/TermRest.Tui.Tests/TermRest.Tui.Tests.csproj @@ -24,9 +24,10 @@ - + + From 3d068d9b1d3f459fbe2f36e3259634fb20bd56ee Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Tue, 17 Nov 2026 18:44:46 -0700 Subject: [PATCH 2/2] Docs: OAuth 2.0 token acquisition The README's new OAuth 2.0 section describes the grants, when a token is fetched, signing in with a loopback or pasted callback, client authentication (Basic, in the body, or a JWT signed with a client certificate), Postman's extra parameters, how token requests are sent, and Copy as cURL; it lists Postman's settings and TermRest's own (private_key_jwt and the x-clientAssertion settings), with an example. The features, the Auth bullet and the compatibility table point to it; the client certificates section says an entry without patterns signs client assertions, send --curl says it fetches no token, the tests include an OAuth 2.0 server, and the roadmap moves on to saving responses as Postman examples. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index d0f14ac..364b4fa 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ A lightweight terminal REST client for development and testing: - **Recording.** Press Record (F12) and every request and response you send is recorded. On stop, TermRest asks where to save it as a HAR file (JSON, opens in browser dev tools). Credentials, cookies, tokens and secret variables are redacted, files sent with a request are recorded by path only, and a recording streams to a private temporary file instead of growing in memory. - **Large bodies from files.** Send a file as the body without loading it: it is streamed when the request is sent, and a JSON or XML file is checked first. - **Client certificates (mutual TLS)** are first-class: PEM (including encrypted keys and chains), PFX/PKCS#12, and OS certificate stores. That includes the Windows certificate store with non-exportable keys and the macOS keychain. Certificates bind to URL patterns via a Newman-compatible registry, and a TLS tab shows exactly what was negotiated and presented. +- **OAuth 2.0 tokens fetched for you** from any standards-based authorization server: client credentials, password, and authorization code with or without PKCE (you sign in with your browser). The client authenticates with its secret, or with a JWT signed by one of your client certificates. Tokens are kept in memory only and refreshed when they expire. See [OAuth 2.0](#oauth-20). - **One native executable** per platform: Windows, macOS and Linux on x64 and ARM64. Built with .NET 10 Native AOT: about 20 MB, starts in about 50 ms, no runtime to install. - **A headless CLI** (`send`, `run`, `validate`, `convert`, `history`, `import-curl`, `certs`) for scripts and CI, using the same engine. @@ -134,7 +135,7 @@ A request that is not in a collection (a new one, an imported curl command, or o - **Params:** query parameters (kept in sync with the URL) and path variables (`:id` segments). Values are sent as typed, except that a `#` in a query parameter, a path variable or a `{{variable}}` in the path, and a `?` in a path variable, are sent percent-encoded (`%23`, `%3F`): they stay part of the value instead of ending the query or path, where the rest would not be sent. - **Headers:** values are sent as typed, in UTF-8 as curl sends them (`X-User: José` works), and cookies a server set go back in the bytes it sent them in; a value with a line break or NUL is refused (a trailing line break is dropped), so a value can never add a header of its own. Headers that describe a body (`Content-Type`, `Content-Encoding` …) are left out of a request without one, with a warning. -- **Auth:** inherit, none, Basic, Bearer, API key, Digest, NTLM, or an OAuth 2.0 access token. Other Postman auth types are kept but not yet applied. Passwords, tokens and API key values are masked. An empty Bearer token (as a login request's script fills in later) adds no header, as in Postman, and a warning says so: an `Authorization` header the request has stays. Digest and NTLM credentials answer only their own scheme's challenges (NTLM also Negotiate) from the request's origin, never a Basic one. Credentials in the URL (`https://user:password@host`) are sent as Basic auth, as curl and Postman send them, unless the request has an `Authorization` header or an auth helper; as in Postman, a `{{variable}}` there may hold any character: `@ / ? # \` in its value are encoded, so a password with them neither ends the user info nor makes the URL invalid. The history masks the password, or the user name of a URL without one (`https://***@host`), which is then the credential. An API key or OAuth 2.0 token sent in the query is URL-encoded and replaces a parameter of the same name. +- **Auth:** inherit, none, Basic, Bearer, API key, Digest, NTLM, or OAuth 2.0, which fetches its token itself (see [OAuth 2.0](#oauth-20)). Other Postman auth types are kept but not yet applied. Passwords, tokens and API key values are masked. An empty Bearer token (as a login request's script fills in later) adds no header, as in Postman, and a warning says so: an `Authorization` header the request has stays. Digest and NTLM credentials answer only their own scheme's challenges (NTLM also Negotiate) from the request's origin, never a Basic one. Credentials in the URL (`https://user:password@host`) are sent as Basic auth, as curl and Postman send them, unless the request has an `Authorization` header or an auth helper; as in Postman, a `{{variable}}` there may hold any character: `@ / ? # \` in its value are encoded, so a password with them neither ends the user info nor makes the URL invalid. The history masks the password, or the user name of a URL without one (`https://***@host`), which is then the credential. An API key or OAuth 2.0 token sent in the query is URL-encoded and replaces a parameter of the same name. - **Body:** none, raw (JSON, XML, text, HTML, JavaScript, colored in the language chosen, with Beautify), form-data with files, x-www-form-urlencoded, a file (see [Sending a file as the body](#sending-a-file-as-the-body)), or GraphQL (its variables colored as JSON). Form-data is sent as browsers, curl and Postman send it: field and file names in UTF-8, a field's content type as typed (one with a line break or NUL is refused), and a file without one with the type of its extension (`.gif`, `.jpg`, `.jpeg`, `.png`, `.svg`, `.txt`, `.htm`, `.html`, `.pdf`, `.xml`, `.json`; any other gets `application/octet-stream`). An empty body is no body, sent without a `Content-Type`, as in Postman: raw text that is empty once its `{{variables}}` are replaced, a form with no enabled field, or a file body without a file (a warning says so). - **Scripts:** pre-request and post-response (test) scripts, in Python, JavaScript, C# or PowerShell (see [Scripts](#scripts)). - **Settings:** per-request SSL verification and redirects, which client certificate applies, and the description. Redirects are followed like `curl -L`: at most *max redirects* (0 follows none; a negative `maxRedirects` on a request, as earlier imports of `--max-redirs -1` saved it, uses the workspace's), never from https to http; 301 and 302 turn a POST into a GET, 303 any method but HEAD, and 307 and 308 send the method and body again. The `Authorization`, `Proxy-Authorization`, `Cookie` and `Host` headers and the auth helper's (such as an API key) go only to the request's origin (scheme, host and port); other headers follow the redirect. The URL a redirect leads to never takes the user and password of the request's URL (they are sent as its `Authorization` header), so it is shown, kept in the history and recorded without them. @@ -609,6 +610,32 @@ Not yet supported in v3 collections: - A key that holds a space followed by `*` (`Accept *: v`) reads as text rather than as a key, so TermRest writes such keys double-quoted (`"Accept *": v`). - Header names over 1,024 characters can't be saved. +## OAuth 2.0 + +An OAuth 2.0 auth helper (a request's, or a collection's or folder's) fetches its access token itself, from any authorization server that follows the standard ([RFC 6749](https://www.rfc-editor.org/rfc/rfc6749)): Keycloak, Okta, Auth0, Ping, Microsoft Entra ID, your own. The token is fetched when a request that uses it is sent, kept in memory for the session (never in a file, the history or a recording), and refreshed with its refresh token, or fetched again, when it is about to expire. In the Auth tab, *Get new token* fetches one now, *Forget token* has the next request fetch a new one, and *Token* says when it was fetched and when it expires. Requests with the same settings (those that inherit a collection's auth) share the token. + +- **Grants:** client credentials, password credentials, and authorization code, with or without PKCE (SHA-256 or plain). The implicit grant, which the [OAuth 2.0 Security Best Current Practice](https://www.rfc-editor.org/rfc/rfc9700) retires, is kept but not fetched. +- **When a token is fetched:** once the token URL is set (for an authorization code, the auth URL too). Until then the *Access token* field is sent, so a collection exported from Postman with a token pasted in it works as before. +- **Signing in** (authorization code): TermRest opens the sign-in page in your browser, and the server sends the browser back to the callback URL with the code. A loopback callback URL (`http://localhost:8400/callback`, `http://127.0.0.1:…`, `http://[::1]:…`) is received by TermRest itself, as native apps do ([RFC 8252](https://www.rfc-editor.org/rfc/rfc8252)); an empty one is a free port of 127.0.0.1 (`http://127.0.0.1:/`), which servers that allow loopback callbacks on any port take. With any other callback URL (Postman's `https://oauth.pstmn.io/v1/callback`, your app's), or a browser on another machine (over SSH), paste the address the browser ends on. The state is checked, so a response to another sign-in is refused; a random state and code verifier are used unless set. In the UI a dialog waits for the browser (with *Copy address*, *Open browser* and a field to paste into) and closes by itself when the browser returns; on the command line the address is printed to stderr and a pasted one read from stdin. With neither a browser nor a terminal (CI), `send` and `run` fail at once instead of waiting. +- **Client authentication:** as in Postman, the client ID and secret go as HTTP Basic (*Basic header*, the default) or in the form (*In body*); a client without a secret (a public one, as with PKCE) names itself in the form. TermRest adds *Signed JWT*: a client assertion ([RFC 7523](https://www.rfc-editor.org/rfc/rfc7523), OpenID Connect's `private_key_jwt`) signed with the private key of one of the workspace's [client certificates](#client-certificates-mutual-tls), so no secret is needed. It is valid for 5 minutes and names the certificate by its SHA-256 and SHA-1 thumbprints (`x5t#S256`, `x5t`). Choose the algorithm (RS256 by default for an RSA key; PS256, and RS or PS with 384 and 512; ES256, ES384 or ES512, as the curve of an EC key says), a key ID (`kid`), the audience (by default the token URL) and whether the certificate chain goes along (`x5c`). A certificate registered without URL patterns only signs: it goes to no server. Keys in the OS store work too, non-exportable ones included. Mutual TLS client authentication ([RFC 8705](https://www.rfc-editor.org/rfc/rfc8705)) works as for any request: the token URL gets the registered certificate whose patterns match it. +- **Extra parameters:** Postman's advanced options (`tokenRequestParams`, `authRequestParams`, `refreshRequestParams`: an `audience` or `resource`, a header, a URL parameter) are sent, and replace a parameter of the same name. TermRest doesn't edit them yet. +- **Token requests** go with the workspace's SSL verification (or `--insecure`), proxy, CA bundle and timeout (60 seconds when none is set). They follow no redirects (they carry the client's credentials), send and keep no cookies, and are not recorded. A request's *Timeline* (and `send --verbose`) says where its token came from and when it expires. A token that can't be had stops the request, and its error says why, with the server's `error` and `error_description`; when the server refuses a refresh, a new token is fetched, with a warning. +- **cURL:** *Copy as cURL* and `send --curl` send nothing, so they add the token fetched earlier, if there is one; otherwise a warning says the command has none. + +The settings are Postman's (`grant_type`, `accessTokenUrl`, `authUrl`, `redirect_uri`, `clientId`, `clientSecret`, `scope`, `state`, `code_verifier`, `challengeAlgorithm`, `client_authentication`, `refreshTokenUrl`, `headerPrefix`, `addTokenTo`, `accessToken` …). A signed JWT is TermRest's `client_authentication: private_key_jwt`, with `x-clientAssertionCertificate` (the certificate's name in the registry), `x-clientAssertionAlgorithm`, `x-clientAssertionKeyId`, `x-clientAssertionAudience` and `x-clientAssertionChain`: + +```yaml +auth: + type: oauth2 + credentials: + grant_type: client_credentials + accessTokenUrl: https://login.example.com/oauth2/token + clientId: "{{clientId}}" + scope: orders.read + client_authentication: private_key_jwt + x-clientAssertionCertificate: service identity +``` + ## Client certificates (mutual TLS) Open **Tools › Client certificates** (F8). From there you can add a PEM pair, a PFX, or pick a certificate from the OS store. Then bind it to URL patterns and press **Test** to confirm it loads with its private key. Entries are stored in `.termrest/certificates.json`: @@ -637,7 +664,7 @@ Open **Tools › Client certificates** (F8). From there you can add a PEM pair, ``` - **File format:** the same as Newman's `--ssl-client-cert-list` (`name`, `matches`, `cert`/`key`/`pfx` `src`, `passphrase`). `x-store` is a TermRest extension. Relative paths resolve against the workspace folder. -- **Matching:** patterns follow Postman's rules: `scheme://host[:port]/path`, where `*.domain` matches the domain and its subdomains, and a pattern without a port matches any port. A host can be written in Unicode or in ASCII (punycode): `https://bücher.example/*` and `https://xn--bcher-kva.example/*` match the same URLs. An IPv6 address goes in brackets, in any of its forms: `https://[::1]:8443/*`. The most specific match wins. A `certificate` set on an individual request in the collection (a Postman v2.1 field) takes precedence over the registry; without URL patterns of its own, it goes to the request's own origin only. A redirect target gets the certificate selected for its own URL. +- **Matching:** patterns follow Postman's rules: `scheme://host[:port]/path`, where `*.domain` matches the domain and its subdomains, and a pattern without a port matches any port. A host can be written in Unicode or in ASCII (punycode): `https://bücher.example/*` and `https://xn--bcher-kva.example/*` match the same URLs. An IPv6 address goes in brackets, in any of its forms: `https://[::1]:8443/*`. The most specific match wins. A `certificate` set on an individual request in the collection (a Postman v2.1 field) takes precedence over the registry; without URL patterns of its own, it goes to the request's own origin only. A redirect target gets the certificate selected for its own URL. An entry without patterns goes to no server: it signs [OAuth 2.0 client assertions](#oauth-20) (as any entry can). - **Passphrases:** avoid storing them in the file. Use `env:NAME` to read an environment variable, or `{{variable}}` to read a (secret) environment value. - **A certificate that can't be loaded** (a missing, locked or unreadable file, a wrong passphrase, or on Windows a file on a network share outside the workspace folder, until you allow files from outside it: see [Workspace layout](#workspace-layout)) is not used: the request is sent without it, and a warning says why. Likewise an extra CA bundle that can't be read: only the OS trust store is used then. - **OS stores** @@ -685,7 +712,7 @@ snapshot options: --send --request --width --height --them ```sh termrest run "samples/TermRest Demo.postman_collection.json" -e "Postman Echo" --report-json report.json termrest send api.postman_collection.json "Users/Get user" --var userId=42 -i -termrest send api.postman_collection.json "Users/Get user" --curl # print an equivalent curl command (scripts do not run; none, and exit code 2, if it can't be sent or curl can't send it the same way) +termrest send api.postman_collection.json "Users/Get user" --curl # print an equivalent curl command (scripts do not run, no OAuth 2.0 token is fetched; none, and exit code 2, if it can't be sent or curl can't send it the same way) termrest send api.postman_collection.json "Users/List users" --filter '$.users[?@.active].email' # only the values a JSONPath query selects, as a JSON array termrest run api.postman_collection.json --python .venv/bin/python # run the collection's Python scripts and tests @@ -718,7 +745,7 @@ On Windows, commands write UTF-8 without a byte order mark to files and pipes, a | Environments / globals | Read/write: JSON (`*.postman_environment.json`, `*.postman_globals.json`) and YAML (`postman/environments/*.environment.yaml`, `postman/globals/workspace.globals.yaml`) | | Folders, descriptions, saved examples, `protocolProfileBehavior`, unknown fields | Kept; edited fields are rewritten surgically | | Body modes | raw, urlencoded, formdata (text + files), file (binary, or typed and checked: `file.language`), graphql | -| Auth | inherit, noauth, basic, bearer, apikey, digest, ntlm, oauth2 (access token) — others are kept, not applied | +| Auth | inherit, noauth, basic, bearer, apikey, digest, ntlm, oauth2 (client credentials, password and authorization code with or without PKCE fetched and refreshed, or a token pasted; see [OAuth 2.0](#oauth-20)) — others are kept, not applied | | Scripts | JavaScript (`pm.*`, and the older `postman.*` and `tests[]`) runs in Node.js or Bun, Python (`"type": "text/x-python"`; v3 `language: text/x-python`) in Python, C# (`"type": "text/x-csharp"`) with the .NET SDK, PowerShell (`"type": "text/x-powershell"`) in PowerShell 7; scripts in TermRest's languages are written `"disabled": true` so Postman and Newman skip them; see [Scripts](#scripts) for the `pm` API supported | | Client certificates | `request.certificate` honoured; Newman certificate-list format for the registry | | cURL | Import (bash, cmd and PowerShell syntax) and export | @@ -749,7 +776,7 @@ src/TermRest.Core UI-free engine: Postman model + mapper (v2.1 JSON, v3 YAML), src/TermRest.Tui Terminal.Gui v2 views and dialogs src/TermRest.Cli `termrest` executable (System.CommandLine): TUI by default + headless commands tests/…Core.Tests xUnit v3: fidelity, mapper, URLs, variables, certificates, YAML, Postman v3, history, cURL, - recording and redaction, in-process Kestrel HTTP/TLS/mTLS tests + recording and redaction, in-process Kestrel HTTP/TLS/mTLS and OAuth 2.0 server tests tests/…Tui.Tests headless UI tests: renders the real window, injects mouse/keyboard input, asserts on screen text tests/…Cli.Tests termrest commands run as a process: exit codes, output, and the files they write ``` @@ -775,7 +802,7 @@ Notes: ## Roadmap -- **Next:** OAuth 2.0 token acquisition, including Entra ID client credentials with a certificate; saving responses as Postman examples, and showing them in v3 collections. +- **Next:** saving responses as Postman examples, and showing them in v3 collections. - **Phase 2:** - Proxy authentication. - Code snippets.