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

test of change request #857

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
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
20 changes: 18 additions & 2 deletions src/Authentication/Services/ChangeRequestSystemUserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Altinn.Authentication.Core.Clients.Interfaces;
Expand All @@ -24,13 +25,15 @@
using Altinn.Urn;
using Altinn.Urn.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Altinn.Platform.Authentication.Services;
#nullable enable

/// <inheritdoc/>
public class ChangeRequestSystemUserService(
ILogger<ChangeRequestSystemUserService> logger,
ISystemRegisterService systemRegisterService,
IPartiesClient partiesClient,
ISystemRegisterRepository systemRegisterRepository,
Expand All @@ -57,7 +60,16 @@
return validationSet.Problem;
}

var verified = await VerifySetOfRights(createRequest, vendorOrgNo);
Result<ChangeRequestResponse> verified = await VerifySetOfRights(createRequest, vendorOrgNo);
if (verified.IsProblem)
{
return verified.Problem;
}

if (verified.Value.Status == ChangeRequestStatus.NoChangeNeeded.ToString())
{
return verified.Value;
}

if (createRequest.RedirectUrl is not null && createRequest.RedirectUrl != string.Empty)
{
Expand Down Expand Up @@ -635,7 +647,9 @@
return new ChangeRequestResponse()
{
Id = Guid.NewGuid(),
ExternalRef = verifyRequest.ExternalRef,

// ExternalRef = verifyRequest.ExternalRef,
ExternalRef = JsonSerializer.Serialize(res.Value),
SystemId = verifyRequest.SystemId,
SystemUserId = Guid.Parse(valSet.Value.SystemUser.Id),
PartyOrgNo = verifyRequest.PartyOrgNo,
Expand Down Expand Up @@ -795,7 +809,9 @@
}
}
};
var req = request.ToString();
logger.LogError($"SystemUser-ChangeRequest: {req} OrgNo: {systemUser.ReporteeOrgNo}");

return await PDPClient.GetDecisionForRequest(request);

Check failure on line 815 in src/Authentication/Services/ChangeRequestSystemUserService.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

A local variable or function named 'req' is already defined in this scope

Check failure on line 815 in src/Authentication/Services/ChangeRequestSystemUserService.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

A local variable or function named 'req' is already defined in this scope

Check failure on line 815 in src/Authentication/Services/ChangeRequestSystemUserService.cs

View workflow job for this annotation

GitHub Actions / Build and Test

A local variable or function named 'req' is already defined in this scope

Check failure on line 815 in src/Authentication/Services/ChangeRequestSystemUserService.cs

View workflow job for this annotation

GitHub Actions / Build and Test

A local variable or function named 'req' is already defined in this scope

Check failure on line 815 in src/Authentication/Services/ChangeRequestSystemUserService.cs

View workflow job for this annotation

GitHub Actions / Analyze

A local variable or function named 'req' is already defined in this scope

Check failure on line 815 in src/Authentication/Services/ChangeRequestSystemUserService.cs

View workflow job for this annotation

GitHub Actions / Analyze

A local variable or function named 'req' is already defined in this scope
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
<None Update="Resources\Testdata\Systemregister\TilgangslisteTest.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Resources\Testdata\SystemUser\CreateChangeRequest.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Resources\Testdata\SystemUser\RequestSystemUser.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,14 @@ public async Task<HttpResponseMessage> PostAsync(string endpoint, string body, s
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);

HttpContent content = new StringContent(body, System.Text.Encoding.UTF8, "application/json");
if (body is not null && body != string.Empty)
{
HttpContent content = new StringContent(body, System.Text.Encoding.UTF8, "application/json");
return await client.PostAsync($"{BaseUrl}/{endpoint}", content);
}

var response = await client.PostAsync($"{BaseUrl}/{endpoint}", content);
return response;
return await client.PostAsync($"{BaseUrl}/{endpoint}", null);

}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"external_ref": "312605031",
"systemId": "{systemId}",
"partyOrgNo": "312605031",
"requiredRights": [
{
"resource": [
{
"id": "urn:altinn:resource",
"value": "kravogbetaling"
}
]
},
{
"resource": [
{
"id": "urn:altinn:resource",
"value": "ske-innrapportering-boligsameie"
}
]
}
],
"unwantedRights": [],
"redirectUrl": "{redirectUrl}"
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@
"value": "kravogbetaling"
}
]
},
{
"Resource": [
{
"id": "urn:altinn:resource",
"value": "ske-innrapportering-boligsameie"
}
]
}
],
"allowedRedirectUrls": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
/// Reported bug: https://github.com/Altinn/altinn-authentication/issues/848
/// </summary>
// [Fact]
public async Task GetCreatedSystemUser()

Check warning on line 87 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Public method 'GetCreatedSystemUser' on test class 'SystemUserTests' should be marked as a Fact. Reduce the visibility of the method, or add a Fact attribute to the method. (https://xunit.net/xunit.analyzers/rules/xUnit1013)

Check warning on line 87 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Build and Test

Public method 'GetCreatedSystemUser' on test class 'SystemUserTests' should be marked as a Fact. Reduce the visibility of the method, or add a Fact attribute to the method. (https://xunit.net/xunit.analyzers/rules/xUnit1013)

Check warning on line 87 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze

Public method 'GetCreatedSystemUser' on test class 'SystemUserTests' should be marked as a Fact. Reduce the visibility of the method, or add a Fact attribute to the method. (https://xunit.net/xunit.analyzers/rules/xUnit1013)
{
const string alternativeParty = "50891151";

Expand Down Expand Up @@ -195,11 +195,94 @@
Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
}

/// <summary>
/// https://github.com/Altinn/altinn-authentication/issues/791
/// API for creating a change request for System User
/// </summary>
[Fact]
public async Task PostChangeRequestSystemUserAndApproveReturnSuccess()
{
// Prerequisite-step
var maskinportenToken = await _platformClient.GetToken();

var teststate = new SystemRegisterState()
.WithClientId(Guid.NewGuid()
.ToString()) //For a real case it should use a maskinporten client id, but that means you cant post the same system again
.WithVendor("312605031")
.WithResource(value: "kravogbetaling", id: "urn:altinn:resource")
.WithRedirectUrl("https://altinn.no")
.WithToken(maskinportenToken);

var response = await _systemRegisterClient.PostSystem(teststate);
Assert.True(response.IsSuccessStatusCode, response.ReasonPhrase);

// Prepare New Request for a new SystemUser from a Vendor
var body = await Helper.ReadFile("Resources/Testdata/SystemUser/CreateRequest.json");
body = body
.Replace("{systemId}", teststate.SystemId)
.Replace("{redirectUrl}", teststate.RedirectUrl);

var respons =
await _platformClient.PostAsync("authentication/api/v1/systemuser/request/vendor", body,
maskinportenToken);

var content = await respons.Content.ReadAsStringAsync();
Assert.True(HttpStatusCode.Created == respons.StatusCode,
$"Status code was not Created, but: {respons.StatusCode} - {content}");

// Prepare Approve Request by end user
var requestId = JObject.Parse(content)["id"].ToString();

Check warning on line 234 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Dereference of a possibly null reference.

Check warning on line 234 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Build and Test

Dereference of a possibly null reference.

Check warning on line 234 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze

Dereference of a possibly null reference.

const string party = "50692553";
var manager = new AltinnUser
{
userId = "20012772",
partyId = "51670464",
pid = "64837001585",
};

var token = await _platformClient.GetPersonalAltinnToken(manager);

// End user approves the request
var responseApprove = await _platformClient.PostAsync($"authentication/api/v1/systemuser/request/{party}/{requestId}/approve", null!, token);
Assert.True(HttpStatusCode.OK == responseApprove.StatusCode, $"Status code was not OK, but: {responseApprove.StatusCode} - {await responseApprove.Content.ReadAsStringAsync()}");

// Prepare Create Change Request for an existing SystemUser by a Vendor
var bodyChange = await Helper.ReadFile("Resources/Testdata/SystemUser/CreateChangeRequest.json");

bodyChange = bodyChange
.Replace("{systemId}", teststate.SystemId)
.Replace("{redirectUrl}", teststate.RedirectUrl);

// Use the Verify endpoint to test if the change request returns an OK empty response, ie no change needed
var responsChange = await _platformClient.PostAsync("authentication/api/v1/systemuser/changerequest/vendor/verify", body, maskinportenToken);
Assert.True(HttpStatusCode.OK == responsChange.StatusCode, $"Status code was not Ok, but: {responsChange.StatusCode} - {await responsChange.Content.ReadAsStringAsync()}");

// Use the Verify endpoint to test if the change request returns a set of Required Rights, because the change is needed
var responsChangeNeeded = await _platformClient.PostAsync("authentication/api/v1/systemuser/changerequest/vendor/verify", bodyChange, maskinportenToken);

Assert.True(HttpStatusCode.OK == responsChangeNeeded.StatusCode, $"Status code was not OK, but: {responsChangeNeeded.StatusCode} - {await responsChangeNeeded.Content.ReadAsStringAsync()}");
string changeRequestResponse = JObject.Parse(await responsChangeNeeded.Content.ReadAsStringAsync()).ToString();
string requiredRights = JObject.Parse(changeRequestResponse)["requiredRights"].ToString();

Check warning on line 266 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Dereference of a possibly null reference.

Check warning on line 266 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Build and Test

Dereference of a possibly null reference.

Check warning on line 266 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze

Dereference of a possibly null reference.

// Use the Create endpoint to create the change request, returns a ChangeRequestResponse
var responsChangeCreate = await _platformClient.PostAsync("authentication/api/v1/systemuser/changerequest/vendor", bodyChange, maskinportenToken);

Assert.True(HttpStatusCode.Created == responsChangeCreate.StatusCode, $"Status code was not OK, but: {responsChangeCreate.StatusCode} - {await responsChangeCreate.Content.ReadAsStringAsync()}");
string changeRequestResponseCreated = JObject.Parse(await responsChangeCreate.Content.ReadAsStringAsync()).ToString();
string requestIdChange = JObject.Parse(changeRequestResponseCreated)["id"].ToString();

Check warning on line 273 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Dereference of a possibly null reference.

Check warning on line 273 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Build and Test

Dereference of a possibly null reference.

Check warning on line 273 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze

Dereference of a possibly null reference.
Assert.NotEmpty(requestIdChange);

var responseApproveChange = await _platformClient.PostAsync($"authentication/api/v1/systemuser/changerequest/{party}/{requestIdChange}/approve", null!, token);
Assert.True(HttpStatusCode.OK == responseApproveChange.StatusCode, $"Status code was not OK, but: {responseApproveChange.StatusCode} - {await responseApproveChange.Content.ReadAsStringAsync()}");
}


/// <summary>
/// https://docs.altinn.studio/nb/authentication/guides/systemauthentication-for-systemproviders/
/// </summary>
//[Fact]
public async Task UseSystemUser()

Check warning on line 285 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Check warning on line 285 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Public method 'UseSystemUser' on test class 'SystemUserTests' should be marked as a Fact. Reduce the visibility of the method, or add a Fact attribute to the method. (https://xunit.net/xunit.analyzers/rules/xUnit1013)

Check warning on line 285 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Build and Test

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Check warning on line 285 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Build and Test

Public method 'UseSystemUser' on test class 'SystemUserTests' should be marked as a Fact. Reduce the visibility of the method, or add a Fact attribute to the method. (https://xunit.net/xunit.analyzers/rules/xUnit1013)

Check warning on line 285 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Check warning on line 285 in test/Altinn.Platform.Authentication.SystemIntegrationTests/Tests/SystemUserTests.cs

View workflow job for this annotation

GitHub Actions / Analyze

Public method 'UseSystemUser' on test class 'SystemUserTests' should be marked as a Fact. Reduce the visibility of the method, or add a Fact attribute to the method. (https://xunit.net/xunit.analyzers/rules/xUnit1013)
{
//Bruk jwt og hent maskinporten-token direkte
}
Expand Down
Loading