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

Add support for system user #599

Merged
merged 17 commits into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from 16 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
4 changes: 0 additions & 4 deletions src/Storage/Altinn.Platform.Storage.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

<ItemGroup>
<PackageReference Include="Altinn.Common.AccessToken" Version="4.5.5" />

<PackageReference Include="Altinn.Common.AccessTokenClient" Version="3.0.11" />
<PackageReference Include="Altinn.Platform.Models" Version="1.6.1" />
<PackageReference Include="Altinn.Platform.Storage.Interface" Version="4.0.5" />
Expand All @@ -20,11 +19,8 @@
<PackageReference Include="Azure.Storage.Blobs" Version="12.23.0" />
<PackageReference Include="Altinn.Common.PEP" Version="4.1.2" />
<PackageReference Include="Azure.Storage.Queues" Version="12.21.0" />

<PackageReference Include="JWTCookieAuthentication" Version="3.0.1" />

<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" />

<PackageReference Include="PDFsharp" Version="6.1.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="7.2.0" />
Expand Down
611 changes: 301 additions & 310 deletions src/Storage/Authorization/AuthorizationService.cs

Large diffs are not rendered by default.

40 changes: 17 additions & 23 deletions src/Storage/Authorization/ClaimsPrincipalProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,24 @@

using Microsoft.AspNetCore.Http;

namespace Altinn.Platform.Storage.Authorization
{
/// <summary>
/// Represents an implementation of <see cref="IClaimsPrincipalProvider"/> using the HttpContext to obtain
/// the current claims principal needed for the application to make calls to other services.
/// </summary>
[ExcludeFromCodeCoverage]
public class ClaimsPrincipalProvider : IClaimsPrincipalProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
namespace Altinn.Platform.Storage.Authorization;

/// <summary>
/// Initializes a new instance of the <see cref="ClaimsPrincipalProvider"/> class.
/// </summary>
/// <param name="httpContextAccessor">The http context accessor</param>
public ClaimsPrincipalProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
/// <summary>
/// Represents an implementation of <see cref="IClaimsPrincipalProvider"/> using the HttpContext to obtain
/// the current claims principal needed for the application to make calls to other services.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="ClaimsPrincipalProvider"/> class.
/// </remarks>
/// <param name="httpContextAccessor">The http context accessor</param>
[ExcludeFromCodeCoverage]
public class ClaimsPrincipalProvider(IHttpContextAccessor httpContextAccessor) : IClaimsPrincipalProvider
{
private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor;

/// <inheritdoc/>
public ClaimsPrincipal GetUser()
{
return _httpContextAccessor.HttpContext.User;
}
/// <inheritdoc/>
public ClaimsPrincipal GetUser()
{
return _httpContextAccessor.HttpContext.User;
}
}
11 changes: 7 additions & 4 deletions src/Storage/Controllers/DataController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ public async Task<ActionResult<DataElement>> Delete(int instanceOwnerPartyId, Gu
}

(Application application, ActionResult applicationError) = await GetApplicationAsync(instance.AppId, instance.Org);

string userOrOrgNo = User.GetUserOrOrgNo();

if (delay)
{
if (appOwnerDeletingElement && dataElement.DeleteStatus?.IsHardDeleted == true)
Expand All @@ -135,11 +138,11 @@ public async Task<ActionResult<DataElement>> Delete(int instanceOwnerPartyId, Gu
return BadRequest($"DataType {dataElement.DataType} does not support delayed deletion");
}

dataElement.LastChangedBy = User.GetUserOrOrgId();
dataElement.LastChangedBy = userOrOrgNo;
return await InitiateDelayedDelete(instance, dataElement);
}

dataElement.LastChangedBy = User.GetUserOrOrgId();
dataElement.LastChangedBy = userOrOrgNo;
return await DeleteImmediately(instance, dataElement, application.StorageAccountNumber);
}

