|
| 1 | +// Copyright (c) The NATS Authors. |
| 2 | +// Licensed under the Apache License, Version 2.0. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using NATS.Jwt.Models; |
| 7 | +using NATS.NKeys; |
| 8 | + |
| 9 | +namespace NATS.Jwt; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// Provides extension methods for validating JSON Web Token (JWT) models. |
| 13 | +/// </summary> |
| 14 | +public static class ModelValidationExtensions |
| 15 | +{ |
| 16 | + private static readonly Dictionary<Type, PrefixByte[]> ExpectedClaimsPrefixes = new() |
| 17 | + { |
| 18 | + { typeof(NatsAccountClaims), [PrefixByte.Account, PrefixByte.Operator] }, |
| 19 | + { typeof(NatsActivationClaims), [PrefixByte.Account, PrefixByte.Operator] }, |
| 20 | + { typeof(NatsAuthorizationRequestClaims), [PrefixByte.Server] }, |
| 21 | + { typeof(NatsAuthorizationResponseClaims), [PrefixByte.Account] }, |
| 22 | + { typeof(NatsGenericClaims), [] }, |
| 23 | + { typeof(NatsOperatorClaims), [PrefixByte.Operator] }, |
| 24 | + { typeof(NatsUserClaims), [PrefixByte.Account] }, |
| 25 | + }; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Determines the expected prefix bytes for the given JWT claims data. |
| 29 | + /// </summary> |
| 30 | + /// <param name="claims">The JWT claims data whose expected prefixes need to be determined.</param> |
| 31 | + /// <returns>An array of PrefixByte values indicating the expected prefixes for the specified claims.</returns> |
| 32 | + /// <exception cref="NatsJwtException">Thrown if the expected prefixes cannot be determined for the given claims type.</exception> |
| 33 | + public static PrefixByte[] ExpectedPrefixes(this JwtClaimsData claims) |
| 34 | + { |
| 35 | + if (!ExpectedClaimsPrefixes.TryGetValue(claims.GetType(), out var prefixes)) |
| 36 | + { |
| 37 | + throw new NatsJwtException($"Can't find prefixes for {claims.GetType().Name}"); |
| 38 | + } |
| 39 | + |
| 40 | + return prefixes; |
| 41 | + } |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Validates the specified JWT header to ensure its type and algorithm are supported. |
| 45 | + /// </summary> |
| 46 | + /// <param name="header">The JWT header to validate.</param> |
| 47 | + /// <exception cref="NatsJwtException">Invalid JWT header.</exception> |
| 48 | + public static void Validate(this JwtHeader header) |
| 49 | + { |
| 50 | + if (!string.Equals("JWT", header.Type, StringComparison.InvariantCultureIgnoreCase)) |
| 51 | + { |
| 52 | + throw new NatsJwtException($"Invalid JWT header: not supported type {header.Type}"); |
| 53 | + } |
| 54 | + |
| 55 | + if (!string.Equals("ed25519", header.Algorithm, StringComparison.InvariantCultureIgnoreCase) |
| 56 | + && !string.Equals(NatsJwt.AlgorithmNkey, header.Algorithm, StringComparison.InvariantCultureIgnoreCase)) |
| 57 | + { |
| 58 | + throw new NatsJwtException($"Invalid JWT header: unexpected {header.Algorithm} algorithm"); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments