Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using HotChocolate.Configuration;
Expand All @@ -8,11 +9,19 @@
using HotChocolate.Types.Relay;
using HotChocolate.Utilities;
using static HotChocolate.Authorization.AuthorizeDirectiveType.Names;
using static HotChocolate.Authorization.Properties.AuthCoreResources;

namespace HotChocolate.Authorization;

internal sealed partial class AuthorizationTypeInterceptor : TypeInterceptor
{
private const string AspNetCoreAuthorizeAttributeName = "Microsoft.AspNetCore.Authorization.AuthorizeAttribute";
private const string AspNetCoreAllowAnonymousAttributeName =
"Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute";

private static readonly string s_authorizeAttributeName = typeof(AuthorizeAttribute).FullName!;
private static readonly string s_allowAnonymousAttributeName = typeof(AllowAnonymousAttribute).FullName!;

private readonly List<ObjectTypeInfo> _objectTypes = [];
private readonly List<UnionTypeInfo> _unionTypes = [];
private readonly Dictionary<ObjectType, DirectiveCollection> _directives = [];
Expand Down Expand Up @@ -121,14 +130,79 @@ public override void OnBeforeCompleteMetadata(
ITypeCompletionContext completionContext,
TypeSystemConfiguration configuration)
{
if (configuration is not ObjectTypeConfiguration typeDef)
{
return;
}

// last in the initialization we need to intercept the query type and ensure that
// authorization configuration is applied to the special introspection and node fields.
if (ReferenceEquals(_queryContext, completionContext) &&
configuration is ObjectTypeConfiguration typeDef)
if (ReferenceEquals(_queryContext, completionContext))
{
var state = _state ?? throw ThrowHelper.StateNotInitialized();
HandleSpecialQueryFields(new ObjectTypeInfo(completionContext, typeDef), state);
}

if (_context.Options.ErrorOnAspNetCoreAuthorizationAttributes && !completionContext.IsIntrospectionType)
{
var runtimeType = typeDef.RuntimeType;
var attributesOnType = runtimeType.GetCustomAttributes().ToArray();

if (ContainsNamedAttribute(attributesOnType, AspNetCoreAuthorizeAttributeName))
{
completionContext.ReportError(
UnsupportedAspNetCoreAttributeError(
AspNetCoreAuthorizeAttributeName,
s_authorizeAttributeName,
runtimeType));
return;
}

if (ContainsNamedAttribute(attributesOnType, AspNetCoreAllowAnonymousAttributeName))
{
completionContext.ReportError(
UnsupportedAspNetCoreAttributeError(
AspNetCoreAllowAnonymousAttributeName,
s_allowAnonymousAttributeName,
runtimeType));
return;
}

foreach (var field in typeDef.Fields)
{
if (field.IsIntrospectionField)
{
continue;
}

var fieldMember = field.ResolverMember ?? field.Member;

if (fieldMember is not null)
{
var attributesOnResolver = fieldMember.GetCustomAttributes().ToArray();

if (ContainsNamedAttribute(attributesOnResolver, AspNetCoreAuthorizeAttributeName))
{
completionContext.ReportError(
UnsupportedAspNetCoreAttributeError(
AspNetCoreAuthorizeAttributeName,
s_authorizeAttributeName,
fieldMember));
return;
}

if (ContainsNamedAttribute(attributesOnResolver, AspNetCoreAllowAnonymousAttributeName))
{
completionContext.ReportError(
UnsupportedAspNetCoreAttributeError(
AspNetCoreAllowAnonymousAttributeName,
s_allowAnonymousAttributeName,
fieldMember));
return;
}
}
}
}
}

public override void OnAfterMakeExecutable()
Expand Down Expand Up @@ -620,6 +694,36 @@ private static bool IsAuthorizedType<T>(T definition)

private State CreateState()
=> new(_context.GetAuthorizationOptions());

private static bool ContainsNamedAttribute(Attribute[] attributes, string nameOfAttribute)
=> attributes.Any(a => a.GetType().FullName == nameOfAttribute);

private static ISchemaError UnsupportedAspNetCoreAttributeError(
string aspNetCoreAttributeName,
string properAttributeName,
Type runtimeType)
{
return SchemaErrorBuilder.New()
.SetMessage(string.Format(AuthorizationTypeInterceptor_UnsupportedAspNetCoreAttributeOnType,
aspNetCoreAttributeName, runtimeType.FullName, properAttributeName))
.SetCode(ErrorCodes.Schema.UnsupportedAspNetCoreAuthorizationAttribute)
.Build();
}

private static ISchemaError UnsupportedAspNetCoreAttributeError(
string aspNetCoreAttributeName,
string properAttributeName,
MemberInfo member)
{
var nameOfDeclaringType = member.DeclaringType?.FullName;
var nameOfMember = member.Name;

return SchemaErrorBuilder.New()
.SetMessage(string.Format(AuthorizationTypeInterceptor_UnsupportedAspNetCoreAttributeOnMember,
aspNetCoreAttributeName, nameOfDeclaringType, nameOfMember, properAttributeName))
.SetCode(ErrorCodes.Schema.UnsupportedAspNetCoreAuthorizationAttribute)
.Build();
}
}