Expand Down Expand Up @@ -436,7 +439,7 @@ public async Task<ActionResult<DataElement>> OverwriteData(
{
{ "/contentType", updatedData.ContentType },
{ "/filename", HttpUtility.UrlDecode(updatedData.Filename) },
{ "/lastChangedBy", User.GetUserOrOrgId() },
{ "/lastChangedBy", User.GetUserOrOrgNo() },
{ "/lastChanged", changedTime },
{ "/refs", updatedData.Refs },
{ "/references", updatedData.References },
Expand Down Expand Up @@ -543,7 +546,7 @@ public async Task<ActionResult> SetFileScanStatus(

(Stream theStream, string contentType, string contentFileName, long fileSize) = await DataElementHelper.GetStream(request, _defaultFormOptions.MultipartBoundaryLengthLimit);

string user = User.GetUserOrOrgId();
string user = User.GetUserOrOrgNo();

DataElement newData = DataElementHelper.CreateDataElement(elementType, refs, instance, creationTime, contentType, contentFileName, fileSize, user, generatedForTask);

Expand Down
31 changes: 13 additions & 18 deletions src/Storage/Controllers/InstancesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Threading.Tasks;
using System.Web;

using Altinn.AccessManagement.Core.Models;
using Altinn.Authorization.ABAC.Xacml.JsonProfile;
using Altinn.Common.PEP.Helpers;
using Altinn.Platform.Storage.Authorization;
Expand Down Expand Up @@ -99,8 +100,8 @@ public async Task<ActionResult<QueryResponse<Instance>>> GetInstances(InstanceQu
}

string orgClaim = User.GetOrg();
int? userId = User.GetUserIdAsInt();
bool appOwnerRequestingInstances = false;
int? userId = User.GetUserId();
SystemUserClaim systemUser = User.GetSystemUser();

if (orgClaim != null)
{
Expand Down Expand Up @@ -136,10 +137,8 @@ public async Task<ActionResult<QueryResponse<Instance>>> GetInstances(InstanceQu
return Forbid();
}
}

appOwnerRequestingInstances = true;
}
else if (userId != null)
else if (userId is not null || systemUser is not null)
{
if (queryParameters.InstanceOwnerPartyId == null && string.IsNullOrEmpty(queryParameters.InstanceOwnerIdentifier))
{
Expand Down Expand Up @@ -202,6 +201,8 @@ public async Task<ActionResult<QueryResponse<Instance>>> GetInstances(InstanceQu
queryParameters.ContinuationToken = HttpUtility.UrlDecode(queryParameters.ContinuationToken);
}

bool appOwnerRequestingInstances = User.HasServiceOwnerScope();

// filter out hard deleted instances if it isn't the appOwner requesting instances
if (!appOwnerRequestingInstances)
{
Expand Down Expand Up @@ -392,9 +393,8 @@ public async Task<ActionResult<Instance>> Post(string appId, [FromBody] Instance
try
{
DateTime creationTime = DateTime.UtcNow;
string userId = GetUserId();

Instance instanceToCreate = CreateInstanceFromTemplate(appInfo, instance, creationTime, userId);
Instance instanceToCreate = CreateInstanceFromTemplate(appInfo, instance, creationTime, User.GetUserOrOrgNo());

storedInstance = await _instanceRepository.Create(instanceToCreate);
await _instanceEventService.DispatchEvent(InstanceEventType.Created, storedInstance);
Expand Down Expand Up @@ -470,7 +470,7 @@ public async Task<ActionResult<Instance>> Delete(int instanceOwnerPartyId, Guid
instance.Status.SoftDeleted = now;
}

instance.LastChangedBy = GetUserId();
instance.LastChangedBy = User.GetUserOrOrgNo();
instance.LastChanged = now;
updateProperties.Add(nameof(instance.LastChanged));
updateProperties.Add(nameof(instance.LastChangedBy));
Expand Down Expand Up @@ -521,7 +521,7 @@ public async Task<ActionResult<Instance>> AddCompleteConfirmation(

instance.CompleteConfirmations.Add(new CompleteConfirmation { StakeholderId = org, ConfirmedOn = DateTime.UtcNow });
instance.LastChanged = DateTime.UtcNow;
instance.LastChangedBy = User.GetUserOrOrgId();
instance.LastChangedBy = User.GetUserOrOrgNo();

updateProperties.Add(nameof(instance.CompleteConfirmations));
updateProperties.Add(nameof(instance.LastChanged));
Expand Down Expand Up @@ -643,7 +643,7 @@ public async Task<ActionResult<Instance>> UpdateSubstatus(

instance.Status.Substatus = substatus;
instance.LastChanged = creationTime;
instance.LastChangedBy = User.GetOrgNumber().ToString();
instance.LastChangedBy = User.GetOrgNumber();

updatedInstance = await _instanceRepository.Update(instance, updateProperties);
updatedInstance.SetPlatformSelfLinks(_storageBaseAndHost);
Expand Down Expand Up @@ -750,14 +750,14 @@ public async Task<ActionResult<Instance>> UpdateDataValues(
return Ok(updatedInstance);
}

private static Instance CreateInstanceFromTemplate(Application appInfo, Instance instanceTemplate, DateTime creationTime, string userId)
private static Instance CreateInstanceFromTemplate(Application appInfo, Instance instanceTemplate, DateTime creationTime, string performedBy)
{
Instance createdInstance = new Instance
{
InstanceOwner = instanceTemplate.InstanceOwner,
CreatedBy = userId,
CreatedBy = performedBy,
Created = creationTime,
LastChangedBy = userId,
LastChangedBy = performedBy,
LastChanged = creationTime,
AppId = appInfo.Id,
Org = appInfo.Org,
Expand Down Expand Up @@ -804,11 +804,6 @@ private static void FilterOutDeletedDataElements(Instance instance)
}
}

private string GetUserId()
{
return User.GetUserOrOrgId();
}

private string BuildRequestLink(string continuationToken)
{
string url = Request.Path;
Expand Down
12 changes: 8 additions & 4 deletions src/Storage/Controllers/MessageboxInstancesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ public async Task<ActionResult> Undelete(int instanceOwnerPartyId, Guid instance
updateProperties.Add(nameof(instance.Status));
updateProperties.Add(nameof(instance.Status.IsSoftDeleted));
updateProperties.Add(nameof(instance.Status.SoftDeleted));
instance.LastChangedBy = User.GetUserOrOrgId();
instance.LastChangedBy = User.GetUserOrOrgNo();
instance.LastChanged = DateTime.UtcNow;
instance.Status.IsSoftDeleted = false;
instance.Status.SoftDeleted = null;
Expand All @@ -241,9 +241,11 @@ public async Task<ActionResult> Undelete(int instanceOwnerPartyId, Guid instance
InstanceOwnerPartyId = instance.InstanceOwner.PartyId,
User = new PlatformUser
{
UserId = User.GetUserIdAsInt(),
UserId = User.GetUserId(),
AuthenticationLevel = User.GetAuthenticationLevel(),
OrgId = User.GetOrg(),
SystemUserId = User.GetSystemUserId(),
SystemUserOwnerOrgNo = User.GetSystemUserOwner(),
}
};

Expand Down Expand Up @@ -298,7 +300,7 @@ public async Task<ActionResult> Delete(Guid instanceGuid, int instanceOwnerParty
instance.Status.SoftDeleted = now;
}

instance.LastChangedBy = User.GetUserOrOrgId();
instance.LastChangedBy = User.GetUserOrOrgNo();
instance.LastChanged = now;
updateProperties.Add(nameof(instance.LastChanged));
updateProperties.Add(nameof(instance.LastChangedBy));
Expand All @@ -311,9 +313,11 @@ public async Task<ActionResult> Delete(Guid instanceGuid, int instanceOwnerParty
InstanceOwnerPartyId = instance.InstanceOwner.PartyId,
User = new PlatformUser
{
UserId = User.GetUserIdAsInt(),
UserId = User.GetUserId(),
AuthenticationLevel = User.GetAuthenticationLevel(),
SandGrainOne marked this conversation as resolved.
Show resolved Hide resolved
OrgId = User.GetOrg(),
SystemUserId = User.GetSystemUserId(),
SystemUserOwnerOrgNo = User.GetSystemUserOwner(),
},
};

Expand Down
2 changes: 1 addition & 1 deletion src/Storage/Controllers/ProcessController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
/// </summary>
[Route("storage/api/v1/instances/{instanceOwnerPartyId:int}/{instanceGuid:guid}/process")]
[ApiController]
public class ProcessController : ControllerBase

Check warning on line 28 in src/Storage/Controllers/ProcessController.cs

View workflow job for this annotation

GitHub Actions / Build, test & analyze

This controller has multiple responsibilities and could be split into 2 smaller controllers. (https://rules.sonarsource.com/csharp/RSPEC-6960)
{
private readonly IInstanceRepository _instanceRepository;
private readonly IInstanceEventRepository _instanceEventRepository;
Expand Down Expand Up @@ -244,11 +244,11 @@
}

existingInstance.Process = processState;
existingInstance.LastChangedBy = User.GetUserOrOrgId();
existingInstance.LastChangedBy = User.GetUserOrOrgNo();
existingInstance.LastChanged = DateTime.UtcNow;
}

private (string Action, string TaskId) ActionMapping(ProcessState processState, Instance existingInstance)

Check warning on line 251 in src/Storage/Controllers/ProcessController.cs

View workflow job for this annotation

GitHub Actions / Build, test & analyze

Make 'ActionMapping' a static method. (https://rules.sonarsource.com/csharp/RSPEC-2325)
{
string taskId = null;
string altinnTaskType = existingInstance.Process?.CurrentTask?.AltinnTaskType;
Expand Down
8 changes: 4 additions & 4 deletions src/Storage/Controllers/SignController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ public SignController(IInstanceService instanceService)
}

/// <summary>
/// Create signature document from listed data elements
/// Create signature document from listed data elements.
/// </summary>
/// <param name="instanceOwnerPartyId">The party id of the instance owner.</param>
/// <param name="instanceGuid">The guid of the instance</param>
/// <param name="signRequest">Signrequest containing data element ids and sign status</param>
/// <param name="instanceGuid">The guid of the instance.</param>
/// <param name="signRequest">Signrequest containing data element ids and sign status.</param>
[Authorize(Policy = AuthzConstants.POLICY_INSTANCE_SIGN)]
[HttpPost("{instanceOwnerPartyId:int}/{instanceGuid:guid}/sign")]
[ProducesResponseType(StatusCodes.Status201Created)]
Expand All @@ -46,7 +46,7 @@ public async Task<ActionResult> Sign([FromRoute] int instanceOwnerPartyId, [From
return Problem("The 'UserId' parameter must be defined for signee.", null, 400);
}

(bool created, ServiceError serviceError) = await _instanceService.CreateSignDocument(instanceOwnerPartyId, instanceGuid, signRequest, User.GetUserIdAsInt().Value);
(bool created, ServiceError serviceError) = await _instanceService.CreateSignDocument(instanceOwnerPartyId, instanceGuid, signRequest, User.GetUserId().Value);

if (created)
{
Expand Down
23 changes: 16 additions & 7 deletions src/Storage/Filters/IdentityTelemetryFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Claims;
using Altinn.AccessManagement.Core.Models;
using Altinn.Platform.Storage.Configuration;
using Altinn.Platform.Storage.Helpers;
using AltinnCore.Authentication.Constants;

using Microsoft.ApplicationInsights.Channel;
Expand Down Expand Up @@ -42,23 +44,23 @@ public void Process(ITelemetry item)
DependencyTelemetry dependency = item as DependencyTelemetry;

if (_disableTelemetryForMigration && (
SandGrainOne marked this conversation as resolved.
Show resolved Hide resolved
(request != null && request.Url.LocalPath.StartsWith("/storage/api/v1/migration", StringComparison.OrdinalIgnoreCase))
(request is not null && request.Url.LocalPath.StartsWith("/storage/api/v1/migration", StringComparison.OrdinalIgnoreCase))
||
(dependency != null && dependency.Context.Operation.Name.StartsWith("POST Migration", StringComparison.OrdinalIgnoreCase))))
(dependency is not null && dependency.Context.Operation.Name.StartsWith("POST Migration", StringComparison.OrdinalIgnoreCase))))
{
return;
}

if (request != null && request.Url.ToString().Contains("storage/api/"))
if (request is not null && request.Url.ToString().Contains("storage/api/"))
{
HttpContext ctx = _httpContextAccessor.HttpContext;

if (ctx != null && ctx.Request.Headers.TryGetValue("X-Forwarded-For", out StringValues ipAddress))
if (ctx is not null && ctx.Request.Headers.TryGetValue("X-Forwarded-For", out StringValues ipAddress))
{
request.Properties.Add("ipAddress", ipAddress.FirstOrDefault());
}

if (ctx?.User != null)
if (ctx?.User is not null)
{
int? orgNumber = GetOrgNumber(ctx.User);
int? userId = GetUserIdAsInt(ctx.User);
Expand All @@ -68,15 +70,22 @@ public void Process(ITelemetry item)
request.Properties.Add("partyId", partyId.ToString());
request.Properties.Add("authLevel", authLevel.ToString());

if (userId != null)
if (userId is not null)
{
request.Properties.Add("userId", userId.ToString());
}

if (orgNumber != null)
if (orgNumber is not null)
{
request.Properties.Add("orgNumber", orgNumber.ToString());
}

SystemUserClaim systemUser = ctx.User.GetSystemUser();
if (systemUser is not null)
{
request.Properties.Add("systemUserId", systemUser.Systemuser_id[0].ToString());
request.Properties.Add("systemUserOrgId", systemUser.Systemuser_org.ID);
}
}
}

Expand Down
Loading
Loading