diff --git a/.editorconfig b/.editorconfig index 32314fd23..09294cd3e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -128,6 +128,24 @@ dotnet_diagnostic.CA1822.severity = suggestion # IDE0080: Remove unnecessary suppression operator dotnet_diagnostic.IDE0080.severity = error +# CA1716: Rename namespace "" so that it no longer conflicts with the reserved language keyword 'Interface' +# TODO: fixing this would be breaking +dotnet_diagnostic.CA1716.severity = suggestion + +# CA1805: Do not initialize unnecessarily +dotnet_diagnostic.CA1805.severity = suggestion + +# CA1711: Identifiers should not have incorrect suffix +# TODO: fixing this would be breaking +dotnet_diagnostic.CA1711.severity = suggestion + +# CA2201: Do not raise reserved exception types +dotnet_diagnostic.CA2201.severity = suggestion + +# CA1720: Identifier contains type name +# TODO: fixing this would be breaking +dotnet_diagnostic.CA1720.severity = suggestion + [Program.cs] dotnet_diagnostic.CA1050.severity = none dotnet_diagnostic.S1118.severity = none diff --git a/src/Altinn.App.Api/Controllers/ApplicationMetadataController.cs b/src/Altinn.App.Api/Controllers/ApplicationMetadataController.cs index 02d86b06e..386d4c714 100644 --- a/src/Altinn.App.Api/Controllers/ApplicationMetadataController.cs +++ b/src/Altinn.App.Api/Controllers/ApplicationMetadataController.cs @@ -47,7 +47,7 @@ public async Task> GetAction( string wantedAppId = $"{org}/{app}"; - if (!checkOrgApp || application.Id.Equals(wantedAppId)) + if (!checkOrgApp || application.Id.Equals(wantedAppId, StringComparison.Ordinal)) { return Ok(application); } @@ -72,7 +72,7 @@ public async Task> GetPolicy(string org, string app) string policy = await _appMetadata.GetApplicationXACMLPolicy(); string wantedAppId = $"{org}/{app}"; - if (application.Id.Equals(wantedAppId)) + if (application.Id.Equals(wantedAppId, StringComparison.Ordinal)) { return Content(policy, "text/xml", System.Text.Encoding.UTF8); } @@ -100,7 +100,7 @@ public async Task> GetProcess(string org, string app) string wantedAppId = $"{org}/{app}"; try { - if (application.Id.Equals(wantedAppId)) + if (application.Id.Equals(wantedAppId, StringComparison.Ordinal)) { string process = await _appMetadata.GetApplicationBPMNProcess(); return Content(process, "text/xml", System.Text.Encoding.UTF8); diff --git a/src/Altinn.App.Api/Controllers/AuthorizationController.cs b/src/Altinn.App.Api/Controllers/AuthorizationController.cs index 13f4e04cc..7590e0dfc 100644 --- a/src/Altinn.App.Api/Controllers/AuthorizationController.cs +++ b/src/Altinn.App.Api/Controllers/AuthorizationController.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Altinn.App.Core.Configuration; using Altinn.App.Core.Helpers; using Altinn.App.Core.Internal.Auth; @@ -83,7 +84,7 @@ public async Task GetCurrentParty(bool returnPartyObject = false) { Response.Cookies.Append( _settings.GetAltinnPartyCookieName, - userContext.PartyId.ToString(), + userContext.PartyId.ToString(CultureInfo.InvariantCulture), new CookieOptions { Domain = _settings.HostName } ); } diff --git a/src/Altinn.App.Api/Controllers/DataController.cs b/src/Altinn.App.Api/Controllers/DataController.cs index 4f51ea025..fe709a6e9 100644 --- a/src/Altinn.App.Api/Controllers/DataController.cs +++ b/src/Altinn.App.Api/Controllers/DataController.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Net; using System.Security.Claims; using System.Text.Json; @@ -133,7 +134,7 @@ [FromQuery] string dataType Application application = await _appMetadata.GetApplicationMetadata(); DataType? dataTypeFromMetadata = application.DataTypes.First(e => - e.Id.Equals(dataType, StringComparison.InvariantCultureIgnoreCase) + e.Id.Equals(dataType, StringComparison.OrdinalIgnoreCase) ); if (dataTypeFromMetadata == null) @@ -302,7 +303,9 @@ public async Task Get( return NotFound($"Did not find instance {instance}"); } - DataElement? dataElement = instance.Data.First(m => m.Id.Equals(dataGuid.ToString())); + DataElement? dataElement = instance.Data.First(m => + m.Id.Equals(dataGuid.ToString(), StringComparison.Ordinal) + ); if (dataElement == null) { @@ -380,7 +383,9 @@ public async Task Put( ); } - DataElement? dataElement = instance.Data.First(m => m.Id.Equals(dataGuid.ToString())); + DataElement? dataElement = instance.Data.First(m => + m.Id.Equals(dataGuid.ToString(), StringComparison.Ordinal) + ); if (dataElement == null) { @@ -459,7 +464,7 @@ public async Task> PatchFormData( ); } - var dataElement = instance.Data.First(m => m.Id.Equals(dataGuid.ToString())); + var dataElement = instance.Data.First(m => m.Id.Equals(dataGuid.ToString(), StringComparison.Ordinal)); if (dataElement == null) { @@ -547,7 +552,9 @@ [FromRoute] Guid dataGuid ); } - DataElement? dataElement = instance.Data.Find(m => m.Id.Equals(dataGuid.ToString())); + DataElement? dataElement = instance.Data.Find(m => + m.Id.Equals(dataGuid.ToString(), StringComparison.Ordinal) + ); if (dataElement == null) { @@ -604,7 +611,7 @@ private async Task CreateBinaryData( Stream fileStream ) { - int instanceOwnerPartyId = int.Parse(instanceBefore.Id.Split("/")[0]); + int instanceOwnerPartyId = int.Parse(instanceBefore.Id.Split("/")[0], CultureInfo.InvariantCulture); Guid instanceGuid = Guid.Parse(instanceBefore.Id.Split("/")[1]); DataElement dataElement = await _dataClient.InsertBinaryData( @@ -655,7 +662,7 @@ private async Task CreateAppModelData(string org, string app, Inst await UpdatePresentationTextsOnInstance(instance, dataType, appModel); await UpdateDataValuesOnInstance(instance, dataType, appModel); - int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); + int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture); ObjectUtils.InitializeAltinnRowId(appModel); ObjectUtils.PrepareModelForXmlStorage(appModel); @@ -692,7 +699,7 @@ DataElement dataElement if (dataStream != null) { string? userOrgClaim = User.GetOrg(); - if (userOrgClaim == null || !org.Equals(userOrgClaim, StringComparison.InvariantCultureIgnoreCase)) + if (userOrgClaim == null || !org.Equals(userOrgClaim, StringComparison.OrdinalIgnoreCase)) { await _instanceClient.UpdateReadStatus(instanceOwnerPartyId, instanceGuid, "read"); } @@ -822,7 +829,7 @@ await _dataClient.UpdateData( // This is likely not required as the instance is already read string? userOrgClaim = User.GetOrg(); - if (userOrgClaim == null || !org.Equals(userOrgClaim, StringComparison.InvariantCultureIgnoreCase)) + if (userOrgClaim == null || !org.Equals(userOrgClaim, StringComparison.OrdinalIgnoreCase)) { await _instanceClient.UpdateReadStatus(instanceOwnerId, instanceGuid, "read"); } @@ -860,7 +867,7 @@ private async Task PutFormData( string? language ) { - int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); + int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture); string classRef = dataType.AppLogic.ClassRef; Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); @@ -928,7 +935,7 @@ private async Task UpdatePresentationTextsOnInstance(Instance instance, string d if (updatedValues.Count > 0) { await _instanceClient.UpdatePresentationTexts( - int.Parse(instance.Id.Split("/")[0]), + int.Parse(instance.Id.Split("/")[0], CultureInfo.InvariantCulture), Guid.Parse(instance.Id.Split("/")[1]), new PresentationTexts { Texts = updatedValues } ); @@ -947,7 +954,7 @@ private async Task UpdateDataValuesOnInstance(Instance instance, string dataType if (updatedValues.Count > 0) { await _instanceClient.UpdateDataValues( - int.Parse(instance.Id.Split("/")[0]), + int.Parse(instance.Id.Split("/")[0], CultureInfo.InvariantCulture), Guid.Parse(instance.Id.Split("/")[1]), new DataValues { Values = updatedValues } ); @@ -996,7 +1003,7 @@ private static bool IsValidContributer(DataType dataType, ClaimsPrincipal user) string key = item.Split(':')[0]; string value = item.Split(':')[1]; - switch (key.ToLower()) + switch (key.ToLowerInvariant()) { case "org": if (value.Equals(user.GetOrg(), StringComparison.OrdinalIgnoreCase)) @@ -1006,7 +1013,12 @@ private static bool IsValidContributer(DataType dataType, ClaimsPrincipal user) break; case "orgno": - if (value.Equals(user.GetOrgNumber().ToString())) + if ( + value.Equals( + user.GetOrgNumber()?.ToString(CultureInfo.InvariantCulture), + StringComparison.Ordinal + ) + ) { return true; } diff --git a/src/Altinn.App.Api/Controllers/DataTagsController.cs b/src/Altinn.App.Api/Controllers/DataTagsController.cs index 9b9116984..1a13dc698 100644 --- a/src/Altinn.App.Api/Controllers/DataTagsController.cs +++ b/src/Altinn.App.Api/Controllers/DataTagsController.cs @@ -61,7 +61,9 @@ [FromRoute] Guid dataGuid return NotFound($"Unable to find instance based on the given parameters."); } - DataElement? dataElement = instance.Data.FirstOrDefault(m => m.Id.Equals(dataGuid.ToString())); + DataElement? dataElement = instance.Data.FirstOrDefault(m => + m.Id.Equals(dataGuid.ToString(), StringComparison.Ordinal) + ); if (dataElement == null) { @@ -106,7 +108,9 @@ [FromBody] string tag return NotFound("Unable to find instance based on the given parameters."); } - DataElement? dataElement = instance.Data.FirstOrDefault(m => m.Id.Equals(dataGuid.ToString())); + DataElement? dataElement = instance.Data.FirstOrDefault(m => + m.Id.Equals(dataGuid.ToString(), StringComparison.Ordinal) + ); if (dataElement == null) { @@ -160,7 +164,9 @@ [FromRoute] string tag return NotFound("Unable to find instance based on the given parameters."); } - DataElement? dataElement = instance.Data.FirstOrDefault(m => m.Id.Equals(dataGuid.ToString())); + DataElement? dataElement = instance.Data.FirstOrDefault(m => + m.Id.Equals(dataGuid.ToString(), StringComparison.Ordinal) + ); if (dataElement == null) { diff --git a/src/Altinn.App.Api/Controllers/InstancesController.cs b/src/Altinn.App.Api/Controllers/InstancesController.cs index cdf5651c9..66aa24586 100644 --- a/src/Altinn.App.Api/Controllers/InstancesController.cs +++ b/src/Altinn.App.Api/Controllers/InstancesController.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Net; using System.Text; using Altinn.App.Api.Helpers.RequestHandling; @@ -146,7 +147,7 @@ [FromRoute] Guid instanceGuid string? userOrgClaim = User.GetOrg(); - if (userOrgClaim == null || !org.Equals(userOrgClaim, StringComparison.InvariantCultureIgnoreCase)) + if (userOrgClaim == null || !org.Equals(userOrgClaim, StringComparison.OrdinalIgnoreCase)) { await _instanceClient.UpdateReadStatus(instanceOwnerPartyId, instanceGuid, "read"); } @@ -239,7 +240,10 @@ [FromQuery] int? instanceOwnerPartyId // create minimum instance template instanceTemplate = new Instance { - InstanceOwner = new InstanceOwner { PartyId = instanceOwnerPartyId.Value.ToString() } + InstanceOwner = new InstanceOwner + { + PartyId = instanceOwnerPartyId.Value.ToString(CultureInfo.InvariantCulture) + } }; } @@ -331,7 +335,7 @@ [FromQuery] int? instanceOwnerPartyId instance = await _instanceClient.GetInstance( app, org, - int.Parse(instance.InstanceOwner.PartyId), + int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture), Guid.Parse(instance.Id.Split("/")[1]) ); @@ -425,7 +429,11 @@ [FromBody] InstansiationInstance instansiationInstance return NotFound($"Cannot lookup party: {partyLookupException.Message}"); } - if (copySourceInstance && party.PartyId.ToString() != instansiationInstance.SourceInstanceId.Split("/")[0]) + if ( + copySourceInstance + && party.PartyId.ToString(CultureInfo.InvariantCulture) + != instansiationInstance.SourceInstanceId.Split("/")[0] + ) { return BadRequest("It is not possible to copy instances between instance owners."); } @@ -705,7 +713,7 @@ [FromBody] Substatus substatus Instance instance = await _instanceClient.GetInstance(app, org, instanceOwnerPartyId, instanceGuid); string? orgClaim = User.GetOrg(); - if (!instance.Org.Equals(orgClaim)) + if (!instance.Org.Equals(orgClaim, StringComparison.OrdinalIgnoreCase)) { return Forbid(); } @@ -783,7 +791,7 @@ int instanceOwnerPartyId new() { { "appId", $"{org}/{app}" }, - { "instanceOwner.partyId", instanceOwnerPartyId.ToString() }, + { "instanceOwner.partyId", instanceOwnerPartyId.ToString(CultureInfo.InvariantCulture) }, { "status.isArchived", "false" }, { "status.isSoftDeleted", "false" } }; @@ -863,14 +871,17 @@ Instance sourceInstance { string org = application.Org; string app = application.AppIdentifier.App; - int instanceOwnerPartyId = int.Parse(targetInstance.InstanceOwner.PartyId); + int instanceOwnerPartyId = int.Parse(targetInstance.InstanceOwner.PartyId, CultureInfo.InvariantCulture); string[] sourceSplit = sourceInstance.Id.Split("/"); Guid sourceInstanceGuid = Guid.Parse(sourceSplit[1]); List dts = application .DataTypes.Where(dt => dt.AppLogic?.ClassRef != null) - .Where(dt => dt.TaskId != null && dt.TaskId.Equals(targetInstance.Process.CurrentTask.ElementId)) + .Where(dt => + dt.TaskId != null + && dt.TaskId.Equals(targetInstance.Process.CurrentTask.ElementId, StringComparison.Ordinal) + ) .ToList(); List excludedDataTypes = application.CopyInstanceSettings.ExcludedDataTypes; @@ -881,9 +892,9 @@ Instance sourceInstance continue; } - if (dts.Any(dts => dts.Id.Equals(de.DataType))) + if (dts.Any(dts => dts.Id.Equals(de.DataType, StringComparison.Ordinal))) { - DataType dt = dts.First(dt => dt.Id.Equals(de.DataType)); + DataType dt = dts.First(dt => dt.Id.Equals(de.DataType, StringComparison.Ordinal)); Type type; try @@ -913,7 +924,11 @@ Instance sourceInstance DataHelper.ResetDataFields(application.CopyInstanceSettings.ExcludedDataFields, data); } - await _prefillService.PrefillDataModel(instanceOwnerPartyId.ToString(), dt.Id, data); + await _prefillService.PrefillDataModel( + instanceOwnerPartyId.ToString(CultureInfo.InvariantCulture), + dt.Id, + data + ); await _instantiationProcessor.DataCreation(targetInstance, data, null); @@ -998,7 +1013,9 @@ string action { try { - return await _altinnPartyClientClient.GetParty(int.Parse(instanceOwner.PartyId)); + return await _altinnPartyClientClient.GetParty( + int.Parse(instanceOwner.PartyId, CultureInfo.InvariantCulture) + ); } catch (Exception e) when (e is not ServiceException) { @@ -1058,7 +1075,7 @@ string action private async Task StorePrefillParts(Instance instance, ApplicationMetadata appInfo, List parts) { Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); - int instanceOwnerIdAsInt = int.Parse(instance.InstanceOwner.PartyId); + int instanceOwnerIdAsInt = int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture); string org = instance.Org; string app = instance.AppId.Split("/")[1]; @@ -1219,7 +1236,7 @@ object data if (updatedValues.Count > 0) { await _instanceClient.UpdatePresentationTexts( - int.Parse(instance.Id.Split("/")[0]), + int.Parse(instance.Id.Split("/")[0], CultureInfo.InvariantCulture), Guid.Parse(instance.Id.Split("/")[1]), new PresentationTexts { Texts = updatedValues } ); @@ -1238,7 +1255,7 @@ object data if (updatedValues.Count > 0) { await _instanceClient.UpdateDataValues( - int.Parse(instance.Id.Split("/")[0]), + int.Parse(instance.Id.Split("/")[0], CultureInfo.InvariantCulture), Guid.Parse(instance.Id.Split("/")[1]), new DataValues { Values = updatedValues } ); diff --git a/src/Altinn.App.Api/Controllers/PartiesController.cs b/src/Altinn.App.Api/Controllers/PartiesController.cs index 39ce416bb..0fe5ff7d9 100644 --- a/src/Altinn.App.Api/Controllers/PartiesController.cs +++ b/src/Altinn.App.Api/Controllers/PartiesController.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Altinn.App.Core.Configuration; using Altinn.App.Core.Helpers; using Altinn.App.Core.Internal.App; @@ -167,7 +168,7 @@ public async Task UpdateSelectedParty(int partyId) Response.Cookies.Append( _settings.GetAltinnPartyCookieName, - partyId.ToString(), + partyId.ToString(CultureInfo.InvariantCulture), new CookieOptions { Domain = _settings.HostName } ); diff --git a/src/Altinn.App.Api/Controllers/PdfController.cs b/src/Altinn.App.Api/Controllers/PdfController.cs index 29434aabb..433849140 100644 --- a/src/Altinn.App.Api/Controllers/PdfController.cs +++ b/src/Altinn.App.Api/Controllers/PdfController.cs @@ -132,7 +132,7 @@ [FromRoute] Guid dataGuid JsonSerializer.Deserialize(layoutSetsString, _jsonSerializerOptions) ?? throw new JsonException("Could not deserialize LayoutSets"); layoutSet = layoutSets.Sets?.FirstOrDefault(t => - t.DataType.Equals(dataElement.DataType) && t.Tasks.Contains(taskId) + t.DataType.Equals(dataElement.DataType, StringComparison.Ordinal) && t.Tasks.Contains(taskId) ); } diff --git a/src/Altinn.App.Api/Controllers/ProcessController.cs b/src/Altinn.App.Api/Controllers/ProcessController.cs index dc46a040f..5c5099b2b 100644 --- a/src/Altinn.App.Api/Controllers/ProcessController.cs +++ b/src/Altinn.App.Api/Controllers/ProcessController.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Net; using Altinn.App.Api.Infrastructure.Filters; using Altinn.App.Api.Models; @@ -563,7 +564,12 @@ [FromRoute] Guid instanceGuid { try { - return Ok(await _processClient.GetProcessHistory(instanceGuid.ToString(), instanceOwnerPartyId.ToString())); + return Ok( + await _processClient.GetProcessHistory( + instanceGuid.ToString(), + instanceOwnerPartyId.ToString(CultureInfo.InvariantCulture) + ) + ); } catch (PlatformHttpException e) { diff --git a/src/Altinn.App.Api/Controllers/RedirectController.cs b/src/Altinn.App.Api/Controllers/RedirectController.cs index e71dc4bc9..a93ca9bef 100644 --- a/src/Altinn.App.Api/Controllers/RedirectController.cs +++ b/src/Altinn.App.Api/Controllers/RedirectController.cs @@ -80,6 +80,6 @@ private bool IsValidRedirectUri(string urlHost) .ToList(); string redirectHost = string.Join(".", goToList); - return validHost.Equals(redirectHost); + return validHost.Equals(redirectHost, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/Altinn.App.Api/Controllers/StatelessDataController.cs b/src/Altinn.App.Api/Controllers/StatelessDataController.cs index 49df9bd01..7aaa0f322 100644 --- a/src/Altinn.App.Api/Controllers/StatelessDataController.cs +++ b/src/Altinn.App.Api/Controllers/StatelessDataController.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Net; using Altinn.App.Api.Infrastructure.Filters; using Altinn.App.Core.Extensions; @@ -110,7 +111,12 @@ public async Task Get( ); } - EnforcementResult enforcementResult = await AuthorizeAction(org, app, Convert.ToInt32(owner.PartyId), "read"); + EnforcementResult enforcementResult = await AuthorizeAction( + org, + app, + Convert.ToInt32(owner.PartyId, CultureInfo.InvariantCulture), + "read" + ); if (!enforcementResult.Authorized) { @@ -225,7 +231,12 @@ public async Task Post( return BadRequest($"Invalid party header"); } - EnforcementResult enforcementResult = await AuthorizeAction(org, app, Convert.ToInt32(owner.PartyId), "read"); + EnforcementResult enforcementResult = await AuthorizeAction( + org, + app, + Convert.ToInt32(owner.PartyId, CultureInfo.InvariantCulture), + "read" + ); if (!enforcementResult.Authorized) { diff --git a/src/Altinn.App.Api/Helpers/RequestHandling/MultipartRequestReader.cs b/src/Altinn.App.Api/Helpers/RequestHandling/MultipartRequestReader.cs index a65a81bfa..9aa77216c 100644 --- a/src/Altinn.App.Api/Helpers/RequestHandling/MultipartRequestReader.cs +++ b/src/Altinn.App.Api/Helpers/RequestHandling/MultipartRequestReader.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Altinn.App.Core.Helpers.Extensions; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Net.Http.Headers; @@ -69,13 +70,25 @@ out ContentDispositionHeaderValue? contentDisposition ) ) { - Errors.Add(string.Format("Part number {0} doesn't have a content disposition", partCounter)); + Errors.Add( + string.Format( + CultureInfo.InvariantCulture, + "Part number {0} doesn't have a content disposition", + partCounter + ) + ); continue; } if (section.ContentType == null) { - Errors.Add(string.Format("Part number {0} doesn't have a content type", partCounter)); + Errors.Add( + string.Format( + CultureInfo.InvariantCulture, + "Part number {0} doesn't have a content type", + partCounter + ) + ); continue; } diff --git a/src/Altinn.App.Api/Helpers/RequestHandling/RequestPartValidator.cs b/src/Altinn.App.Api/Helpers/RequestHandling/RequestPartValidator.cs index c52b919dd..ebe525264 100644 --- a/src/Altinn.App.Api/Helpers/RequestHandling/RequestPartValidator.cs +++ b/src/Altinn.App.Api/Helpers/RequestHandling/RequestPartValidator.cs @@ -27,7 +27,7 @@ public RequestPartValidator(Application appInfo) { if (part.Name == "instance") { - if (!part.ContentType.StartsWith("application/json")) + if (!part.ContentType.StartsWith("application/json", StringComparison.Ordinal)) { return $"Unexpected Content-Type '{part.ContentType}' of embedded instance template. Expecting 'application/json'"; } diff --git a/src/Altinn.App.Api/Infrastructure/Telemetry/HealthTelemetryFilter.cs b/src/Altinn.App.Api/Infrastructure/Telemetry/HealthTelemetryFilter.cs index 5b87dd537..1859d8ffd 100644 --- a/src/Altinn.App.Api/Infrastructure/Telemetry/HealthTelemetryFilter.cs +++ b/src/Altinn.App.Api/Infrastructure/Telemetry/HealthTelemetryFilter.cs @@ -37,7 +37,7 @@ private static bool ExcludeItemTelemetry(ITelemetry item) { RequestTelemetry request = item as RequestTelemetry; - if (request != null && request.Url.ToString().EndsWith("/health")) + if (request != null && request.Url.ToString().EndsWith("/health", StringComparison.OrdinalIgnoreCase)) { return true; } diff --git a/src/Altinn.App.Api/Infrastructure/Telemetry/IdentityTelemetryFilter.cs b/src/Altinn.App.Api/Infrastructure/Telemetry/IdentityTelemetryFilter.cs index f0eb983dc..15141dd86 100644 --- a/src/Altinn.App.Api/Infrastructure/Telemetry/IdentityTelemetryFilter.cs +++ b/src/Altinn.App.Api/Infrastructure/Telemetry/IdentityTelemetryFilter.cs @@ -1,5 +1,6 @@ #nullable disable using System.Diagnostics.CodeAnalysis; +using System.Globalization; using Altinn.App.Core.Extensions; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; @@ -42,17 +43,17 @@ public void Process(ITelemetry item) int? partyId = ctx.User.GetPartyIdAsInt(); int authLevel = ctx.User.GetAuthenticationLevel(); - request.Properties.Add("partyId", partyId.ToString()); - request.Properties.Add("authLevel", authLevel.ToString()); + request.Properties.Add("partyId", partyId?.ToString(CultureInfo.InvariantCulture) ?? ""); + request.Properties.Add("authLevel", authLevel.ToString(CultureInfo.InvariantCulture)); if (userId != null) { - request.Properties.Add("userId", userId.ToString()); + request.Properties.Add("userId", userId?.ToString(CultureInfo.InvariantCulture) ?? ""); } if (orgNumber != null) { - request.Properties.Add("orgNumber", orgNumber.ToString()); + request.Properties.Add("orgNumber", orgNumber?.ToString(CultureInfo.InvariantCulture) ?? ""); } } } diff --git a/src/Altinn.App.Core/Configuration/AppSettings.cs b/src/Altinn.App.Core/Configuration/AppSettings.cs index 59c70b419..962226e02 100644 --- a/src/Altinn.App.Core/Configuration/AppSettings.cs +++ b/src/Altinn.App.Core/Configuration/AppSettings.cs @@ -6,6 +6,7 @@ namespace Altinn.App.Core.Configuration; // TODO: IOptions validation so that we know which of these properties are required public class AppSettings { +#pragma warning disable CA1707 // Identifiers should not contain underscores /// /// Constant for the location of json schema file /// @@ -15,6 +16,7 @@ public class AppSettings /// Constant for the location of validation configuration file /// public const string VALIDATION_CONFIG_FILENAME = "validation.json"; +#pragma warning restore CA1707 // Identifiers should not contain underscores /// /// The app configuration baseUrl where files are stored in the container diff --git a/src/Altinn.App.Core/Constants/AuthzConstants.cs b/src/Altinn.App.Core/Constants/AuthzConstants.cs index 97517042d..bd11696f6 100644 --- a/src/Altinn.App.Core/Constants/AuthzConstants.cs +++ b/src/Altinn.App.Core/Constants/AuthzConstants.cs @@ -5,6 +5,7 @@ namespace Altinn.App.Core.Constants; /// public static class AuthzConstants { +#pragma warning disable CA1707 // Identifiers should not contain underscores /// /// Policy tag for reading an instance. /// @@ -24,4 +25,5 @@ public static class AuthzConstants /// Policy tag for authorizing client scope. /// public const string POLICY_INSTANCE_COMPLETE = "InstanceComplete"; +#pragma warning restore CA1707 // Identifiers should not contain underscores } diff --git a/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingService.cs b/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingService.cs index dbe3e2d61..b96fd3748 100644 --- a/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingService.cs +++ b/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingService.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; using Altinn.App.Core.Configuration; using Altinn.App.Core.Constants; using Altinn.App.Core.EFormidling.Interface; @@ -196,7 +197,7 @@ private async Task SendInstanceData(Instance instance, Dictionary GetAltinn2Codelist(string id, string langCode, int? version = null) { var response = await _client.GetAsync( - $"https://www.altinn.no/api/metadata/codelists/{id}/{version?.ToString() ?? string.Empty}?language={langCode}" + $"https://www.altinn.no/api/metadata/codelists/{id}/{version?.ToString(CultureInfo.InvariantCulture) ?? string.Empty}?language={langCode}" ); if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { response = await _client.GetAsync( - $"https://www.altinn.no/api/metadata/codelists/{id}/{version?.ToString() ?? string.Empty}" + $"https://www.altinn.no/api/metadata/codelists/{id}/{version?.ToString(CultureInfo.InvariantCulture) ?? string.Empty}" ); } response.EnsureSuccessStatusCode(); diff --git a/src/Altinn.App.Core/Features/Validation/Helpers/ModelStateHelpers.cs b/src/Altinn.App.Core/Features/Validation/Helpers/ModelStateHelpers.cs index a5ab2fc19..a22871460 100644 --- a/src/Altinn.App.Core/Features/Validation/Helpers/ModelStateHelpers.cs +++ b/src/Altinn.App.Core/Features/Validation/Helpers/ModelStateHelpers.cs @@ -66,7 +66,7 @@ private static (ValidationIssueSeverity Severity, string Message) GetSeverityFro GeneralSettings generalSettings ) { - if (originalMessage.StartsWith(generalSettings.SoftValidationPrefix)) + if (originalMessage.StartsWith(generalSettings.SoftValidationPrefix, StringComparison.Ordinal)) { return ( ValidationIssueSeverity.Warning, @@ -75,7 +75,7 @@ GeneralSettings generalSettings } #pragma warning disable CS0618 // Type or member is obsolete - if (originalMessage.StartsWith(generalSettings.FixedValidationPrefix)) + if (originalMessage.StartsWith(generalSettings.FixedValidationPrefix, StringComparison.Ordinal)) { return ( ValidationIssueSeverity.Fixed, @@ -84,7 +84,7 @@ GeneralSettings generalSettings } #pragma warning restore CS0618 // Type or member is obsolete - if (originalMessage.StartsWith(generalSettings.InfoValidationPrefix)) + if (originalMessage.StartsWith(generalSettings.InfoValidationPrefix, StringComparison.Ordinal)) { return ( ValidationIssueSeverity.Informational, @@ -92,7 +92,7 @@ GeneralSettings generalSettings ); } - if (originalMessage.StartsWith(generalSettings.SuccessValidationPrefix)) + if (originalMessage.StartsWith(generalSettings.SuccessValidationPrefix, StringComparison.Ordinal)) { return ( ValidationIssueSeverity.Success, diff --git a/src/Altinn.App.Core/Helpers/AppTextHelper.cs b/src/Altinn.App.Core/Helpers/AppTextHelper.cs index d441fc2ee..9d0e62d4e 100644 --- a/src/Altinn.App.Core/Helpers/AppTextHelper.cs +++ b/src/Altinn.App.Core/Helpers/AppTextHelper.cs @@ -1,3 +1,5 @@ +using System.Globalization; + namespace Altinn.App.Core.Helpers; /// @@ -37,7 +39,7 @@ string languageId stringList[i] = textParams[i]; } - text = string.Format(text, stringList); + text = string.Format(CultureInfo.InvariantCulture, text, stringList); } } diff --git a/src/Altinn.App.Core/Helpers/AuthenticationHelper.cs b/src/Altinn.App.Core/Helpers/AuthenticationHelper.cs index 8d7a7cc34..f8bd5a49f 100644 --- a/src/Altinn.App.Core/Helpers/AuthenticationHelper.cs +++ b/src/Altinn.App.Core/Helpers/AuthenticationHelper.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Security.Claims; using AltinnCore.Authentication.Constants; using Microsoft.AspNetCore.Http; @@ -22,9 +23,9 @@ public static int GetUserId(HttpContext context) { foreach (Claim claim in context.User.Claims) { - if (claim.Type.Equals(AltinnCoreClaimTypes.UserId)) + if (claim.Type.Equals(AltinnCoreClaimTypes.UserId, StringComparison.Ordinal)) { - userId = Convert.ToInt32(claim.Value); + userId = Convert.ToInt32(claim.Value, CultureInfo.InvariantCulture); } } } diff --git a/src/Altinn.App.Core/Helpers/DataModel/DataModel.cs b/src/Altinn.App.Core/Helpers/DataModel/DataModel.cs index ae7b5a0d6..361d9098a 100644 --- a/src/Altinn.App.Core/Helpers/DataModel/DataModel.cs +++ b/src/Altinn.App.Core/Helpers/DataModel/DataModel.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Reflection; using System.Text.RegularExpressions; @@ -224,7 +225,7 @@ internal static (string key, int? index) ParseKeyPart(string keypart) return (keypart, null); } var match = _keyPartRegex.Match(keypart); - return (match.Groups[1].Value, int.Parse(match.Groups[2].Value)); + return (match.Groups[1].Value, int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture)); } private static void AddIndiciesRecursive( diff --git a/src/Altinn.App.Core/Helpers/InstantiationHelper.cs b/src/Altinn.App.Core/Helpers/InstantiationHelper.cs index f0b31da71..122e9dac6 100644 --- a/src/Altinn.App.Core/Helpers/InstantiationHelper.cs +++ b/src/Altinn.App.Core/Helpers/InstantiationHelper.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Altinn.Platform.Register.Enums; using Altinn.Platform.Register.Models; using Altinn.Platform.Storage.Interface.Models; @@ -110,9 +111,12 @@ public static bool IsPartyAllowedToInstantiate(Party? party, PartyTypesAllowed? bool isSubUnit = party.UnitType != null - && (SUB_UNIT_CODE.Equals(party.UnitType.Trim()) || SUB_UNIT_CODE_AAFY.Equals(party.UnitType.Trim())); + && ( + SUB_UNIT_CODE.Equals(party.UnitType.Trim(), StringComparison.Ordinal) + || SUB_UNIT_CODE_AAFY.Equals(party.UnitType.Trim(), StringComparison.Ordinal) + ); bool isMainUnit = !isSubUnit; - bool isKbo = party.UnitType != null && BANKRUPTCY_CODE.Equals(party.UnitType.Trim()); + bool isKbo = party.UnitType != null && BANKRUPTCY_CODE.Equals(party.UnitType.Trim(), StringComparison.Ordinal); switch (partyType) { @@ -192,19 +196,23 @@ public static InstanceOwner PartyToInstanceOwner(Party party) { if (!string.IsNullOrEmpty(party.SSN)) { - return new() { PartyId = party.PartyId.ToString(), PersonNumber = party.SSN, }; + return new() { PartyId = party.PartyId.ToString(CultureInfo.InvariantCulture), PersonNumber = party.SSN, }; } else if (!string.IsNullOrEmpty(party.OrgNumber)) { - return new() { PartyId = party.PartyId.ToString(), OrganisationNumber = party.OrgNumber, }; + return new() + { + PartyId = party.PartyId.ToString(CultureInfo.InvariantCulture), + OrganisationNumber = party.OrgNumber, + }; } else if (party.PartyTypeName.Equals(PartyType.SelfIdentified)) { - return new() { PartyId = party.PartyId.ToString(), Username = party.Name, }; + return new() { PartyId = party.PartyId.ToString(CultureInfo.InvariantCulture), Username = party.Name, }; } return new() { - PartyId = party.PartyId.ToString(), + PartyId = party.PartyId.ToString(CultureInfo.InvariantCulture), // instanceOwnerPartyType == "unknown" }; } diff --git a/src/Altinn.App.Core/Helpers/JsonSerializerIgnorePrefix.cs b/src/Altinn.App.Core/Helpers/JsonSerializerIgnorePrefix.cs index 79a3c0ec9..81edde649 100644 --- a/src/Altinn.App.Core/Helpers/JsonSerializerIgnorePrefix.cs +++ b/src/Altinn.App.Core/Helpers/JsonSerializerIgnorePrefix.cs @@ -22,7 +22,7 @@ internal static JsonSerializerOptions GetOptions(string prefix) if (ti.Kind != JsonTypeInfoKind.Object) return; - ti.Properties.RemoveAll(prop => prop.Name.StartsWith(prefix)); + ti.Properties.RemoveAll(prop => prop.Name.StartsWith(prefix, StringComparison.Ordinal)); }; JsonSerializerOptions newOptions = diff --git a/src/Altinn.App.Core/Helpers/MultiDecisionHelper.cs b/src/Altinn.App.Core/Helpers/MultiDecisionHelper.cs index 7b6afbe31..1cf269924 100644 --- a/src/Altinn.App.Core/Helpers/MultiDecisionHelper.cs +++ b/src/Altinn.App.Core/Helpers/MultiDecisionHelper.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Security.Claims; using Altinn.App.Core.Models; using Altinn.Authorization.ABAC.Xacml.JsonProfile; @@ -94,7 +95,7 @@ private static List CreateMultipleActionCategory(List { XacmlJsonCategory actionCategory; actionCategory = DecisionHelper.CreateActionCategory(actionType, true); - actionCategory.Id = ActionId + counter.ToString(); + actionCategory.Id = ActionId + counter.ToString(CultureInfo.InvariantCulture); actionCategories.Add(actionCategory); counter++; } diff --git a/src/Altinn.App.Core/Helpers/ObjectUtils.cs b/src/Altinn.App.Core/Helpers/ObjectUtils.cs index ba40cada1..8ac0a1a84 100644 --- a/src/Altinn.App.Core/Helpers/ObjectUtils.cs +++ b/src/Altinn.App.Core/Helpers/ObjectUtils.cs @@ -25,7 +25,7 @@ public static void InitializeAltinnRowId(object model, int depth = 64) ); } - if (type.Namespace?.StartsWith("System") == true) + if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) { return; // System.DateTime.Now causes infinite recursion, and we shuldn't recurse into system types anyway. } @@ -90,7 +90,7 @@ public static void PrepareModelForXmlStorage(object model, int depth = 64) ); } - if (type.Namespace?.StartsWith("System") == true) + if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) { return; } @@ -190,7 +190,7 @@ public static void RemoveAltinnRowId(object model, int depth = 64) ); } var type = model.GetType(); - if (type.Namespace?.StartsWith("System") == true) + if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) { return; // System.DateTime.Now causes infinite recursion, and we shuldn't recurse into system types anyway. } diff --git a/src/Altinn.App.Core/Helpers/PathHelper.cs b/src/Altinn.App.Core/Helpers/PathHelper.cs index c3fb2d24e..a75a8bdfc 100644 --- a/src/Altinn.App.Core/Helpers/PathHelper.cs +++ b/src/Altinn.App.Core/Helpers/PathHelper.cs @@ -16,7 +16,7 @@ public static bool ValidateLegalFilePath(string legalPath, string filePath) var fullRootedFolder = Path.GetFullPath(legalPath + Path.DirectorySeparatorChar); var expandedFilename = Path.GetFullPath(filePath); - return expandedFilename.StartsWith(fullRootedFolder); + return expandedFilename.StartsWith(fullRootedFolder, StringComparison.Ordinal); } /// diff --git a/src/Altinn.App.Core/Helpers/SelfLinkHelper.cs b/src/Altinn.App.Core/Helpers/SelfLinkHelper.cs index d7ee798ae..b52ca7176 100644 --- a/src/Altinn.App.Core/Helpers/SelfLinkHelper.cs +++ b/src/Altinn.App.Core/Helpers/SelfLinkHelper.cs @@ -21,7 +21,7 @@ public static void SetInstanceAppSelfLinks(Instance instance, HttpRequest reques string selfLink = $"{host}{url}"; - int start = selfLink.IndexOf("/instances"); + int start = selfLink.IndexOf("/instances", StringComparison.OrdinalIgnoreCase); if (start > 0) { selfLink = string.Concat(selfLink.AsSpan(0, start), "/instances"); @@ -29,7 +29,7 @@ public static void SetInstanceAppSelfLinks(Instance instance, HttpRequest reques selfLink += $"/{instance.Id}"; - if (!selfLink.EndsWith(instance.Id)) + if (!selfLink.EndsWith(instance.Id, StringComparison.OrdinalIgnoreCase)) { selfLink += instance.Id; } @@ -66,7 +66,7 @@ HttpRequest request string selfLink = $"{host}{url}"; - int start = selfLink.IndexOf("/instances"); + int start = selfLink.IndexOf("/instances", StringComparison.OrdinalIgnoreCase); if (start > 0) { selfLink = string.Concat(selfLink.AsSpan(0, start), "/instances"); diff --git a/src/Altinn.App.Core/Helpers/ShadowFieldsConverter.cs b/src/Altinn.App.Core/Helpers/ShadowFieldsConverter.cs index 3bf92e0f7..86325ddb1 100644 --- a/src/Altinn.App.Core/Helpers/ShadowFieldsConverter.cs +++ b/src/Altinn.App.Core/Helpers/ShadowFieldsConverter.cs @@ -23,7 +23,7 @@ public void ModifyPrefixInfo(JsonTypeInfo ti) if (ti.Kind != JsonTypeInfoKind.Object) return; - ti.Properties.RemoveAll(prop => prop.Name.StartsWith(_ignorePrefix)); + ti.Properties.RemoveAll(prop => prop.Name.StartsWith(_ignorePrefix, StringComparison.Ordinal)); } } diff --git a/src/Altinn.App.Core/Helpers/UserHelper.cs b/src/Altinn.App.Core/Helpers/UserHelper.cs index ecaa9c703..c1eeb45bd 100644 --- a/src/Altinn.App.Core/Helpers/UserHelper.cs +++ b/src/Altinn.App.Core/Helpers/UserHelper.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Security.Claims; using Altinn.App.Core.Configuration; using Altinn.App.Core.Internal.Profile; @@ -47,24 +48,24 @@ public async Task GetUserContext(HttpContext context) foreach (Claim claim in context.User.Claims) { - if (claim.Type.Equals(AltinnCoreClaimTypes.UserName)) + if (claim.Type.Equals(AltinnCoreClaimTypes.UserName, StringComparison.Ordinal)) { userContext.UserName = claim.Value; } - if (claim.Type.Equals(AltinnCoreClaimTypes.UserId)) + if (claim.Type.Equals(AltinnCoreClaimTypes.UserId, StringComparison.Ordinal)) { - userContext.UserId = Convert.ToInt32(claim.Value); + userContext.UserId = Convert.ToInt32(claim.Value, CultureInfo.InvariantCulture); } - if (claim.Type.Equals(AltinnCoreClaimTypes.PartyID)) + if (claim.Type.Equals(AltinnCoreClaimTypes.PartyID, StringComparison.Ordinal)) { - userContext.PartyId = Convert.ToInt32(claim.Value); + userContext.PartyId = Convert.ToInt32(claim.Value, CultureInfo.InvariantCulture); } - if (claim.Type.Equals(AltinnCoreClaimTypes.AuthenticationLevel)) + if (claim.Type.Equals(AltinnCoreClaimTypes.AuthenticationLevel, StringComparison.Ordinal)) { - userContext.AuthenticationLevel = Convert.ToInt32(claim.Value); + userContext.AuthenticationLevel = Convert.ToInt32(claim.Value, CultureInfo.InvariantCulture); } } @@ -75,7 +76,10 @@ await _profileClient.GetUserProfile(userContext.UserId) if (context.Request.Cookies[_settings.GetAltinnPartyCookieName] != null) { - userContext.PartyId = Convert.ToInt32(context.Request.Cookies[_settings.GetAltinnPartyCookieName]); + userContext.PartyId = Convert.ToInt32( + context.Request.Cookies[_settings.GetAltinnPartyCookieName], + CultureInfo.InvariantCulture + ); } if (userContext.PartyId == userProfile.PartyId) diff --git a/src/Altinn.App.Core/Implementation/AppResourcesSI.cs b/src/Altinn.App.Core/Implementation/AppResourcesSI.cs index 6a0e00a8d..5adb31c4f 100644 --- a/src/Altinn.App.Core/Implementation/AppResourcesSI.cs +++ b/src/Altinn.App.Core/Implementation/AppResourcesSI.cs @@ -212,7 +212,7 @@ public string GetClassRefForLogicDataType(string dataType) Application application = GetApplication(); string classRef = string.Empty; - DataType? element = application.DataTypes.SingleOrDefault(d => d.Id.Equals(dataType)); + DataType? element = application.DataTypes.SingleOrDefault(d => d.Id.Equals(dataType, StringComparison.Ordinal)); if (element != null) { diff --git a/src/Altinn.App.Core/Implementation/DefaultAppEvents.cs b/src/Altinn.App.Core/Implementation/DefaultAppEvents.cs index 729ac6784..19a697a17 100644 --- a/src/Altinn.App.Core/Implementation/DefaultAppEvents.cs +++ b/src/Altinn.App.Core/Implementation/DefaultAppEvents.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Altinn.App.Core.Internal.App; using Altinn.App.Core.Internal.Data; using Altinn.App.Core.Internal.Instances; @@ -69,7 +70,7 @@ private async Task AutoDeleteDataElements(Instance instance) _dataClient.DeleteData( applicationMetadata.Org, applicationMetadata.AppIdentifier.App, - int.Parse(instance.InstanceOwner.PartyId), + int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture), Guid.Parse(item.InstanceGuid), Guid.Parse(item.Id), true diff --git a/src/Altinn.App.Core/Implementation/PrefillSI.cs b/src/Altinn.App.Core/Implementation/PrefillSI.cs index 0a839cca1..895380dc8 100644 --- a/src/Altinn.App.Core/Implementation/PrefillSI.cs +++ b/src/Altinn.App.Core/Implementation/PrefillSI.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Reflection; using Altinn.App.Core.Features; using Altinn.App.Core.Helpers; @@ -93,7 +94,7 @@ public async Task PrefillDataModel( _allowOverwrite = allowOverwriteToken.ToObject(); } - Party? party = await _altinnPartyClientClient.GetParty(int.Parse(partyId)); + Party? party = await _altinnPartyClientClient.GetParty(int.Parse(partyId, CultureInfo.InvariantCulture)); if (party == null) { string errorMessage = $"Could find party for partyId: {partyId}"; diff --git a/src/Altinn.App.Core/Infrastructure/Clients/KeyVault/SecretsLocalClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/KeyVault/SecretsLocalClient.cs index 042851d88..ff254da36 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/KeyVault/SecretsLocalClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/KeyVault/SecretsLocalClient.cs @@ -46,9 +46,9 @@ public KeyVaultClient GetKeyVaultClient() } /// - public async Task GetSecretAsync(string secretId) + public async Task GetSecretAsync(string secretName) { - string token = GetTokenFromSecrets(secretId); + string token = GetTokenFromSecrets(secretName); return await Task.FromResult(token); } diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Profile/ProfileClientCachingDecorator.cs b/src/Altinn.App.Core/Infrastructure/Clients/Profile/ProfileClientCachingDecorator.cs index d0a1e4133..cab458bdb 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Profile/ProfileClientCachingDecorator.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Profile/ProfileClientCachingDecorator.cs @@ -22,7 +22,7 @@ public class ProfileClientCachingDecorator : IProfileClient public ProfileClientCachingDecorator( IProfileClient decoratedService, IMemoryCache memoryCache, - IOptions _settings + IOptions settings ) { _decoratedService = decoratedService; @@ -30,7 +30,7 @@ IOptions _settings _cacheOptions = new() { - AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(_settings.Value.ProfileCacheLifetimeSeconds) + AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(settings.Value.ProfileCacheLifetimeSeconds) }; } diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceClient.cs index c6cecad87..609f618ae 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceClient.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Net; using System.Net.Http.Headers; using System.Text; @@ -60,10 +61,10 @@ public InstanceClient( } /// - public async Task GetInstance(string app, string org, int instanceOwnerPartyId, Guid instanceGuid) + public async Task GetInstance(string app, string org, int instanceOwnerPartyId, Guid instanceId) { - using var activity = _telemetry?.StartGetInstanceByGuidActivity(instanceGuid); - string instanceIdentifier = $"{instanceOwnerPartyId}/{instanceGuid}"; + using var activity = _telemetry?.StartGetInstanceByGuidActivity(instanceId); + string instanceIdentifier = $"{instanceOwnerPartyId}/{instanceId}"; string apiUrl = $"instances/{instanceIdentifier}"; string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName); @@ -78,7 +79,7 @@ public async Task GetInstance(string app, string org, int instanceOwne } else { - _logger.LogError($"Unable to fetch instance with instance id {instanceGuid}"); + _logger.LogError($"Unable to fetch instance with instance id {instanceId}"); throw await PlatformHttpException.CreateAsync(response); } } @@ -90,7 +91,7 @@ public async Task GetInstance(Instance instance) using var activity = _telemetry?.StartGetInstanceByInstanceActivity(instanceGuid); string app = instance.AppId.Split("/")[1]; string org = instance.Org; - int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); + int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture); return await GetInstance(app, org, instanceOwnerPartyId, instanceGuid); } diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceEventClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceEventClient.cs index 97db5f58e..5224647c4 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceEventClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceEventClient.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; using System.Net.Http.Headers; using System.Text; using Altinn.App.Core.Configuration; @@ -66,7 +67,7 @@ string to StringBuilder bld = new StringBuilder(); foreach (string type in eventTypes) { - bld.Append($"{paramSeparator}eventTypes={type}"); + bld.Append(CultureInfo.InvariantCulture, $"{paramSeparator}eventTypes={type}"); paramSeparator = '&'; } diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Storage/TextClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Storage/TextClient.cs index f037eec7e..d35eba899 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Storage/TextClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Storage/TextClient.cs @@ -62,7 +62,7 @@ IMemoryCache memoryCache public async Task GetText(string org, string app, string language) { TextResource? textResource = null; - string cacheKey = $"{org}-{app}-{language.ToLower()}"; + string cacheKey = $"{org}-{app}-{language.ToLowerInvariant()}"; if (!_memoryCache.TryGetValue(cacheKey, out textResource)) { diff --git a/src/Altinn.App.Core/Internal/Data/DataService.cs b/src/Altinn.App.Core/Internal/Data/DataService.cs index 8f9e822fd..bbe27960a 100644 --- a/src/Altinn.App.Core/Internal/Data/DataService.cs +++ b/src/Altinn.App.Core/Internal/Data/DataService.cs @@ -27,7 +27,9 @@ public DataService(IDataClient dataClient, IAppMetadata appMetadata) /// public async Task<(Guid dataElementId, T? model)> GetByType(Instance instance, string dataTypeId) { - DataElement? dataElement = instance.Data.SingleOrDefault(d => d.DataType.Equals(dataTypeId)); + DataElement? dataElement = instance.Data.SingleOrDefault(d => + d.DataType.Equals(dataTypeId, StringComparison.Ordinal) + ); if (dataElement == null) { diff --git a/src/Altinn.App.Core/Internal/Expressions/ExpressionEvaluator.cs b/src/Altinn.App.Core/Internal/Expressions/ExpressionEvaluator.cs index 30ffbf3eb..45b607576 100644 --- a/src/Altinn.App.Core/Internal/Expressions/ExpressionEvaluator.cs +++ b/src/Altinn.App.Core/Internal/Expressions/ExpressionEvaluator.cs @@ -266,7 +266,7 @@ private static string Round(object?[] args) int precision = 0; if (args.Length == 2 && args[1] is not null) { - precision = Convert.ToInt32(args[1]); + precision = Convert.ToInt32(args[1], CultureInfo.InvariantCulture); } return number.Value.ToString($"N{precision}", CultureInfo.InvariantCulture); @@ -386,7 +386,7 @@ bool ab $"Expected number, got value {(ab ? "true" : "false")}" ), string s => ParseNumber(s), - IConvertible c => Convert.ToDouble(c), + IConvertible c => Convert.ToDouble(c, CultureInfo.InvariantCulture), _ => null }; } @@ -398,7 +398,7 @@ bool ab return PrepareBooleanArg(args[0]) ? args[1] : null; } - if (args.Length > 2 && !"else".Equals(args[2] as string, StringComparison.InvariantCultureIgnoreCase)) + if (args.Length > 2 && !"else".Equals(args[2] as string, StringComparison.OrdinalIgnoreCase)) { throw new ExpressionEvaluatorTypeErrorException("Expected third argument to be \"else\""); } @@ -488,15 +488,15 @@ bool ab if (value is string svalue) { // Special case for "TruE" to be equal to true - if ("true".Equals(svalue, StringComparison.InvariantCultureIgnoreCase)) + if ("true".Equals(svalue, StringComparison.OrdinalIgnoreCase)) { return "true"; } - else if ("false".Equals(svalue, StringComparison.InvariantCultureIgnoreCase)) + else if ("false".Equals(svalue, StringComparison.OrdinalIgnoreCase)) { return "false"; } - else if ("null".Equals(svalue, StringComparison.InvariantCultureIgnoreCase)) + else if ("null".Equals(svalue, StringComparison.OrdinalIgnoreCase)) { return null; } @@ -523,7 +523,7 @@ bool ab throw new ExpressionEvaluatorTypeErrorException($"Expected 2 argument(s), got {args.Length}"); } - return string.Equals(ToStringForEquals(args[0]), ToStringForEquals(args[1]), StringComparison.InvariantCulture); + return string.Equals(ToStringForEquals(args[0]), ToStringForEquals(args[1]), StringComparison.Ordinal); } private static object Argv(object?[] args, object[]? positionalArguments) diff --git a/src/Altinn.App.Core/Internal/Pdf/PdfService.cs b/src/Altinn.App.Core/Internal/Pdf/PdfService.cs index 7df8db7ba..600b21db3 100644 --- a/src/Altinn.App.Core/Internal/Pdf/PdfService.cs +++ b/src/Altinn.App.Core/Internal/Pdf/PdfService.cs @@ -195,8 +195,12 @@ private static string GetFileName(Instance instance, TextResource? textResource) } TextResourceElement? titleText = - textResource.Resources.Find(textResourceElement => textResourceElement.Id.Equals("appName")) - ?? textResource.Resources.Find(textResourceElement => textResourceElement.Id.Equals("ServiceName")); + textResource.Resources.Find(textResourceElement => + textResourceElement.Id.Equals("appName", StringComparison.Ordinal) + ) + ?? textResource.Resources.Find(textResourceElement => + textResourceElement.Id.Equals("ServiceName", StringComparison.Ordinal) + ); if (titleText != null && !string.IsNullOrEmpty(titleText.Value)) { diff --git a/src/Altinn.App.Core/Internal/Process/EventHandlers/EndEventEventHandler.cs b/src/Altinn.App.Core/Internal/Process/EventHandlers/EndEventEventHandler.cs index 2e9dbe69c..9ebd24525 100644 --- a/src/Altinn.App.Core/Internal/Process/EventHandlers/EndEventEventHandler.cs +++ b/src/Altinn.App.Core/Internal/Process/EventHandlers/EndEventEventHandler.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Altinn.App.Core.Internal.App; using Altinn.App.Core.Internal.Instances; using Altinn.App.Core.Models; @@ -48,7 +49,7 @@ private async Task AutoDeleteOnProcessEndIfEnabled(Instance instance) ApplicationMetadata applicationMetadata = await _appMetadata.GetApplicationMetadata(); if (applicationMetadata.AutoDeleteOnProcessEnd && instance.Process?.Ended != null) { - int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); + int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture); await _instanceClient.DeleteInstance(instanceOwnerPartyId, instanceIdentifier.InstanceGuid, true); } } diff --git a/src/Altinn.App.Core/Internal/Process/ExclusiveGatewayFactory.cs b/src/Altinn.App.Core/Internal/Process/ExclusiveGatewayFactory.cs index 099be5bf6..6f3b69fd3 100644 --- a/src/Altinn.App.Core/Internal/Process/ExclusiveGatewayFactory.cs +++ b/src/Altinn.App.Core/Internal/Process/ExclusiveGatewayFactory.cs @@ -30,7 +30,7 @@ public ExclusiveGatewayFactory(IEnumerable gateways) public IProcessExclusiveGateway? GetProcessExclusiveGateway(string gatewayId) { return _gateways.FirstOrDefault(gateway => - String.Equals(gateway.GatewayId, gatewayId, StringComparison.CurrentCultureIgnoreCase) + string.Equals(gateway.GatewayId, gatewayId, StringComparison.OrdinalIgnoreCase) ); } } diff --git a/src/Altinn.App.Core/Internal/Process/ExpressionsExclusiveGateway.cs b/src/Altinn.App.Core/Internal/Process/ExpressionsExclusiveGateway.cs index a22f885dd..35bfe198d 100644 --- a/src/Altinn.App.Core/Internal/Process/ExpressionsExclusiveGateway.cs +++ b/src/Altinn.App.Core/Internal/Process/ExpressionsExclusiveGateway.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Text; using System.Text.Json; using Altinn.App.Core.Features; @@ -98,7 +99,7 @@ private async Task GetLayoutEvaluatorState( dataElementType, instance.Org, instance.AppId.Split("/")[1], - int.Parse(instance.InstanceOwner.PartyId), + int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture), dataGuid.Value ); } diff --git a/src/Altinn.App.Core/Internal/Process/ProcessReader.cs b/src/Altinn.App.Core/Internal/Process/ProcessReader.cs index f5f2aba41..c854cda60 100644 --- a/src/Altinn.App.Core/Internal/Process/ProcessReader.cs +++ b/src/Altinn.App.Core/Internal/Process/ProcessReader.cs @@ -24,7 +24,12 @@ public class ProcessReader : IProcessReader public ProcessReader(IProcessClient processClient, Telemetry? telemetry = null) { XmlSerializer serializer = new XmlSerializer(typeof(Definitions)); - Definitions? definitions = (Definitions?)serializer.Deserialize(processClient.GetProcessDefinition()); + // TODO: IO should be async + using var stream = processClient.GetProcessDefinition(); +#pragma warning disable CA5369 // Use XmlReader for 'XmlSerializer.Deserialize()' + // NOTE: this is trusted XML input, as it comes from the apps own code + Definitions? definitions = (Definitions?)serializer.Deserialize(stream); +#pragma warning restore CA5369 // Use XmlReader for 'XmlSerializer.Deserialize()' _definitions = definitions diff --git a/src/Altinn.App.Core/Internal/Process/ProcessTasks/Common/ProcessTaskFinalizer.cs b/src/Altinn.App.Core/Internal/Process/ProcessTasks/Common/ProcessTaskFinalizer.cs index 996baeba0..5914c07ea 100644 --- a/src/Altinn.App.Core/Internal/Process/ProcessTasks/Common/ProcessTaskFinalizer.cs +++ b/src/Altinn.App.Core/Internal/Process/ProcessTasks/Common/ProcessTaskFinalizer.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Text.Json; using Altinn.App.Core.Configuration; using Altinn.App.Core.Helpers; @@ -85,7 +86,7 @@ DataType dataType Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); Guid dataGuid = Guid.Parse(dataElement.Id); string app = instance.AppId.Split("/")[1]; - int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); + int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture); object data = await _dataClient.GetFormData( instanceGuid, modelType, diff --git a/src/Altinn.App.Core/Internal/Process/ProcessTasks/Common/ProcessTaskInitializer.cs b/src/Altinn.App.Core/Internal/Process/ProcessTasks/Common/ProcessTaskInitializer.cs index cd2850f72..3c96de722 100644 --- a/src/Altinn.App.Core/Internal/Process/ProcessTasks/Common/ProcessTaskInitializer.cs +++ b/src/Altinn.App.Core/Internal/Process/ProcessTasks/Common/ProcessTaskInitializer.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Altinn.App.Core.Features; using Altinn.App.Core.Helpers; using Altinn.App.Core.Internal.App; @@ -107,7 +108,7 @@ private async Task UpdatePresentationTextsOnInstance(Instance instance, string d if (updatedValues.Count > 0) { Instance updatedInstance = await _instanceClient.UpdatePresentationTexts( - int.Parse(instance.Id.Split("/")[0]), + int.Parse(instance.Id.Split("/")[0], CultureInfo.InvariantCulture), Guid.Parse(instance.Id.Split("/")[1]), new PresentationTexts { Texts = updatedValues } ); @@ -129,7 +130,7 @@ private async Task UpdateDataValuesOnInstance(Instance instance, string dataType if (updatedValues.Count > 0) { Instance updatedInstance = await _instanceClient.UpdateDataValues( - int.Parse(instance.Id.Split("/")[0]), + int.Parse(instance.Id.Split("/")[0], CultureInfo.InvariantCulture), Guid.Parse(instance.Id.Split("/")[1]), new DataValues { Values = updatedValues } ); diff --git a/src/Altinn.App.Core/Internal/Validation/ValidationService.cs b/src/Altinn.App.Core/Internal/Validation/ValidationService.cs index 46e2fcd4c..8b8916e12 100644 --- a/src/Altinn.App.Core/Internal/Validation/ValidationService.cs +++ b/src/Altinn.App.Core/Internal/Validation/ValidationService.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Altinn.App.Core.Features; using Altinn.App.Core.Internal.App; using Altinn.App.Core.Internal.AppModel; @@ -139,7 +140,7 @@ public async Task> ValidateDataElement( Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); string app = instance.AppId.Split("/")[1]; - int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); + int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId, CultureInfo.InvariantCulture); var data = await _dataClient.GetFormData( instanceGuid, modelType, diff --git a/src/Altinn.App.Core/Models/AppIdentifier.cs b/src/Altinn.App.Core/Models/AppIdentifier.cs index 0b61d1988..3d1627612 100644 --- a/src/Altinn.App.Core/Models/AppIdentifier.cs +++ b/src/Altinn.App.Core/Models/AppIdentifier.cs @@ -93,8 +93,8 @@ public bool Equals(AppIdentifier? other) { return Org != null && App != null - && Org.Equals(other?.Org, StringComparison.CurrentCultureIgnoreCase) - && App.Equals(other?.App, StringComparison.CurrentCultureIgnoreCase); + && Org.Equals(other?.Org, StringComparison.OrdinalIgnoreCase) + && App.Equals(other?.App, StringComparison.OrdinalIgnoreCase); } /// diff --git a/src/Altinn.App.Core/Models/DataList.cs b/src/Altinn.App.Core/Models/DataList.cs index 7bf0060ad..e9682b700 100644 --- a/src/Altinn.App.Core/Models/DataList.cs +++ b/src/Altinn.App.Core/Models/DataList.cs @@ -14,6 +14,8 @@ public class DataList /// Gets or sets the metadata of the DataList. /// #pragma warning disable IDE1006 // Naming Styles - public members should be PascalCase +#pragma warning disable CA1707 // Identifiers should not contain underscores public DataListMetadata _metaData { get; set; } = new DataListMetadata(); +#pragma warning restore CA1707 // Identifiers should not contain underscores #pragma warning restore IDE1006 // Naming Styles } diff --git a/src/Altinn.App.Core/Models/InstanceIdentifier.cs b/src/Altinn.App.Core/Models/InstanceIdentifier.cs index 6363edd29..ae6ac5c94 100644 --- a/src/Altinn.App.Core/Models/InstanceIdentifier.cs +++ b/src/Altinn.App.Core/Models/InstanceIdentifier.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Altinn.Platform.Storage.Interface.Models; namespace Altinn.App.Core.Models; @@ -110,7 +111,7 @@ public override string ToString() private static (int InstanceOwnerPartyId, Guid InstanceGuid) DeconstructInstanceId(string instanceId) { var deconstructed = instanceId.Split("/"); - int instanceOwnerPartyId = int.Parse(deconstructed[0]); + int instanceOwnerPartyId = int.Parse(deconstructed[0], CultureInfo.InvariantCulture); Guid instanceGuid = Guid.Parse(deconstructed[1]); return (instanceOwnerPartyId, instanceGuid); @@ -129,13 +130,17 @@ private static (int InstanceOwnerId, Guid InstanceOwnerGuid) DeconstructInstance string searchForSingular = "/instance/"; string instanceSubpath = string.Empty; - if (url.Contains(searchForPlural, StringComparison.InvariantCultureIgnoreCase)) + if (url.Contains(searchForPlural, StringComparison.OrdinalIgnoreCase)) { - instanceSubpath = url.Substring(url.IndexOf(searchForPlural) + searchForPlural.Length); + instanceSubpath = url.Substring( + url.IndexOf(searchForPlural, StringComparison.OrdinalIgnoreCase) + searchForPlural.Length + ); } - else if (url.Contains(searchForSingular, StringComparison.InvariantCultureIgnoreCase)) + else if (url.Contains(searchForSingular, StringComparison.OrdinalIgnoreCase)) { - instanceSubpath = url.Substring(url.IndexOf(searchForSingular) + searchForSingular.Length); + instanceSubpath = url.Substring( + url.IndexOf(searchForSingular, StringComparison.OrdinalIgnoreCase) + searchForSingular.Length + ); } if (string.IsNullOrEmpty(instanceSubpath)) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 6669928bf..5dff295a1 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -13,6 +13,7 @@ + Recommended enable enable true @@ -50,4 +51,4 @@ true - \ No newline at end of file +