|
| 1 | +// <autogenerated /> |
| 2 | +#nullable enable |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Diagnostics.CodeAnalysis; |
| 6 | +using System.IO; |
| 7 | +using System.Security.Claims; |
| 8 | +using Microsoft.IdentityModel.JsonWebTokens; |
| 9 | +using Microsoft.IdentityModel.Tokens; |
| 10 | + |
| 11 | +namespace Devlooped.Sponsors; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// The resulting status from validation. |
| 15 | +/// </summary> |
| 16 | +public enum ManifestStatus |
| 17 | +{ |
| 18 | + /// <summary> |
| 19 | + /// The manifest couldn't be read at all. |
| 20 | + /// </summary> |
| 21 | + Unknown, |
| 22 | + /// <summary> |
| 23 | + /// The manifest was read and is valid (not expired and properly signed). |
| 24 | + /// </summary> |
| 25 | + Valid, |
| 26 | + /// <summary> |
| 27 | + /// The manifest was read but has expired. |
| 28 | + /// </summary> |
| 29 | + Expired, |
| 30 | + /// <summary> |
| 31 | + /// The manifest was read, but its signature is invalid. |
| 32 | + /// </summary> |
| 33 | + Invalid, |
| 34 | +} |
| 35 | + |
| 36 | +/// <summary> |
| 37 | +/// Represents the sponsorship status of a user. |
| 38 | +/// </summary> |
| 39 | +/// <param name="Status">The status.</param> |
| 40 | +/// <param name="Principal">The principal potentially containing roles validated from the manifest.</param> |
| 41 | +/// <param name="SecurityToken">The security token from the validated manifest.</param> |
| 42 | +public record SponsorManifest(ManifestStatus Status, ClaimsPrincipal Principal, SecurityToken? SecurityToken) |
| 43 | +{ |
| 44 | + /// <summary> |
| 45 | + /// Whether the manifest <see cref="Status"/> is <see cref="ManifestStatus.Valid"/>. |
| 46 | + /// </summary> |
| 47 | + public bool IsValid => Status == ManifestStatus.Valid; |
| 48 | +} |
| 49 | + |
| 50 | +static partial class SponsorLink |
| 51 | +{ |
| 52 | + /// <summary> |
| 53 | + /// Reads the local manifest (if present) for the specified sponsorable account and validates it |
| 54 | + /// against the given JWK key. |
| 55 | + /// </summary> |
| 56 | + /// <param name="sponsorable">The sponsorable account to read.</param> |
| 57 | + /// <param name="jwk">The public key to validate the signature on the manifest JWT if found.</param> |
| 58 | + /// <param name="validateExpiration">Whether to validate the manifest expiration. If <see langword="false"/>, |
| 59 | + /// an expired manifest will be reported as <see cref="ManifestStatus.Valid"/>. The expiration date |
| 60 | + /// can be checked in that case via the <see cref="SponsorManifest.SecurityToken"/>.</param> |
| 61 | + /// <returns>A manifest that represents the user status.</returns> |
| 62 | + public static SponsorManifest GetManifest(string sponsorable, string jwk, bool validateExpiration = true) |
| 63 | + { |
| 64 | + var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), |
| 65 | + ".sponsorlink", "github", sponsorable + ".jwt"); |
| 66 | + |
| 67 | + if (!File.Exists(path)) |
| 68 | + return new SponsorManifest(ManifestStatus.Unknown, new ClaimsPrincipal(), null); |
| 69 | + |
| 70 | + return ParseManifest(File.ReadAllText(path), jwk, validateExpiration); |
| 71 | + } |
| 72 | + |
| 73 | + internal static SponsorManifest ParseManifest(string jwt, string jwk, bool validateExpiration) |
| 74 | + { |
| 75 | + var status = Validate(jwt, jwk, out var token, out var identity, validateExpiration); |
| 76 | + |
| 77 | + if (status == ManifestStatus.Unknown || identity == null) |
| 78 | + return new SponsorManifest(status, new ClaimsPrincipal(), token); |
| 79 | + |
| 80 | + return new SponsorManifest(status, new JwtRolesPrincipal(identity), token); |
| 81 | + } |
| 82 | + |
| 83 | + /// <summary> |
| 84 | + /// Validates the manifest signature and optional expiration. |
| 85 | + /// </summary> |
| 86 | + /// <param name="jwt">The JWT to validate.</param> |
| 87 | + /// <param name="jwk">The key to validate the manifest signature with.</param> |
| 88 | + /// <param name="token">Except when returning <see cref="Status.Unknown"/>, returns the security token read from the JWT, even if signature check failed.</param> |
| 89 | + /// <param name="identity">The associated claims, only when return value is not <see cref="Status.Unknown"/>.</param> |
| 90 | + /// <param name="requireExpiration">Whether to check for expiration.</param> |
| 91 | + /// <returns>The status of the validation.</returns> |
| 92 | + public static ManifestStatus Validate(string jwt, string jwk, out SecurityToken? token, out ClaimsIdentity? identity, bool validateExpiration) |
| 93 | + { |
| 94 | + token = default; |
| 95 | + identity = default; |
| 96 | + |
| 97 | + SecurityKey key; |
| 98 | + try |
| 99 | + { |
| 100 | + key = JsonWebKey.Create(jwk); |
| 101 | + } |
| 102 | + catch (ArgumentException) |
| 103 | + { |
| 104 | + return ManifestStatus.Unknown; |
| 105 | + } |
| 106 | + |
| 107 | + var handler = new JsonWebTokenHandler { MapInboundClaims = false }; |
| 108 | + |
| 109 | + if (!handler.CanReadToken(jwt)) |
| 110 | + return ManifestStatus.Unknown; |
| 111 | + |
| 112 | + var validation = new TokenValidationParameters |
| 113 | + { |
| 114 | + RequireExpirationTime = false, |
| 115 | + ValidateLifetime = false, |
| 116 | + ValidateAudience = false, |
| 117 | + ValidateIssuer = false, |
| 118 | + ValidateIssuerSigningKey = true, |
| 119 | + IssuerSigningKey = key, |
| 120 | + RoleClaimType = "roles", |
| 121 | + NameClaimType = "sub", |
| 122 | + }; |
| 123 | + |
| 124 | + var result = handler.ValidateTokenAsync(jwt, validation).Result; |
| 125 | + if (!result.IsValid || result.Exception != null) |
| 126 | + { |
| 127 | + if (result.Exception is SecurityTokenInvalidSignatureException) |
| 128 | + { |
| 129 | + var jwtToken = handler.ReadJsonWebToken(jwt); |
| 130 | + token = jwtToken; |
| 131 | + identity = new ClaimsIdentity(jwtToken.Claims); |
| 132 | + return ManifestStatus.Invalid; |
| 133 | + } |
| 134 | + else |
| 135 | + { |
| 136 | + var jwtToken = handler.ReadJsonWebToken(jwt); |
| 137 | + token = jwtToken; |
| 138 | + identity = new ClaimsIdentity(jwtToken.Claims); |
| 139 | + return ManifestStatus.Invalid; |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + token = result.SecurityToken; |
| 144 | + identity = new ClaimsIdentity(result.ClaimsIdentity.Claims, "JWT"); |
| 145 | + |
| 146 | + if (validateExpiration && token.ValidTo == DateTime.MinValue) |
| 147 | + return ManifestStatus.Invalid; |
| 148 | + |
| 149 | + // The sponsorable manifest does not have an expiration time. |
| 150 | + if (validateExpiration && token.ValidTo < DateTimeOffset.UtcNow) |
| 151 | + return ManifestStatus.Expired; |
| 152 | + |
| 153 | + return ManifestStatus.Valid; |
| 154 | + } |
| 155 | + |
| 156 | + class JwtRolesPrincipal(ClaimsIdentity identity) : ClaimsPrincipal([identity]) |
| 157 | + { |
| 158 | + public override bool IsInRole(string role) => HasClaim("roles", role) || base.IsInRole(role); |
| 159 | + } |
| 160 | +} |
0 commit comments