file static class AuthorizationTypeInterceptorExtensions
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,10 @@
<data name="ThrowHelper_UnableToResolveTypeReg" xml:space="preserve">
<value>Unable to resolve a type registration.</value>
</data>
<data name="AuthorizationTypeInterceptor_UnsupportedAspNetCoreAttributeOnType" xml:space="preserve">
<value>Found unsupported `{0}` on `{1}`. Use `{2}` instead.</value>
</data>
<data name="AuthorizationTypeInterceptor_UnsupportedAspNetCoreAttributeOnMember" xml:space="preserve">
<value>Found unsupported `{0}` on `{1}.{2}`. Use `{3}` instead.</value>
</data>
</root>
6 changes: 6 additions & 0 deletions src/HotChocolate/Core/src/Types/IReadOnlySchemaOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,4 +207,10 @@ public interface IReadOnlySchemaOptions
/// to the DataLoader promise cache.
/// </summary>
bool PublishRootFieldPagesToPromiseCache { get; }

/// <summary>
/// Errors if either an ASP.NET Core [Authorize] or [AllowAnonymous] attribute
/// is used on a Hot Chocolate resolver or type definition.
/// </summary>
bool ErrorOnAspNetCoreAuthorizationAttributes { get; }
}
6 changes: 5 additions & 1 deletion src/HotChocolate/Core/src/Types/SchemaOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ public FieldBindingFlags DefaultFieldBindingFlags
/// <inheritdoc cref="IReadOnlySchemaOptions.PublishRootFieldPagesToPromiseCache"/>
public bool PublishRootFieldPagesToPromiseCache { get; set; } = true;

/// <inheritdoc cref="IReadOnlySchemaOptions.ErrorOnAspNetCoreAuthorizationAttributes"/>
public bool ErrorOnAspNetCoreAuthorizationAttributes { get; set; } = true;

