From 76525992f852d70ab1d22a81604f6d4d567ed160 Mon Sep 17 00:00:00 2001 From: Brent Miller Date: Tue, 17 Nov 2026 16:56:45 -0600 Subject: [PATCH] feat(analyzers): add E128228 token validation flag rule Flag a TokenValidationParameters validation flag set to a literal false. Report the five true-default flags and give ValidateIssuerSigningKey its own message because it defaults to false. Add tests, README coverage, and the 3.2.0 release entry. --- lode/dotnet/analyzer-candidates/catalog.md | 3 +- lode/dotnet/analyzer-candidates/index.md | 6 +- lode/dotnet/analyzers.md | 4 +- .../dotnet/analyzers/rule-details-security.md | 30 ++- lode/dotnet/release-tracking.md | 3 +- .../token-validation-flag-false-context.md | 49 ---- .../token-validation-flag-false-plan.md | 58 ---- .../token-validation-flag-false-tasks.md | 16 -- .../AnalyzerReleases.Shipped.md | 8 + src/E128.Analyzers/E128.Analyzers.csproj | 2 +- src/E128.Analyzers/README.md | 27 +- .../TokenValidationFlagFalseAnalyzer.cs | 117 +++++++++ .../TokenValidationFlagFalseAnalyzerTests.cs | 247 ++++++++++++++++++ 13 files changed, 438 insertions(+), 132 deletions(-) delete mode 100644 plans/token-validation-flag-false/token-validation-flag-false-context.md delete mode 100644 plans/token-validation-flag-false/token-validation-flag-false-plan.md delete mode 100644 plans/token-validation-flag-false/token-validation-flag-false-tasks.md create mode 100644 src/E128.Analyzers/Security/TokenValidationFlagFalseAnalyzer.cs create mode 100644 tests/E128.Analyzers.Tests/TokenValidationFlagFalseAnalyzerTests.cs diff --git a/lode/dotnet/analyzer-candidates/catalog.md b/lode/dotnet/analyzer-candidates/catalog.md index 099a2e4..9037ea7 100644 --- a/lode/dotnet/analyzer-candidates/catalog.md +++ b/lode/dotnet/analyzer-candidates/catalog.md @@ -1,5 +1,5 @@ # Analyzer Candidates: Settled Catalog -*Updated: 2026-11-13T22:43:07Z* +*Updated: 2026-11-17T22:44:32Z* This file holds the settled side of the register: which rule shipped, which idea was checked and rejected, and which sweep closed. Every rule ships from @@ -48,6 +48,7 @@ conversion plan. Open .NET 11 conversion shapes: [net11-conversion-sweep.md](net | E128225 | abstract-base-with-members-is-closed | implemented | 4/5 | 2026-11-13 | | E128226 | comparer-set-by-loop | implemented | 3.5/5 | 2026-11-13 | | E128227 | http-body-read-without-size-bound | implemented | 3.5/5 | 2026-11-13 | +| E128228 | token-validation-flag-false | implemented | n/a | 2026-11-17 | ## Rules From Guidance Documents diff --git a/lode/dotnet/analyzer-candidates/index.md b/lode/dotnet/analyzer-candidates/index.md index f77bf3d..a2f751e 100644 --- a/lode/dotnet/analyzer-candidates/index.md +++ b/lode/dotnet/analyzer-candidates/index.md @@ -1,5 +1,5 @@ # Analyzer Candidates: Open Register -*Updated: 2026-11-17T16:36:03Z* +*Updated: 2026-11-17T22:44:32Z* One register for every open analyzer candidate, whichever repository noticed it. A candidate enters at status `new`, carries a four-dimension score, and leaves @@ -31,6 +31,7 @@ No open candidate. `ByteSizeType.Is` matches the type by simple name, so a namespace move does not break the E128080 exemption. The body-read shape shipped as E128227. See [catalog.md](catalog.md). +The token-validation flag shape shipped as E128228. See [catalog.md](catalog.md). The JSON enumerator shape closed as skipped, because the enumerator releases no resource. See [skipped-decisions.md](skipped-decisions.md). @@ -39,6 +40,8 @@ resource. See [skipped-decisions.md](skipped-decisions.md). These clear the same bar and wait for a real defect in review. The `AsReadOnly()` getter shape left this table on 2026-11-14, because E128058 and E128060 require that shape. See [skipped-decisions.md](skipped-decisions.md). +The token-validation flag shape left this table on 2026-11-17, because the +maintainer chose prevention over the real-defect bar. | Rule | Check | Noise | | ------------------------------------------------------------------ | -------------------------------------------------------------- | ------ | @@ -49,7 +52,6 @@ and E128060 require that shape. See [skipped-decisions.md](skipped-decisions.md) | `Array.Resize` or `Concat` in a loop | call reassigned to the same receiver inside the loop | Low | | CORS wildcard with credentials | one chain holds `AllowAnyOrigin` and `AllowCredentials` | Low | | Antiforgery missing on a state-changing action | verb attribute with no antiforgery attribute in scope | Medium | -| Token validation flag set to constant `false` | six `TokenValidationParameters` flags | Low | | `readonly` field of a mutable struct | defensive copy on every member call | Low | | Floating-point loop counter | `for` loop steps a `float` or `double` local | Low | | Enum cast outside the member set | constant integral to enum conversion | Low | diff --git a/lode/dotnet/analyzers.md b/lode/dotnet/analyzers.md index 2a2f423..b493c95 100644 --- a/lode/dotnet/analyzers.md +++ b/lode/dotnet/analyzers.md @@ -1,5 +1,5 @@ # .NET 11 Roslyn Analyzers -*Updated: 2026-11-17T13:33:06Z* +*Updated: 2026-11-17T22:44:32Z* ## Strategy: Deny by Default @@ -123,7 +123,7 @@ Key rules by category (not exhaustive): | Design | Sealed-by-default, async void, sync-over-async, ConfigureAwait, TimeProvider, DI, ImmutableArray, abstract base with members is closed (E128225) | | Reliability | GeneratedRegex safety, DateTime roundtrip, Task.WhenAll, JsonDocument lifetime, pool Rent() guard, stackalloc bounds, pool zeroing, service lifetime (E128154, `TryAdd`, keyed, `typeof` and `AddHostedService` forms, and a singleton `DbContext`), `foreach` mutation (E128155, including array writes and `break` or `return` exits), `TaskCompletionSource` options and shared-source completers (E128159), hand-rolled process capture (E128223, redirect, read, then wait), `Path.Combine` segments (E128161), use after `Dispose` (E128162, direct block statement only), `ImmutableArray` default (E128163, no fix for struct instance fields), `await` in `finally` (E128186), exception filter text read (E128188), unreleased `GCHandle` (E128189), hidden `GetBuffer` (E128192), disposable field overwritten in a loop (E128193), `Lazy` without thread safety (E128194), configuration key absent from the settings files (E128195), `JsonSerializerOptions` written after first use (E128196), fixed day count used as a month (E128197), `Substring` count underflow (E128198) | | Performance | MinBy/MaxBy, HttpCompletionOption, FrozenSet, O(n²) loops, `SearchValues` (E128102), UTF-8 parsing, alternate lookups (E128131 to E128135), span bulk methods (E128140), u8 literals (E128141), complexity ceiling (E128152), `RemoveAt(0)` in loop (E128153), `SaveChanges` in loop (E128185), uncapped `Parallel.ForEachAsync` (E128187), `FileStream` without async I/O (E128190), HTTP and database round trips in a loop (E128203, E128204), collection presize (E128205), empty spin loop (E128206), reflection lookup in a loop (E128207), concurrent dictionary double lookup (E128208), `GetBytes` length in a loop (E128209), `new Regex` in a loop (E128210), `Task.Delay` in a loop without a token (E128211), `ToCharArray` copy (E128212), `Activator` in a loop (E128213), handler without decompression (E128214), `StringBuilder` capacity (E128215), unbounded channel (E128216), large struct by value (E128217), read-only `MemoryStream` (E128224), comparer set filled by a loop (E128226) | -| Security | FIPS cryptography rules: unapproved hash names, `System.Random` in security code, managed and CNG type creation, RSA key size, cipher mode, PBKDF2 work factor, TLS versions, deprecated RNG, excluded cipher names, AES-GCM tag size, SHA-3 policy, HMAC key length (E128071, E128075, E128142 to E128151), certificate bypass (E128156, `SslOptions` and `SslStream` too), fixed-time compare (E128157), hardcoded URL (E128164, dot boundary), hardcoded secret (E128165, token, credential and bearer names, `??`, indexers, getter returns, `u8`, connection strings), sensitive log argument (E128166, `LoggerMessage`, wrapped args, whole-word `ssn` and `pwd`, skips `EventId` and `Exception`), PFX import without `EphemeralKeySet` (E128191), unvalidated JWT claims used as an identity (E128202) | +| Security | FIPS cryptography rules: unapproved hash names, `System.Random` in security code, managed and CNG type creation, RSA key size, cipher mode, PBKDF2 work factor, TLS versions, deprecated RNG, excluded cipher names, AES-GCM tag size, SHA-3 policy, HMAC key length (E128071, E128075, E128142 to E128151), certificate bypass (E128156, `SslOptions` and `SslStream` too), fixed-time compare (E128157), hardcoded URL (E128164, dot boundary), hardcoded secret (E128165, token, credential and bearer names, `??`, indexers, getter returns, `u8`, connection strings), sensitive log argument (E128166, `LoggerMessage`, wrapped args, whole-word `ssn` and `pwd`, skips `EventId` and `Exception`), PFX import without `EphemeralKeySet` (E128191), unvalidated JWT claims used as an identity (E128202), token validation flag pinned false (E128228) | | Unsafe | `Unsafe.As` to `Unsafe.BitCast`, unaligned reads, unaligned non-blittable reads (E128139), bounds bypass, bool and int reinterpret, non-blittable `MemoryMarshal`, fixed buffers, `SkipInit`, unpinned pointers, string writes, null byref, delegate lifetime, bulk copy, pointer and length pairs, nonpublic reflection, raw IL, function pointer types (E128112 to E128129, E128136 to E128139, E128200) | | Style | string.Empty, Encoding.UTF8, XML doc comments, null-forgiving operator | | Maintainability | Direct recursion (E128199), conditional directive ceiling (E128201) | diff --git a/lode/dotnet/analyzers/rule-details-security.md b/lode/dotnet/analyzers/rule-details-security.md index 3c350aa..a26c42a 100644 --- a/lode/dotnet/analyzers/rule-details-security.md +++ b/lode/dotnet/analyzers/rule-details-security.md @@ -1,5 +1,5 @@ # Security Rule Detail Notes -*Updated: 2026-11-16T15:41:36Z* +*Updated: 2026-11-17T22:44:32Z* Detection shape and exclusions for the E128 security rules that the main rule table cannot show. The severity and the code-fix status live in @@ -51,3 +51,31 @@ check to the measured path. The rule needs `System.Net.Http.HttpContent`. Without that type it registers no action, so a consumer with no HTTP reference gets no report. + +### E128228: Token validation flag set to constant false + +Flags an assignment of a literal `false` to a validation flag on +`Microsoft.IdentityModel.Tokens.TokenValidationParameters`. The analyzer resolves +the property symbol and the containing type, so an unrelated type with the same +property name stays silent. One `SimpleAssignmentExpression` action covers an +object initializer assignment and an assignment after construction. + +Five flags default to `true`: `ValidateIssuer`, `ValidateAudience`, +`ValidateLifetime`, `RequireExpirationTime`, and `RequireSignedTokens`. + +`ValidateIssuerSigningKey` defaults to `false`. The rule reports that flag with +its own message, because the assignment matches the default and changes no +runtime behavior. + +The rule reports only a literal `false`, including a parenthesized literal. A +value read from configuration, a local, or a `const` stays silent, because the +rule cannot judge it. The safe value depends on the deployment, so the rule +carries no code fix. + +The rule needs `Microsoft.IdentityModel.Tokens.TokenValidationParameters`. +Without that type it registers no action, so a consumer with no JWT reference +gets no report. + +The analyzer declares two descriptors with one ID. The test harness cannot infer +a named markup diagnostic when descriptors share an ID, so the tests supply an +explicit `DiagnosticResult` with a keyed location. diff --git a/lode/dotnet/release-tracking.md b/lode/dotnet/release-tracking.md index 4c0f959..18d5ee7 100644 --- a/lode/dotnet/release-tracking.md +++ b/lode/dotnet/release-tracking.md @@ -1,5 +1,5 @@ # Roslyn Analyzer Release Tracking -*Updated: 2026-11-17T13:14:44Z* +*Updated: 2026-11-17T22:56:03Z* ## Overview @@ -170,6 +170,7 @@ that is missing from either file blocks the ship, even on a docs-only change set | 2.11.0 | E128223-226 | Hand-rolled process capture, read-only `MemoryStream`, closed base with members, and comparer set construction. E128220 also reports a closed-hierarchy switch that ends in a discard arm. | | 3.0.0 | (none) | E128160 removed. E128223 reports the read-then-wait shape that replaced the hand-rolled process capture. | | 3.1.0 | E128227 | HTTP body read without a size bound. Security, Warning. | +| 3.2.0 | E128228 | Token validation flag set to constant false. Security, Warning. | ## Sources diff --git a/plans/token-validation-flag-false/token-validation-flag-false-context.md b/plans/token-validation-flag-false/token-validation-flag-false-context.md deleted file mode 100644 index b7d1f41..0000000 --- a/plans/token-validation-flag-false/token-validation-flag-false-context.md +++ /dev/null @@ -1,49 +0,0 @@ -# Token Validation Flag Pinned False: Context -*Updated: 2026-11-14T00:08:09Z* - -## Problem - -`TokenValidationParameters` carries six boolean flags that default to `true`. A -literal `false` in an object initializer or an assignment turns the check off -with no build warning and no runtime warning. The token handler then accepts a -token that the caller believes it rejects. - -No installed rule covers the shape. E128202 reports unvalidated JWT claims used -as an identity, which is a later step in the same failure. - -## Evidence - -| Check | Result | -| ----- | ------ | -| `TokenValidationParameters` sites in `~/repos/e128` | Zero (as of 2026-11-14) | -| Covered by an installed rule | No | -| Runtime guard | None | - -Zero sites means the frequency score is low. The register bar is a real defect, -so Phase 0 records the decision to ship for prevention or to close. - -## Register Rows Considered And Declined - -| Row | Reason | -| --- | ------ | -| `AsReadOnly()` in a property getter | E128058 and E128060 require `.AsReadOnly()` in that exact getter shape. A second rule would report the code the shipped rules demand. Recorded in `skipped-decisions.md`. | -| CORS wildcard with credentials | ASP.NET Core throws at startup when a policy holds `AllowAnyOrigin` and `AllowCredentials`. The runtime already reports the defect. Zero sites in the corpus. | - -## Shape - -```csharp -var parameters = new TokenValidationParameters -{ - ValidateIssuer = false, - ValidateAudience = false, -}; -``` - -The rewrite is a caller decision, because the safe value depends on the issuer -and the audience. The rule reports and carries no code fix. - -## Related - -- [index.md](../../lode/dotnet/analyzer-candidates/index.md): open register -- [catalog.md](../../lode/dotnet/analyzer-candidates/catalog.md): settled rules -- [rule-details-security.md](../../lode/dotnet/analyzers/rule-details-security.md): security detection shapes diff --git a/plans/token-validation-flag-false/token-validation-flag-false-plan.md b/plans/token-validation-flag-false/token-validation-flag-false-plan.md deleted file mode 100644 index 0d4f9e2..0000000 --- a/plans/token-validation-flag-false/token-validation-flag-false-plan.md +++ /dev/null @@ -1,58 +0,0 @@ -# Token Validation Flag Pinned False: Plan -*Updated: 2026-11-14T00:08:09Z* - -Ship E128228: a `TokenValidationParameters` flag set to a literal `false` -silently disables a JWT check. Register row: "Token validation flag set to -constant `false`" in [lode/dotnet/analyzer-candidates/index.md](../../lode/dotnet/analyzer-candidates/index.md). - -## Success Criteria - -1. The rule has an analyzer, tests, a README row, and a README section. -2. `scripts/check.sh` passes with zero warnings. -3. The rule appears in `AnalyzerReleases.Unshipped.md`. -4. The lode register records the shipped rule, and the Tier 2 row leaves the table. -5. The evidence question in Phase 0 has a recorded answer. - -## Phases - -### Phase 0: Evidence - -1. Search every repository under `~/repos/e128` for `TokenValidationParameters`. -2. Record the site count as of the plan date. -3. If the count stays zero, decide with the maintainer: ship for prevention, or - close the row as skipped. Record the decision. - -### Phase 1: Tests - -1. Initializer sets each of the six flags to `false` and the test expects a hit. - The six flags: `ValidateIssuer`, `ValidateAudience`, `ValidateLifetime`, - `ValidateIssuerSigningKey`, `RequireExpirationTime`, `RequireSignedTokens`. -2. Assignment after construction expects a hit. -3. A literal `true`, a non-constant value, and a call argument stay silent. -4. An unrelated type with a same-named property stays silent. - -### Phase 2: Analyzer - -Diagnostic only. The safe value depends on the deploy, so no code fix. - -1. Match the property symbol against the `TokenValidationParameters` type. -2. Report an object initializer assignment or a simple assignment whose value is - `false`. -3. Report only a literal `false`, so a computed value stays silent. - -### Phase 3: Documentation - -1. Add the README row and section. -2. Add the `AnalyzerReleases.Unshipped.md` row. - -### Phase 4: Register And Verification - -1. Move the Tier 2 row to the catalog with the rule ID. -2. Add the detection shape to `rule-details-security.md`. -3. Run `scripts/check.sh` and `scripts/lode-check.sh --changed`. - -## Out Of Scope - -- Missing flags, such as a parameters object with no `ValidateLifetime` set. -- A flag read from configuration. The value is not a literal, so the rule cannot - judge it. diff --git a/plans/token-validation-flag-false/token-validation-flag-false-tasks.md b/plans/token-validation-flag-false/token-validation-flag-false-tasks.md deleted file mode 100644 index 540d9ed..0000000 --- a/plans/token-validation-flag-false/token-validation-flag-false-tasks.md +++ /dev/null @@ -1,16 +0,0 @@ -# Token Validation Flag Pinned False: Tasks -*Updated: 2026-11-14T00:08:09Z* - -- [ ] Phase 0: Search every repository for `TokenValidationParameters`. -- [ ] Phase 0: Record the site count. -- [ ] Phase 0: Decide ship or close when the count is zero. -- [ ] Phase 1: Test each of the six flags in an object initializer. -- [ ] Phase 1: Test an assignment after construction. -- [ ] Phase 1: Test the silent cases. -- [ ] Phase 2: Write the analyzer. Diagnostic only. -- [ ] Phase 3: Add the README row and section. -- [ ] Phase 3: Add the release row. -- [ ] Phase 4: Move the register row to the catalog. -- [ ] Phase 4: Add the detection shape to `rule-details-security.md`. -- [ ] Phase 4: Run `scripts/check.sh`. -- [ ] Phase 4: Run `scripts/lode-check.sh --changed`. diff --git a/src/E128.Analyzers/AnalyzerReleases.Shipped.md b/src/E128.Analyzers/AnalyzerReleases.Shipped.md index 0525ce5..4bea8ea 100644 --- a/src/E128.Analyzers/AnalyzerReleases.Shipped.md +++ b/src/E128.Analyzers/AnalyzerReleases.Shipped.md @@ -1,3 +1,11 @@ +## Release 3.2.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------ +E128228 | E128-Security | Warning | Token validation flag set to constant false + ## Release 3.1.1 ### Changed Rules diff --git a/src/E128.Analyzers/E128.Analyzers.csproj b/src/E128.Analyzers/E128.Analyzers.csproj index bb052b9..63a6ce5 100644 --- a/src/E128.Analyzers/E128.Analyzers.csproj +++ b/src/E128.Analyzers/E128.Analyzers.csproj @@ -23,7 +23,7 @@ - 3.1.5 + 3.2.0 true false true diff --git a/src/E128.Analyzers/README.md b/src/E128.Analyzers/README.md index 64d4fc0..94811e1 100644 --- a/src/E128.Analyzers/README.md +++ b/src/E128.Analyzers/README.md @@ -5,7 +5,7 @@ Roslyn analyzers and code fixes that enforce opinionated .NET conventions at com ## Installation ```xml - + ``` > `PrivateAssets="all"` keeps the analyzers out of your consumers' dependency graph. @@ -229,6 +229,7 @@ All rules default to **Warning** severity unless noted. Every rule includes a co | E128202 | Unvalidated JWT claims used as an identity | No | | E128222 | `Path.Combine` of a root `.FullName` and an uncontained leaf | Yes | | E128227 | HTTP body read without a size bound | No | +| E128228 | Token validation flag set to constant false | No | ### Style @@ -3297,6 +3298,30 @@ if (response.Content.Headers.ContentLength is not > MaxBodyBytes) var json = await response.Content.ReadAsStringAsync(cancellationToken); ``` +### E128228: Token validation flag set to constant false + +Flags a `TokenValidationParameters` flag assigned a literal `false`. Five flags default to `true`, so a literal `false` disables the check with no build warning and no runtime warning. The token handler then accepts a token that the caller believes it rejects. + +`ValidateIssuerSigningKey` defaults to `false`. The rule reports that flag with a distinct message, because the assignment matches the default value. + +The rule resolves the property symbol against `TokenValidationParameters` and reports only a literal `false`. A value read from configuration or a variable stays silent. The rule carries no code fix, because the safe value depends on the deployment. + +```csharp +// Before (warns) +var parameters = new TokenValidationParameters +{ + ValidateIssuer = false, + ValidateAudience = false, +}; + +// After +var parameters = new TokenValidationParameters +{ + ValidateIssuer = true, + ValidateAudience = true, +}; +``` + ## Requirements - .NET SDK 11.0+ (targets `netstandard2.0`, runs in any modern Roslyn host) diff --git a/src/E128.Analyzers/Security/TokenValidationFlagFalseAnalyzer.cs b/src/E128.Analyzers/Security/TokenValidationFlagFalseAnalyzer.cs new file mode 100644 index 0000000..61328be --- /dev/null +++ b/src/E128.Analyzers/Security/TokenValidationFlagFalseAnalyzer.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace E128.Analyzers.Security; + +/// +/// E128228: Reports a TokenValidationParameters flag set to a literal +/// false, which turns a JWT check off with no build warning. +/// +/// +/// Five flags default to true, so a literal false +/// silently disables the check. ValidateIssuerSigningKey defaults to +/// false, so the rule reports it with a distinct message. The rule +/// resolves the property symbol against TokenValidationParameters and +/// reports only a literal false, so a value read from configuration stays +/// silent. The safe value depends on the deployment, so the rule carries no code fix. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class TokenValidationFlagFalseAnalyzer : DiagnosticAnalyzer +{ + internal const string DiagnosticId = "E128228"; + + private const string TokenValidationParametersTypeName = "Microsoft.IdentityModel.Tokens.TokenValidationParameters"; + + private const string SigningKeyFlagName = "ValidateIssuerSigningKey"; + + private static readonly ImmutableHashSet DisabledCheckNames = ImmutableHashSet.Create( + StringComparer.Ordinal, + "ValidateIssuer", + "ValidateAudience", + "ValidateLifetime", + "RequireExpirationTime", + "RequireSignedTokens"); + + private static readonly DiagnosticDescriptor Rule = new( + DiagnosticId, + "Token validation flag set to constant false", + "JWT check '{0}' is set to false, so the token handler skips it", + "E128-Security", + DiagnosticSeverity.Warning, + true, + "The safe value depends on the deployment. Set the flag from configuration, or set it to true."); + + private static readonly DiagnosticDescriptor SigningKeyRule = new( + DiagnosticId, + "Issuer signing-key validation left off", + "ValidateIssuerSigningKey is set to false, which is the default, so the token handler does not check that the signing key belongs to the issuer", + "E128-Security", + DiagnosticSeverity.Warning, + true, + "Set the flag to true when the issuer publishes its signing keys."); + + /// + public override ImmutableArray SupportedDiagnostics => [Rule, SigningKeyRule]; + + /// + public override void Initialize(AnalysisContext context) + { + if (context is null) + { + throw new ArgumentNullException(nameof(context)); + } + + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static startContext => + { + MetadataTypes.RegisterForType( + startContext, + TokenValidationParametersTypeName, + Analyze, + SyntaxKind.SimpleAssignmentExpression); + }); + } + + private static void Analyze(SyntaxNodeAnalysisContext context, INamedTypeSymbol parametersType) + { + var assignment = (AssignmentExpressionSyntax)context.Node; + + if (context.SemanticModel.GetSymbolInfo(assignment.Left, context.CancellationToken).Symbol + is not IPropertySymbol property + || !TypeSymbols.DerivesFrom(property.ContainingType, parametersType)) + { + return; + } + + var isSigningKey = string.Equals(property.Name, SigningKeyFlagName, StringComparison.Ordinal); + if (!isSigningKey && !DisabledCheckNames.Contains(property.Name)) + { + return; + } + + if (!IsFalseLiteral(assignment.Right)) + { + return; + } + + context.ReportDiagnostic(isSigningKey + ? Diagnostic.Create(SigningKeyRule, assignment.GetLocation()) + : Diagnostic.Create(Rule, assignment.GetLocation(), property.Name)); + } + + private static bool IsFalseLiteral(ExpressionSyntax expression) + { + while (expression is ParenthesizedExpressionSyntax parenthesized) + { + expression = parenthesized.Expression; + } + + return expression.IsKind(SyntaxKind.FalseLiteralExpression); + } +} diff --git a/tests/E128.Analyzers.Tests/TokenValidationFlagFalseAnalyzerTests.cs b/tests/E128.Analyzers.Tests/TokenValidationFlagFalseAnalyzerTests.cs new file mode 100644 index 0000000..1619159 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TokenValidationFlagFalseAnalyzerTests.cs @@ -0,0 +1,247 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TokenValidationFlagFalseAnalyzerTests +{ + private const string Stub = """ + namespace Microsoft.IdentityModel.Tokens + { + public class TokenValidationParameters + { + public bool ValidateIssuer { get; set; } + public bool ValidateAudience { get; set; } + public bool ValidateLifetime { get; set; } + public bool ValidateIssuerSigningKey { get; set; } + public bool RequireExpirationTime { get; set; } + public bool RequireSignedTokens { get; set; } + } + } + """; + + private static readonly AnalyzerTestOptions Options = new() { Sources = [Stub] }; + + private static DiagnosticResult Expected() + { + return new DiagnosticResult("E128228", DiagnosticSeverity.Warning).WithLocation(0); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("ValidateIssuer")] + [InlineData("ValidateAudience")] + [InlineData("ValidateLifetime")] + [InlineData("RequireExpirationTime")] + [InlineData("RequireSignedTokens")] + public Task Reports_WhenAValidationFlagIsSetToFalse(string flag) + { + return AnalyzerTestRunner.VerifyAsync( + $$""" + using Microsoft.IdentityModel.Tokens; + + class C + { + TokenValidationParameters M() => new() { {|#0:{{flag}} = false|} }; + } + """, + Expected(), + Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WithItsOwnMessage_WhenTheSigningKeyFlagIsSetToFalse() + { + const string Code = """ + using Microsoft.IdentityModel.Tokens; + + class C + { + TokenValidationParameters M() => new() { {|#0:ValidateIssuerSigningKey = false|} }; + } + """; + + var expected = Expected().WithMessage("ValidateIssuerSigningKey is set to false, which is the default, so the token handler does not check that the signing key belongs to the issuer"); + + return AnalyzerTestRunner.VerifyAsync(Code, expected, Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAFlagIsAssignedAfterConstruction() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using Microsoft.IdentityModel.Tokens; + + class C + { + void M(TokenValidationParameters parameters) + { + {|#0:parameters.ValidateLifetime = false|}; + } + } + """, + Expected(), + Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFalseLiteralIsParenthesized() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using Microsoft.IdentityModel.Tokens; + + class C + { + TokenValidationParameters M() => new() { {|#0:ValidateAudience = (false)|} }; + } + """, + Expected(), + Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenADerivedTypeSetsTheFlag() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using Microsoft.IdentityModel.Tokens; + + class MyParameters : TokenValidationParameters + { + } + + class C + { + MyParameters M() => new() { {|#0:ValidateIssuer = false|} }; + } + """, + Expected(), + Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFlagIsTrue() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using Microsoft.IdentityModel.Tokens; + + class C + { + TokenValidationParameters M() => new() { ValidateAudience = true }; + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheValueIsALocal() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using Microsoft.IdentityModel.Tokens; + + class C + { + TokenValidationParameters M() + { + var disabled = false; + return new() { ValidateAudience = disabled }; + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheValueIsAConstant() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using Microsoft.IdentityModel.Tokens; + + class C + { + TokenValidationParameters M() + { + const bool Disabled = false; + return new() { ValidateAudience = Disabled }; + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFlagIsPassedAsANamedArgument() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M() + { + Configure(validateAudience: false); + } + + void Configure(bool validateAudience) + { + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnUnrelatedTypeHasTheSameProperty() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class Settings + { + public bool ValidateAudience { get; set; } + } + + class C + { + Settings M() => new() { ValidateAudience = false }; + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTokenValidationParametersTypeIsNotReferenced() + { + return AnalyzerTestRunner.VerifyAsync( + """ + namespace Other + { + public class TokenValidationParameters + { + public bool ValidateAudience { get; set; } + } + } + + class C + { + Other.TokenValidationParameters M() => new() { ValidateAudience = false }; + } + """); + } +}