Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions README.md

Large diffs are not rendered by default.

82 changes: 82 additions & 0 deletions src/TermRest.Cli/ConsoleSignIn.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using TermRest.Core.Auth;

namespace TermRest.Cli;

/// <summary>
/// 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.
/// </summary>
internal sealed class ConsoleSignIn : IOAuth2Interaction
{
/// <summary>A line being read from stdin; one at a time, kept for the next sign-in when this one ended without it.</summary>
private Task<string?>? _reading;

public async Task<string?> 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<string?> 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;
}
}
1 change: 1 addition & 0 deletions src/TermRest.Cli/RequestOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion src/TermRest.Cli/SendCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static Command Create(Option<bool> insecure)
var raw = new Option<bool>("--raw") { Description = "Print the body as received (no JSON/XML pretty printing); with --filter, the values on one line" };
var filter = new Option<string?>("--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<bool>("--fail", "-f") { Description = "Exit with code 22 when the HTTP status is 400 or higher" };
var curl = new Option<bool>("--curl") { Description = "Print the request as a cURL command instead of sending it (scripts do not run)" };
var curl = new Option<bool>("--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<bool>("--no-history") { Description = "Do not record this request in the workspace history" };
var options = new RequestOptions();
command.Arguments.Add(collection);
Expand Down Expand Up @@ -89,7 +89,9 @@ public static Command Create(Option<bool> 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)
{
Expand Down
2 changes: 1 addition & 1 deletion src/TermRest.Cli/ValidateAndCertsCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
19 changes: 17 additions & 2 deletions src/TermRest.Core/Auth/AuthApplier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ public sealed class AppliedAuth

/// <summary>Resolved credentials (passwords, tokens, key values) that must not end up in history or logs.</summary>
public List<string> Secrets { get; } = [];

/// <summary>
/// OAuth 2.0 settings to fetch the access token with before the request is sent (see <see cref="OAuth2Tokens"/>); 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.
/// </summary>
public OAuth2Settings? OAuth2 { get; set; }
}

public static class AuthApplier
Expand Down Expand Up @@ -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));
Expand Down
141 changes: 141 additions & 0 deletions src/TermRest.Core/Auth/ClientAssertion.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Client assertions (RFC 7523; <c>private_key_jwt</c> 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.
/// </summary>
public static class ClientAssertion
{
/// <summary>The <c>client_assertion_type</c> of a JWT assertion.</summary>
public const string AssertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";

/// <summary>How long an assertion is valid: long enough for its token request, too short to be replayed later.</summary>
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);

/// <summary>The JWS algorithms assertions are signed with: RSA (PKCS #1 v1.5 and PSS) and ECDSA.</summary>
public static readonly string[] Algorithms = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"];

/// <summary>
/// A signed assertion for <paramref name="clientId"/> (its issuer and subject) to <paramref name="audience"/> (the token
/// endpoint), valid from <paramref name="now"/> for <see cref="Lifetime"/>. Its header names the certificate by its
/// SHA-256 and SHA-1 thumbprints (<c>x5t#S256</c>, <c>x5t</c>), and <paramref name="keyId"/> (<c>kid</c>) and the
/// certificate chain (<c>x5c</c>) when asked for. Without an <paramref name="algorithm"/>: RS256 for an RSA key, and for
/// an EC key the one of its curve (ES256 for P-256 …). Throws <see cref="OAuth2Exception"/> when it cannot sign.
/// </summary>
/// <param name="name">The certificate's name in the registry (for messages).</param>
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<Utf8JsonWriter> 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();
}
}
Loading
Loading