Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PM-6170] Explore making responses required and nullable #60

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
28 changes: 11 additions & 17 deletions src/Api/SecretsManager/Models/Response/BaseSecretResponseModel.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Bit.Core.Models.Api;
#nullable enable

using Bit.Core.Models.Api;
using Bit.Core.SecretsManager.Entities;

namespace Bit.Api.SecretsManager.Models.Response;
Expand All @@ -24,39 +26,31 @@
Projects = secret.Projects?.Select(p => new SecretResponseInnerProject(p));
}

public BaseSecretResponseModel(string objectName = _objectName) : base(objectName)
{
}

public BaseSecretResponseModel() : base(_objectName)
{
}

public Guid Id { get; set; }
public Guid Id { get; }

public Guid OrganizationId { get; set; }
public Guid OrganizationId { get; }

public string Key { get; set; }
public string? Key { get; }

public string Value { get; set; }
public string? Value { get; }

public string Note { get; set; }
public string? Note { get; }
Comment on lines +33 to +37
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider if these fields should be nullable. If they are required, remove the '?'


public DateTime CreationDate { get; set; }
public DateTime CreationDate { get; }

public DateTime RevisionDate { get; set; }
public DateTime RevisionDate { get; }

public IEnumerable<SecretResponseInnerProject> Projects { get; set; }
public IEnumerable<SecretResponseInnerProject>? Projects { get; init; }
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Using 'init' here might cause issues if Projects need to be modified after initialization


public class SecretResponseInnerProject
{
public SecretResponseInnerProject(Project project)

Check warning on line 47 in src/Api/SecretsManager/Models/Response/BaseSecretResponseModel.cs

View workflow job for this annotation

GitHub Actions / Build artifacts (Api, ./src)

Non-nullable property 'Name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
{
Id = project.Id;
Name = project.Name;

Check warning on line 50 in src/Api/SecretsManager/Models/Response/BaseSecretResponseModel.cs

View workflow job for this annotation

GitHub Actions / Build artifacts (Api, ./src)

Possible null reference assignment.
}

public SecretResponseInnerProject()

Check warning on line 53 in src/Api/SecretsManager/Models/Response/BaseSecretResponseModel.cs

View workflow job for this annotation

GitHub Actions / Build artifacts (Api, ./src)

Non-nullable property 'Name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
{
}

Expand Down
4 changes: 0 additions & 4 deletions src/Api/SecretsManager/Models/Response/SecretResponseModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ public SecretResponseModel(Secret secret, bool read, bool write) : base(secret,
Write = write;
}

public SecretResponseModel() : base(_objectName)
{
}

public bool Read { get; set; }

public bool Write { get; set; }
Expand Down
1 change: 1 addition & 0 deletions src/Api/Utilities/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public static void AddSwagger(this IServiceCollection services, GlobalSettings g
// config.UseReferencedDefinitionsForEnums();

config.SchemaFilter<EnumSchemaFilter>();
config.SchemaFilter<RequireNotNullableSchemaFilter>();

var apiFilePath = Path.Combine(AppContext.BaseDirectory, "Api.xml");
config.IncludeXmlComments(apiFilePath, true);
Expand Down
66 changes: 66 additions & 0 deletions src/SharedWeb/Swagger/RequireNotNullableSchemaFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System.Reflection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Bit.SharedWeb.Swagger;

/// <summary>
///
/// </summary>
Comment on lines +7 to +9
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Add a brief description of the class's purpose in the summary

/// <remarks>
/// Credits: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/2036#issuecomment-894015122
/// </remarks>
public class RequireNotNullableSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema.Properties == null)
{
return;
}

FixNullableProperties(schema, context);

var notNullableProperties = schema
.Properties
.Where(x => !x.Value.Nullable && x.Value.Default == default && !schema.Required.Contains(x.Key))
.ToList();
Comment on lines +24 to +27
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider using HashSet<string> for schema.Required to improve lookup performance


foreach (var property in notNullableProperties)
{
schema.Required.Add(property.Key);
}
}

/// <summary>
/// Option "SupportNonNullableReferenceTypes" not working with complex types ({ "type": "object" }),
/// so they always have "Nullable = false",
/// see method "SchemaGenerator.GenerateSchemaForMember"
/// </summary>
private static void FixNullableProperties(OpenApiSchema schema, SchemaFilterContext context)
{
foreach (var property in schema.Properties)
{
var field = context.Type
.GetMembers(BindingFlags.Public | BindingFlags.Instance)
.FirstOrDefault(x =>
string.Equals(x.Name, property.Key, StringComparison.InvariantCultureIgnoreCase));

if (field == null)
{
continue;
}

var fieldType = field switch
{
FieldInfo fieldInfo => fieldInfo.FieldType,
PropertyInfo propertyInfo => propertyInfo.PropertyType,
_ => throw new NotSupportedException(),
};
Comment on lines +54 to +59
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Handle potential NotSupportedException to prevent unexpected runtime errors


property.Value.Nullable = fieldType.IsValueType
? Nullable.GetUnderlyingType(fieldType) != null
: !field.IsNonNullableReferenceType();
}
}
}
Loading