/// <summary>
/// Creates a mutable options object from a read-only options object.
/// </summary>
Expand Down Expand Up @@ -175,7 +178,8 @@ public static SchemaOptions FromOptions(IReadOnlySchemaOptions options)
StripLeadingIFromInterface = options.StripLeadingIFromInterface,
EnableTag = options.EnableTag,
DefaultQueryDependencyInjectionScope = options.DefaultQueryDependencyInjectionScope,
DefaultMutationDependencyInjectionScope = options.DefaultMutationDependencyInjectionScope
DefaultMutationDependencyInjectionScope = options.DefaultMutationDependencyInjectionScope,
ErrorOnAspNetCoreAuthorizationAttributes = options.ErrorOnAspNetCoreAuthorizationAttributes
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,78 @@ public async Task Skip_After_Validation_For_Null()
""");
}

[Fact]
public async Task Microsoft_AuthorizeAttribute_On_Method_Produces_Error()
{
var builder = new ServiceCollection()
.AddGraphQL()
.AddQueryType<QueryWithMicrosoftAuthorizeAttributeOnMethod>()
.AddAuthorizationCore();

var act = async () => await builder.BuildSchemaAsync();

var exception = await Assert.ThrowsAsync<SchemaException>(act);
var error = exception.Errors.First();
Assert.Equal(ErrorCodes.Schema.UnsupportedAspNetCoreAuthorizationAttribute, error.Code);
Assert.Equal(
"Found unsupported `Microsoft.AspNetCore.Authorization.AuthorizeAttribute` on `HotChocolate.Authorization.AnnotationBasedAuthorizationTests+QueryWithMicrosoftAuthorizeAttributeOnMethod.Field`. Use `HotChocolate.Authorization.AuthorizeAttribute` instead.",
error.Message);
}

[Fact]
public async Task Microsoft_AllowAnonymousAttribute_On_Method_Produces_Error()
{
var builder = new ServiceCollection()
.AddGraphQL()
.AddQueryType<QueryWithMicrosoftAllowAnonymousAttributeOnMethod>()
.AddAuthorizationCore();

var act = async () => await builder.BuildSchemaAsync();

var exception = await Assert.ThrowsAsync<SchemaException>(act);
var error = exception.Errors.First();
Assert.Equal(ErrorCodes.Schema.UnsupportedAspNetCoreAuthorizationAttribute, error.Code);
Assert.Equal(
"Found unsupported `Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute` on `HotChocolate.Authorization.AnnotationBasedAuthorizationTests+QueryWithMicrosoftAllowAnonymousAttributeOnMethod.Field`. Use `HotChocolate.Authorization.AllowAnonymousAttribute` instead.",
error.Message);
}

[Fact]
public async Task Microsoft_AuthorizeAttribute_On_Type_Produces_Error()
{
var builder = new ServiceCollection()
.AddGraphQL()
.AddQueryType<QueryWithMicrosoftAuthorizeAttribute>()
.AddAuthorizationCore();

var act = async () => await builder.BuildSchemaAsync();

var exception = await Assert.ThrowsAsync<SchemaException>(act);
var error = exception.Errors.First();
Assert.Equal(ErrorCodes.Schema.UnsupportedAspNetCoreAuthorizationAttribute, error.Code);
Assert.Equal(
"Found unsupported `Microsoft.AspNetCore.Authorization.AuthorizeAttribute` on `HotChocolate.Authorization.AnnotationBasedAuthorizationTests+QueryWithMicrosoftAuthorizeAttribute`. Use `HotChocolate.Authorization.AuthorizeAttribute` instead.",
error.Message);
}

[Fact]
public async Task Microsoft_AllowAnonymousAttribute_On_Type_Produces_Error()
{
var builder = new ServiceCollection()
.AddGraphQL()
.AddQueryType<QueryWithMicrosoftAllowAnonymousAttribute>()
.AddAuthorizationCore();

var act = async () => await builder.BuildSchemaAsync();

var exception = await Assert.ThrowsAsync<SchemaException>(act);
var error = exception.Errors.First();
Assert.Equal(ErrorCodes.Schema.UnsupportedAspNetCoreAuthorizationAttribute, error.Code);
Assert.Equal(
"Found unsupported `Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute` on `HotChocolate.Authorization.AnnotationBasedAuthorizationTests+QueryWithMicrosoftAllowAnonymousAttribute`. Use `HotChocolate.Authorization.AllowAnonymousAttribute` instead.",
error.Message);
}

private static IServiceProvider CreateServices(
IAuthorizationHandler handler,
Action<AuthorizationOptions>? configure = null)
Expand All @@ -971,6 +1043,30 @@ private static IServiceProvider CreateServices(
.Services
.BuildServiceProvider();

public class QueryWithMicrosoftAuthorizeAttributeOnMethod
{
[Microsoft.AspNetCore.Authorization.Authorize]
public string Field() => "foo";
}

public class QueryWithMicrosoftAllowAnonymousAttributeOnMethod
{
[Microsoft.AspNetCore.Authorization.AllowAnonymous]
public string Field() => "foo";
}

[Microsoft.AspNetCore.Authorization.Authorize]
public class QueryWithMicrosoftAuthorizeAttribute
{
public string Field() => "foo";
}

[Microsoft.AspNetCore.Authorization.AllowAnonymous]
public class QueryWithMicrosoftAllowAnonymousAttribute
{
public string Field() => "foo";
}

[FooDirective]
[Authorize("QUERY", ApplyPolicy.Validation)]
[Authorize("QUERY2", ApplyPolicy.BeforeResolver)]
Expand Down
8 changes: 7 additions & 1 deletion src/HotChocolate/Primitives/src/Primitives/ErrorCodes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,12 @@ public static class Schema
/// The specified directive argument does not exist.
/// </summary>
public const string UnknownDirectiveArgument = "HC0072";

/// <summary>
/// An underlying schema runtime type / member is annotated with a
/// Microsoft.AspNetCore.Authorization.* attribute that is not supported by Hot Chocolate.
/// </summary>
public const string UnsupportedAspNetCoreAuthorizationAttribute = "HC0090";
}

public static class Scalars
Expand All @@ -264,7 +270,7 @@ public static class Scalars

/// <summary>
/// Either the syntax node is invalid when parsing the literal or the syntax
/// node value has an invalid format.
/// node value has an invalid format.`
/// </summary>
public const string InvalidSyntaxFormat = "HC0002";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@ The `@skip` and `@include` directives are now disallowed on root subscription fi

Deprecating a field now requires the implemented field in the interface to also be deprecated, as specified in the [draft specification](https://spec.graphql.org/draft/#sec-Objects.Type-Validation).

## Accidental use of `Microsoft.AspNetCore.Authorization.*` attributes throws an error

Since our authorization attributes (`[Authorize]` and `[AllowAnonymous]`) share the same names as the regular ASP.NET attributes, it's easy to accidentally use the wrong ones.
In the worst-case scenario, this could result in your field or type ending up without any authorization being applied!

To prevent this, we've added a check that throws an error during schema generation if it detects `Microsoft.AspNetCore.Authorization.*` attributes being applied to a GraphQL resolver.

> Note: Keep in mind that your clients might currently rely on the absence of authorization.

You can disable this new validation by setting the `ErrorOnAspNetCoreAuthorizationAttributes` option to `false`:

```csharp
builder.Services.AddGraphQLServer()
.ModifyOptions(options => {
options.ErrorOnAspNetCoreAuthorizationAttributes = false;
})
```

# Deprecations

Things that will continue to function this release, but we encourage you to move away from.
Loading