|
| 1 | +using System.Security.Claims; |
| 2 | +using GithubActionsOrchestrator.Models; |
| 3 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 4 | +using Microsoft.IdentityModel.Tokens; |
| 5 | + |
| 6 | +namespace GithubActionsOrchestrator.Auth; |
| 7 | + |
| 8 | +public static class TeleportAuth |
| 9 | +{ |
| 10 | + public const string CanMutatePolicy = "CanMutate"; |
| 11 | + public const string JwtHeader = "Teleport-Jwt-Assertion"; |
| 12 | + |
| 13 | + public static void AddTeleportAuth(this WebApplicationBuilder builder, TeleportAuthConfiguration cfg) |
| 14 | + { |
| 15 | + builder.Services.AddHttpClient(); |
| 16 | + builder.Services.AddSingleton<TeleportSigningKeyProvider>(); |
| 17 | + |
| 18 | + builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| 19 | + .AddJwtBearer(); |
| 20 | + |
| 21 | + // Configure JwtBearer with DI access to the key provider. |
| 22 | + builder.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme) |
| 23 | + .Configure<TeleportSigningKeyProvider>((options, keyProvider) => |
| 24 | + { |
| 25 | + options.MapInboundClaims = false; // keep raw Teleport claim names ("roles", "sub", "username") |
| 26 | + options.RequireHttpsMetadata = false; // we supply keys ourselves, no metadata endpoint |
| 27 | + options.Events = new JwtBearerEvents |
| 28 | + { |
| 29 | + // Teleport passes the assertion in a custom header, not "Authorization: Bearer". |
| 30 | + OnMessageReceived = ctx => |
| 31 | + { |
| 32 | + var header = ctx.Request.Headers[JwtHeader].FirstOrDefault(); |
| 33 | + if (!string.IsNullOrEmpty(header)) |
| 34 | + ctx.Token = header; |
| 35 | + return Task.CompletedTask; |
| 36 | + } |
| 37 | + }; |
| 38 | + options.TokenValidationParameters = new TokenValidationParameters |
| 39 | + { |
| 40 | + ValidateIssuer = !string.IsNullOrWhiteSpace(cfg.Issuer), |
| 41 | + ValidIssuer = cfg.Issuer, |
| 42 | + ValidateAudience = !string.IsNullOrWhiteSpace(cfg.Audience), |
| 43 | + ValidAudience = cfg.Audience, |
| 44 | + ValidateLifetime = true, |
| 45 | + ValidateIssuerSigningKey = true, |
| 46 | + NameClaimType = "username", |
| 47 | + RoleClaimType = "roles", |
| 48 | + ClockSkew = TimeSpan.FromMinutes(1), |
| 49 | + IssuerSigningKeyResolver = (_, _, kid, _) => keyProvider.ResolveKeys(kid), |
| 50 | + }; |
| 51 | + }); |
| 52 | + |
| 53 | + builder.Services.AddAuthorizationBuilder() |
| 54 | + .AddPolicy(CanMutatePolicy, policy => |
| 55 | + { |
| 56 | + if (!cfg.Enabled) |
| 57 | + { |
| 58 | + // Auth disabled: fall back to the API key gate only. |
| 59 | + policy.RequireAssertion(_ => true); |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + policy.RequireAuthenticatedUser(); |
| 64 | + policy.RequireAssertion(ctx => IsAuthorizedToMutate(ctx.User, cfg)); |
| 65 | + }); |
| 66 | + } |
| 67 | + |
| 68 | + /// <summary> |
| 69 | + /// A user may mutate when no allowlists are configured (any authenticated user), or when |
| 70 | + /// they hold an allowed role, or when their username is explicitly allowed. |
| 71 | + /// </summary> |
| 72 | + public static bool IsAuthorizedToMutate(ClaimsPrincipal user, TeleportAuthConfiguration cfg) |
| 73 | + { |
| 74 | + if (user?.Identity?.IsAuthenticated != true) |
| 75 | + return false; |
| 76 | + |
| 77 | + var roles = cfg.AuthorizedRoles ?? new List<string>(); |
| 78 | + var users = cfg.AuthorizedUsers ?? new List<string>(); |
| 79 | + |
| 80 | + if (roles.Count == 0 && users.Count == 0) |
| 81 | + return true; |
| 82 | + |
| 83 | + bool hasAllowedRole = roles.Count > 0 && GetRoles(user).Any(r => roles.Contains(r, StringComparer.OrdinalIgnoreCase)); |
| 84 | + bool isAllowedUser = users.Count > 0 && users.Contains(GetUsername(user), StringComparer.OrdinalIgnoreCase); |
| 85 | + |
| 86 | + return hasAllowedRole || isAllowedUser; |
| 87 | + } |
| 88 | + |
| 89 | + public static string GetUsername(ClaimsPrincipal user) |
| 90 | + { |
| 91 | + return user?.FindFirst("username")?.Value |
| 92 | + ?? user?.FindFirst("sub")?.Value |
| 93 | + ?? user?.Identity?.Name; |
| 94 | + } |
| 95 | + |
| 96 | + public static IEnumerable<string> GetRoles(ClaimsPrincipal user) |
| 97 | + { |
| 98 | + if (user == null) return Enumerable.Empty<string>(); |
| 99 | + return user.Claims |
| 100 | + .Where(c => c.Type is "roles" or ClaimTypes.Role) |
| 101 | + .Select(c => c.Value); |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +/// <summary> |
| 106 | +/// Fetches and caches Teleport's JWKS signing keys, refreshing on an interval and on a |
| 107 | +/// key-id miss (so key rotation is picked up without a restart). |
| 108 | +/// </summary> |
| 109 | +public class TeleportSigningKeyProvider |
| 110 | +{ |
| 111 | + private readonly IHttpClientFactory _httpClientFactory; |
| 112 | + private readonly ILogger<TeleportSigningKeyProvider> _logger; |
| 113 | + private readonly string _jwksUrl; |
| 114 | + private readonly TimeSpan _minRefreshInterval = TimeSpan.FromMinutes(5); |
| 115 | + private readonly object _lock = new(); |
| 116 | + |
| 117 | + private IList<SecurityKey> _keys = new List<SecurityKey>(); |
| 118 | + private DateTime _lastRefreshUtc = DateTime.MinValue; |
| 119 | + |
| 120 | + public TeleportSigningKeyProvider(IHttpClientFactory httpClientFactory, ILogger<TeleportSigningKeyProvider> logger) |
| 121 | + { |
| 122 | + _httpClientFactory = httpClientFactory; |
| 123 | + _logger = logger; |
| 124 | + _jwksUrl = Program.Config.TeleportAuth?.JwksUrl; |
| 125 | + } |
| 126 | + |
| 127 | + public IEnumerable<SecurityKey> ResolveKeys(string kid) |
| 128 | + { |
| 129 | + var current = _keys; |
| 130 | + var match = Filter(current, kid); |
| 131 | + if (match.Count > 0) |
| 132 | + return match; |
| 133 | + |
| 134 | + // Unknown kid (or empty cache): refresh once (throttled) and retry. |
| 135 | + Refresh(force: false); |
| 136 | + return Filter(_keys, kid); |
| 137 | + } |
| 138 | + |
| 139 | + private static List<SecurityKey> Filter(IList<SecurityKey> keys, string kid) |
| 140 | + { |
| 141 | + if (keys == null || keys.Count == 0) |
| 142 | + return new List<SecurityKey>(); |
| 143 | + if (string.IsNullOrEmpty(kid)) |
| 144 | + return keys.ToList(); |
| 145 | + var byKid = keys.Where(k => string.Equals(k.KeyId, kid, StringComparison.Ordinal)).ToList(); |
| 146 | + // If the token has a kid we don't recognise, fall back to trying all keys. |
| 147 | + return byKid.Count > 0 ? byKid : keys.ToList(); |
| 148 | + } |
| 149 | + |
| 150 | + private void Refresh(bool force) |
| 151 | + { |
| 152 | + if (string.IsNullOrWhiteSpace(_jwksUrl)) |
| 153 | + return; |
| 154 | + |
| 155 | + lock (_lock) |
| 156 | + { |
| 157 | + if (!force && DateTime.UtcNow - _lastRefreshUtc < _minRefreshInterval) |
| 158 | + return; |
| 159 | + |
| 160 | + try |
| 161 | + { |
| 162 | + var client = _httpClientFactory.CreateClient(); |
| 163 | + client.Timeout = TimeSpan.FromSeconds(10); |
| 164 | + var json = client.GetStringAsync(_jwksUrl).GetAwaiter().GetResult(); |
| 165 | + var keySet = new JsonWebKeySet(json); |
| 166 | + var keys = keySet.GetSigningKeys(); |
| 167 | + _keys = keys; |
| 168 | + _lastRefreshUtc = DateTime.UtcNow; |
| 169 | + _logger.LogInformation("Refreshed Teleport JWKS: {Count} signing key(s) from {Url}", keys.Count, _jwksUrl); |
| 170 | + } |
| 171 | + catch (Exception ex) |
| 172 | + { |
| 173 | + _lastRefreshUtc = DateTime.UtcNow; // avoid hammering a broken endpoint |
| 174 | + _logger.LogError(ex, "Failed to fetch Teleport JWKS from {Url}", _jwksUrl); |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | +} |
0 commit comments