diff --git a/lode/dotnet/analyzer-candidates/index.md b/lode/dotnet/analyzer-candidates/index.md index 6278421..eddd967 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-14T00:08:28Z* +*Updated: 2026-11-16T15:18:25Z* One register for every open analyzer candidate, whichever repository noticed it. A candidate enters at status `new`, carries a four-dimension score, and leaves @@ -158,9 +158,3 @@ Nushell or Markdown capture stays in the pugworks ledger. > **Why**: S109 wants each literal behind a named constant, S2339 forbids a public `const` member, and neither accepts the other's answer. The workaround is a private const per value behind a public static property, which doubles the type for no behavior. Either S109 should skip a member whose declaration is the name, or S2339 should allow a const on a table type. > **Source**: `session friction 2026-11-14T18:20:00Z`, occurrence 1 of 3 -### Captured: E128184 must follow a temp directory into the method that deletes it (1/3): score pending -> **Key**: `e128184-must-follow-a-temp-directory-into-the-method-that-delet` -> **Class**: `design`, **Lang**: `cs`, **File**: `src/Harvest/Commands/ReadCommand.cs` -> **Pattern**: A recursive delete of a directory built from `Path.GetTempPath()` stays sound when the deletion moves into a helper -> **Why**: E128184 matches the delete call against a path created in the same method body, so extracting the cleanup into `DeleteTempDirectory(writer, tempDir)` reports a false positive on the package-private producer of that path. The rule should accept a `DirectoryInfo` that carries the temp-root provenance, or at least a helper in the same type. -> **Source**: `session friction 2026-11-14T18:22:00Z`, occurrence 1 of 3 diff --git a/lode/dotnet/analyzers/rule-details-security.md b/lode/dotnet/analyzers/rule-details-security.md index 2cfd59d..69f3b24 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-14T01:26:59Z* +*Updated: 2026-11-16T15:18:25Z* 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 @@ -18,8 +18,9 @@ stays silent. A body bound counts when it sits in the enclosing method body or the enclosing lambda body, and the rule resolves the bound by symbol, not by name text: -- A resolved `HttpContent.LoadIntoBufferAsync(long)` call. The parameterless - overload does not bound anything. +- A resolved `HttpContent.LoadIntoBufferAsync` call whose first parameter is + `long`, with or without a trailing `CancellationToken`. The parameterless + overload and the `CancellationToken`-only overload do not bound anything. - A null-safe `ContentLength` comparison on the same receiver chain. The check must precede and dominate the read. A read inside the `then` branch needs a condition that is false when `ContentLength` is `null`. A read outside it diff --git a/lode/dotnet/analyzers/rule-details.md b/lode/dotnet/analyzers/rule-details.md index dc2ec20..fe9bb89 100644 --- a/lode/dotnet/analyzers/rule-details.md +++ b/lode/dotnet/analyzers/rule-details.md @@ -1,5 +1,5 @@ # Rule Detail Notes -*Updated: 2026-11-13T22:43:20Z* +*Updated: 2026-11-16T15:19:01Z* Behavior notes for individual E128 rules. The complete rule table, the severity, and the code-fix status live in `src/E128.Analyzers/README.md`. This @@ -97,18 +97,19 @@ Severity: **Info**. Flags a recursive `Directory.Delete` or a build gate blocks work for no gain, so the severity stays low and the reported set stays narrow. -**Reported**: a parameter, a field read, a property read, and a `Path.Combine` -whose first argument is one of those. +**Reported**: a parameter that no safe call site bounds, a field read, a property +read, a `Path.Combine` over one of those, and a rooted literal such as +`"/etc/nginx"`. A readonly field, a get-only property, and a mutable field +report, because the value is computed at run time. **Silent**: a path under `Path.GetTempPath()`, a relative string literal, a const -field, a `Path.GetFullPath` over a safe value, a local that holds one of those, an -unknown shape, a non-recursive call, and a delete guarded by a proving -`StartsWith` test on the same path in the same block. +field, a `Path.GetFullPath` result, a `DirectoryInfo` over either, a local that +holds one of those, an unknown shape, a non-recursive call, and a delete guarded +by a proving `StartsWith` test. -**Reported literals**: a rooted literal, such as `"/etc/nginx"` or `"C:\Data"`. -The rule cannot prove such a directory is disposable. A readonly field, a -get-only property, and a mutable field report, because the value is computed at -run time. +**Parameter provenance**: the parameter of a private method takes the safety of +its call sites in the same type part. A call cycle, a non-private method, a +split type, or no visible call stays unsafe. A guard proves the test passed in two shapes, and the comparison must use `StringComparison.Ordinal` or `OrdinalIgnoreCase` with a root that ends at a @@ -120,9 +121,8 @@ around the delete and an `||` condition do not count. A local alias counts as the value it holds. A `Path.Combine` under a temp path stays silent when a later segment comes from a variable, because the rule cannot -see a `..` or a rooted value in it. - -No code fix. The safe root belongs to the caller. +see a `..` or a rooted value in it. No code fix: the safe root belongs to the +caller. ### E128191: PFX import without `EphemeralKeySet` diff --git a/src/E128.Analyzers/E128.Analyzers.csproj b/src/E128.Analyzers/E128.Analyzers.csproj index c435bbe..5f106ef 100644 --- a/src/E128.Analyzers/E128.Analyzers.csproj +++ b/src/E128.Analyzers/E128.Analyzers.csproj @@ -23,7 +23,7 @@ - 3.1.1 + 3.1.2 true false true diff --git a/src/E128.Analyzers/README.md b/src/E128.Analyzers/README.md index 67bdff1..14829ad 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. @@ -1973,9 +1973,9 @@ await winner; ### E128184: Recursive delete outside a recognized safe root -Flags a recursive `Directory.Delete` or `DirectoryInfo.Delete` when the path is a parameter, a field read, a property read, or a `Path.Combine` whose first argument is one of those. The severity is Info, because a false positive on a build gate blocks work for no gain. +Flags a recursive `Directory.Delete` or `DirectoryInfo.Delete` when the path is a parameter that no safe call site bounds, a field read, a property read, or a `Path.Combine` whose first argument is one of those. The severity is Info, because a false positive on a build gate blocks work for no gain. -A path under `Path.GetTempPath()`, a relative string literal, a const field, and a `Path.GetFullPath` over a safe value are recognized as safe. A local that holds one of those is also safe, and a local alias counts as the value it holds. A rooted literal reports, for example `"/etc/nginx"` or `"C:\Data"`, because the rule cannot prove the directory is disposable. A readonly field, a get-only property, and a mutable field report, because the value is computed at run time. +A path under `Path.GetTempPath()`, a relative string literal, a const field, and a `Path.GetFullPath` over a safe value are recognized as safe. A local that holds one of those is also safe, and a local alias counts as the value it holds. A `DirectoryInfo` created over a safe path is safe too. A parameter of a private method is safe when every call site in the same type part passes a safe path, so a cleanup helper keeps the provenance of its caller. A rooted literal reports, for example `"/etc/nginx"` or `"C:\Data"`, because the rule cannot prove the directory is disposable. A readonly field, a get-only property, and a mutable field report, because the value is computed at run time. A guard counts only when it proves the test passed. The comparison must use `StringComparison.Ordinal` or `OrdinalIgnoreCase`, and the root must end at a separator boundary, so a prefix test cannot pass for a sibling directory. An enclosing `if` that holds the call alone or joined by `&&` counts, and so does a preceding `if` with no `else` that exits when the call is false. The guard must be the statement before the delete. A write to the guarded symbol between the guard and the delete voids the guard. A negated test around the delete and an `||` condition do not count. @@ -3276,14 +3276,14 @@ HashSet set = [with(StringComparer.OrdinalIgnoreCase), .. items]; Flags an `HttpContent.ReadAsStringAsync` or `HttpContent.ReadAsByteArrayAsync` call that buffers the whole body with no cap. An untrusted server can answer with a body large enough to exhaust the heap. -The rule resolves the read and the bound by symbol, not by name. A bound must precede the read. A bound is a resolved `HttpContent.LoadIntoBufferAsync` call with the `long` cap overload, or a null-safe `ContentLength` comparison on the same content chain. A plain greater-than guard does not bound the read, because `ContentLength` is `null` for a chunked response and the guard passes through. A `MaxResponseContentBufferSize` setting anywhere in the enclosing type bounds it too. An in-memory content type (`StringContent`, `ByteArrayContent`, `ReadOnlyMemoryContent`, `JsonContent`) needs no bound, because its size is already known. The rule carries no code fix, because the cap value is a caller decision. +The rule resolves the read and the bound by symbol, not by name. A bound must precede the read. A bound is a resolved `HttpContent.LoadIntoBufferAsync` call with the `long` cap overload, with or without a trailing `CancellationToken`, or a null-safe `ContentLength` comparison on the same content chain. A plain greater-than guard does not bound the read, because `ContentLength` is `null` for a chunked response and the guard passes through. A `MaxResponseContentBufferSize` setting anywhere in the enclosing type bounds it too. An in-memory content type (`StringContent`, `ByteArrayContent`, `ReadOnlyMemoryContent`, `JsonContent`) needs no bound, because its size is already known. The rule carries no code fix, because the cap value is a caller decision. ```csharp // Before (warns) var json = await response.Content.ReadAsStringAsync(cancellationToken); // After option 1: cap the buffer load. -await response.Content.LoadIntoBufferAsync(MaxBodyBytes); +await response.Content.LoadIntoBufferAsync(MaxBodyBytes, cancellationToken); var json = await response.Content.ReadAsStringAsync(cancellationToken); // After option 2: fail closed when ContentLength is unknown. diff --git a/src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs b/src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs index a65f042..3af3d64 100644 --- a/src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs +++ b/src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs @@ -18,7 +18,7 @@ namespace E128.Analyzers.Security; /// /// The rule resolves symbols instead of matching names. A bound must precede the read and /// dominate it. A bound is a resolved HttpContent.LoadIntoBufferAsync -/// call with the long cap overload, or a null-safe +/// cap overload, with or without a trailing CancellationToken, or a null-safe /// ContentLength comparison on the same content chain. A plain /// greater-than guard does not bound the read, because ContentLength is /// null for a chunked response and the guard passes through. A @@ -43,8 +43,13 @@ public sealed class HttpBodyReadWithoutSizeBoundAnalyzer : DiagnosticAnalyzer private const string CappedBufferLoadName = "LoadIntoBufferAsync"; + private const string CancellationTokenTypeName = "System.Threading.CancellationToken"; + private const string ContentLengthName = "ContentLength"; + // A cap overload takes the long cap, optionally followed by a CancellationToken. + private const int MaxCapOverloadParameterCount = 2; + private static readonly ImmutableHashSet ReadMethodNames = ImmutableHashSet.Create( StringComparer.Ordinal, "ReadAsStringAsync", @@ -92,9 +97,10 @@ public override void Initialize(AnalysisContext context) ]; var httpContentHeaders = startContext.Compilation.GetTypeByMetadataName(HttpContentHeadersTypeName); + var cancellationToken = startContext.Compilation.GetTypeByMetadataName(CancellationTokenTypeName); startContext.RegisterSyntaxNodeAction( - nodeContext => AnalyzeRead(nodeContext, httpContent, httpContentHeaders, inMemoryContents), + nodeContext => AnalyzeRead(nodeContext, httpContent, httpContentHeaders, cancellationToken, inMemoryContents), SyntaxKind.InvocationExpression); }); } @@ -103,6 +109,7 @@ private static void AnalyzeRead( SyntaxNodeAnalysisContext context, INamedTypeSymbol httpContent, INamedTypeSymbol? httpContentHeaders, + INamedTypeSymbol? cancellationTokenType, INamedTypeSymbol?[] inMemoryContents) { var invocation = (InvocationExpressionSyntax)context.Node; @@ -123,7 +130,7 @@ private static void AnalyzeRead( var receiverType = model.GetTypeInfo(access.Expression, cancellationToken).Type; if (IsInMemoryContent(receiverType, inMemoryContents) - || HasSizeBound(invocation, model, httpContent, httpContentHeaders, cancellationToken)) + || HasSizeBound(invocation, model, httpContent, httpContentHeaders, cancellationTokenType, cancellationToken)) { return; } @@ -154,6 +161,7 @@ private static bool HasSizeBound( SemanticModel model, INamedTypeSymbol httpContent, INamedTypeSymbol? httpContentHeaders, + INamedTypeSymbol? cancellationTokenType, CancellationToken cancellationToken) { var scope = BlockScope.GetScope(read); @@ -164,7 +172,7 @@ private static bool HasSizeBound( { var contentLength = GetContentLengthProperty(httpContentHeaders); var boundVariables = CollectBoundVariables(scope, model, contentLength, readRoot, cancellationToken); - if (HasCappedBufferLoad(scope, read, readRoot, model, httpContent, cancellationToken) + if (HasCappedBufferLoad(scope, read, readRoot, model, httpContent, cancellationTokenType, cancellationToken) || HasContentLengthBound(scope, read, readRoot, model, contentLength, boundVariables, cancellationToken)) { return true; @@ -178,7 +186,8 @@ private static bool HasSizeBound( /// /// True when a resolved LoadIntoBufferAsync call on the same content - /// chain uses the cap overload with a long argument. The + /// chain uses the cap overload with a long argument. The overload may + /// also take a CancellationToken, so the token-aware form counts. The /// parameterless overload reads the whole body and does not bound anything. /// private static bool HasCappedBufferLoad( @@ -187,13 +196,14 @@ private static bool HasCappedBufferLoad( string readRoot, SemanticModel model, INamedTypeSymbol httpContent, + INamedTypeSymbol? cancellationTokenType, CancellationToken cancellationToken) { foreach (var candidate in scope.DescendantNodes().OfType()) { if (candidate != read && SameRoot(candidate.Expression, readRoot) - && IsCappedBufferLoad(candidate, model, httpContent, cancellationToken) + && IsCappedBufferLoad(candidate, model, httpContent, cancellationTokenType, cancellationToken) && Dominates(candidate, read, scope)) { return true; @@ -207,13 +217,16 @@ private static bool IsCappedBufferLoad( InvocationExpressionSyntax invocation, SemanticModel model, INamedTypeSymbol httpContent, + INamedTypeSymbol? cancellationTokenType, CancellationToken cancellationToken) { return model.GetSymbolInfo(invocation, cancellationToken).Symbol is IMethodSymbol method && string.Equals(method.Name, CappedBufferLoadName, StringComparison.Ordinal) && TypeSymbols.DerivesFrom(method.ContainingType, httpContent) - && method.Parameters.Length is 1 - && method.Parameters[0].Type.SpecialType is SpecialType.System_Int64; + && method.Parameters.Length is >= 1 and <= MaxCapOverloadParameterCount + && method.Parameters[0].Type.SpecialType is SpecialType.System_Int64 + && (method.Parameters.Length is 1 + || TypeSymbols.Matches(method.Parameters[1].Type, cancellationTokenType)); } /// diff --git a/src/E128.Analyzers/Security/RecursiveDeleteRootAnalyzer.cs b/src/E128.Analyzers/Security/RecursiveDeleteRootAnalyzer.cs index c768c94..412a074 100644 --- a/src/E128.Analyzers/Security/RecursiveDeleteRootAnalyzer.cs +++ b/src/E128.Analyzers/Security/RecursiveDeleteRootAnalyzer.cs @@ -16,10 +16,11 @@ namespace E128.Analyzers.Security; /// root. /// /// -/// The rule reports a path it cannot trace to a recognized safe root, and it never follows a -/// path across a method boundary. A path rooted at a temp directory, a relative literal, a -/// Path.GetFullPath result of either, or a value guarded by a -/// StartsWith check against a directory-bounded root stays silent. +/// The rule reports a path it cannot trace to a recognized safe root. A path rooted at a temp +/// directory, a relative literal, a Path.GetFullPath result of either, a +/// DirectoryInfo created over either, or a value guarded by a +/// StartsWith check against a directory-bounded root stays silent. A +/// parameter of a private method takes the safety of its call sites in the same type part. /// [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class RecursiveDeleteRootAnalyzer : DiagnosticAnalyzer @@ -107,7 +108,9 @@ private static void AnalyzeInvocation( return; } - if (ClassifyPath(path, model, pathTypes, cancellationToken) is not PathSafety.Unsafe) + var tracedMethods = new HashSet(SymbolEqualityComparer.Default); + if (ClassifyPath(path, model, pathTypes, directoryInfoTypes, tracedMethods, cancellationToken) + is not PathSafety.Unsafe) { return; } @@ -248,6 +251,8 @@ private static PathSafety ClassifyPath( ExpressionSyntax expression, SemanticModel model, ImmutableArray pathTypes, + ImmutableArray directoryInfoTypes, + HashSet tracedMethods, CancellationToken cancellationToken) { var visited = new HashSet(SymbolEqualityComparer.Default); @@ -271,13 +276,15 @@ private static PathSafety ClassifyPath( current = initializer; } - return ClassifyPathCore(current, model, pathTypes, cancellationToken); + return ClassifyPathCore(current, model, pathTypes, directoryInfoTypes, tracedMethods, cancellationToken); } private static PathSafety ClassifyPathCore( ExpressionSyntax expression, SemanticModel model, ImmutableArray pathTypes, + ImmutableArray directoryInfoTypes, + HashSet tracedMethods, CancellationToken cancellationToken) { var unwrapped = ExpressionUnwrapper.ParenthesesAndCasts(expression); @@ -301,12 +308,18 @@ private static PathSafety ClassifyPathCore( return PathSafety.Safe; } + if (ClassifyDirectoryInfoCreation(unwrapped, model, pathTypes, directoryInfoTypes, tracedMethods, cancellationToken) + is { } wrapperSafety) + { + return wrapperSafety; + } + if (FindPathInvocation(unwrapped, GetFullPathMethodName, pathTypes, model, cancellationToken) is { } getFullPath) { var arguments = getFullPath.ArgumentList.Arguments; return arguments.Count > 0 - ? ClassifyPath(arguments[0].Expression, model, pathTypes, cancellationToken) + ? ClassifyPath(arguments[0].Expression, model, pathTypes, directoryInfoTypes, tracedMethods, cancellationToken) : PathSafety.Unknown; } @@ -316,9 +329,170 @@ private static PathSafety ClassifyPathCore( return ClassifyCombine(combine, model, pathTypes, cancellationToken); } - return IsParameterOrMemberRead(unwrapped, model, cancellationToken) - ? PathSafety.Unsafe - : PathSafety.Unknown; + return ClassifyParameterOrMember( + unwrapped, + model, + pathTypes, + directoryInfoTypes, + tracedMethods, + cancellationToken); + } + + /// + /// A new DirectoryInfo(path) carries the safety of its argument, so a + /// temp directory keeps its provenance through the wrapper type. Any other shape returns + /// null. + /// + private static PathSafety? ClassifyDirectoryInfoCreation( + ExpressionSyntax expression, + SemanticModel model, + ImmutableArray pathTypes, + ImmutableArray directoryInfoTypes, + HashSet tracedMethods, + CancellationToken cancellationToken) + { + if (expression is not ObjectCreationExpressionSyntax creation + || creation.ArgumentList is not { Arguments.Count: > 0 } creationArguments + || !MetadataTypes.Contains(directoryInfoTypes, model.GetTypeInfo(creation, cancellationToken).Type)) + { + return null; + } + + return ClassifyPath( + creationArguments.Arguments[0].Expression, + model, + pathTypes, + directoryInfoTypes, + tracedMethods, + cancellationToken); + } + + /// + /// Classifies a parameter by its call sites and a field or property read as unsafe. Any + /// other symbol stays unknown. + /// + private static PathSafety ClassifyParameterOrMember( + ExpressionSyntax expression, + SemanticModel model, + ImmutableArray pathTypes, + ImmutableArray directoryInfoTypes, + HashSet tracedMethods, + CancellationToken cancellationToken) + { + return model.GetSymbolInfo(expression, cancellationToken).Symbol switch + { + IParameterSymbol parameter => ClassifyParameter( + parameter, + model, + pathTypes, + directoryInfoTypes, + tracedMethods, + cancellationToken), + IFieldSymbol or IPropertySymbol => PathSafety.Unsafe, + _ => PathSafety.Unknown + }; + } + + /// + /// A private helper takes its safety from every argument its call sites pass. The rule + /// trusts the parameter only when a call site exists and every argument is safe. A method + /// that is not private, a type split across files, or a method with no visible call site + /// stays unsafe, because the rule cannot prove what the parameter holds. + /// + private static PathSafety ClassifyParameter( + IParameterSymbol parameter, + SemanticModel model, + ImmutableArray pathTypes, + ImmutableArray directoryInfoTypes, + HashSet tracedMethods, + CancellationToken cancellationToken) + { + if (parameter.ContainingSymbol is not IMethodSymbol method + || method.DeclaredAccessibility is not Accessibility.Private + || !tracedMethods.Add(method) + || !IsSinglePartDeclaration(method.ContainingType, model.SyntaxTree)) + { + return PathSafety.Unsafe; + } + + return ClassifyCallSites(method, parameter, model, pathTypes, directoryInfoTypes, tracedMethods, cancellationToken); + } + + private static PathSafety ClassifyCallSites( + IMethodSymbol method, + IParameterSymbol parameter, + SemanticModel model, + ImmutableArray pathTypes, + ImmutableArray directoryInfoTypes, + HashSet tracedMethods, + CancellationToken cancellationToken) + { + var foundCall = false; + var result = PathSafety.Safe; + + foreach (var declaration in method.ContainingType.DeclaringSyntaxReferences) + { + if (declaration.GetSyntax(cancellationToken) is not TypeDeclarationSyntax typeDeclaration) + { + continue; + } + + foreach (var invocation in typeDeclaration.DescendantNodes().OfType()) + { + if (FindCallArgument(invocation, method, parameter, model, cancellationToken) is not { } argument) + { + continue; + } + + foundCall = true; + var argumentSafety = ClassifyPath( + argument, + model, + pathTypes, + directoryInfoTypes, + tracedMethods, + cancellationToken); + + if (argumentSafety is PathSafety.Unsafe) + { + return PathSafety.Unsafe; + } + + if (argumentSafety is not PathSafety.Safe) + { + result = PathSafety.Unknown; + } + } + } + + return foundCall ? result : PathSafety.Unsafe; + } + + private static ExpressionSyntax? FindCallArgument( + InvocationExpressionSyntax invocation, + IMethodSymbol method, + IParameterSymbol parameter, + SemanticModel model, + CancellationToken cancellationToken) + { + return SymbolEqualityComparer.Default.Equals( + model.GetSymbolInfo(invocation, cancellationToken).Symbol, + method) + ? FindArgument(invocation, method, parameter.Ordinal) + : null; + } + + private static bool IsSinglePartDeclaration(INamedTypeSymbol type, SyntaxTree tree) + { + foreach (var reference in type.DeclaringSyntaxReferences) + { + if (reference.SyntaxTree != tree) + { + return false; + } + } + + return true; } // Path.Combine(first, ...) takes its safety from the first argument. diff --git a/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerTests.cs b/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerTests.cs index 2685c80..18d217a 100644 --- a/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerTests.cs @@ -221,6 +221,46 @@ async Task M(HttpResponseMessage response) """); } + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheBodyIsBufferedWithACapAndToken() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + class C + { + async Task M(HttpResponseMessage response, CancellationToken token) + { + await response.Content.LoadIntoBufferAsync(4096, token); + _ = await response.Content.ReadAsStringAsync(token); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenLoadIntoBufferAsyncCarriesOnlyAToken() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + class C + { + async Task M(HttpResponseMessage response, CancellationToken token) + { + await response.Content.LoadIntoBufferAsync(token); + _ = await {|E128227:response.Content.ReadAsStringAsync()|}; + } + } + """); + } + [Fact] [Trait("Category", "CI")] public Task Silent_WhenTheTypeSetsMaxResponseContentBufferSize() diff --git a/tests/E128.Analyzers.Tests/RecursiveDeleteRootAnalyzerTests.cs b/tests/E128.Analyzers.Tests/RecursiveDeleteRootAnalyzerTests.cs index d567ec3..f40c223 100644 --- a/tests/E128.Analyzers.Tests/RecursiveDeleteRootAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/RecursiveDeleteRootAnalyzerTests.cs @@ -566,4 +566,81 @@ void M() } """); } + + [Fact] + [Trait("Category", "CI")] + public Task HelperOverTempDirectory_DoesNotFire() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + void M() + { + var tempDir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), "harvest")); + DeleteTempDirectory(tempDir); + } + + private static void DeleteTempDirectory(DirectoryInfo directory) + { + directory.Delete(true); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task HelperPassedAParameter_Fires() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + void M(string path) + { + DeleteTempDirectory(path); + } + + private static void DeleteTempDirectory(string directory) + { + {|E128184:Directory.Delete(directory, true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task DirectoryInfoOverRootedLiteral_Fires() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + void M() + { + var directory = new DirectoryInfo("/etc/nginx"); + {|E128184:directory.Delete(true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task DirectoryInfoOverTempPath_DoesNotFire() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + void M() + { + var directory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), "harvest")); + directory.Delete(true); + } + } + """); + } }