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

Feature/signing #956

Draft
wants to merge 48 commits into
base: main
Choose a base branch
from
Draft

Feature/signing #956

wants to merge 48 commits into from

Conversation

HauklandJ
Copy link
Contributor

@HauklandJ HauklandJ commented Dec 6, 2024

Description

PR so that vi can publish an experimental package

Related Issue(s)

  • #{issue number}

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)
  • All tests run green

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

HauklandJ and others added 30 commits September 26, 2024 09:31
* adr for transaction handling

* scaffold signee service
… is supplied, authorize it as a write action. Move deletion of stale data elements to ProcessTaskInitializer.
* Expose endpoint for searching for person using ssn and last name.

* Use class and drop dto postfix.

* Move mapping to reponse class.

* Add success property to PersonSearchResult. Move person details into nested object.
* adds endpoint for getting an organisation from Enhetsregisteret

* renames OrganisationSearch -> Lookup
* temp

* feat: add phone and email to signee state

* split signee states on person/org, handle delegation before notification

* split signing notification and delegation to seperate services

* Move SigneeParty to Models folder

* update signeeConfig -> signeeParty

* split out method for processing signees to support retries

* restructure signeecontext, party and state

* update signing service to use new signingcontext structure

* split notification config based on the receiving system

* Make telemetry nullable in signing service.

* some more stuff

* Fix compilation error

* Touples in notification service. Sms number from registry. Store reason for sms/email failure.

* Extract SigningService interface. Various adjustments after mob session.

* For now: Add user action for initializing delegated signing.

---------

Co-authored-by: Bjørn Tore Gjerde <[email protected]>
* add model for delegation request

* add step builder for delegation request

* add scaffold for delegation client

* add scaffold to signing delegation service

* temp solution for const instead of magic strings

* add delegation client

* weird state

* update handling of party id to use party uuid

* rm sign delegate rights from access management client
# Conflicts:
#	src/Altinn.App.Core/Configuration/PlatformSettings.cs
#	src/Altinn.App.Core/Extensions/ServiceCollectionExtensions.cs
* update builder to standard set in correspondance (1/2)

* restructure: add builders folder

* formatting

* add TryGet method to retrieve app resource id

* cleanup

* formatting

* add custom exceptions

* use IOptions for plattformsettings

* simplify builder

* format

* trailing comma

* more formatting
* update controllers

* add 500 annotation for org lookup

* fix copy pasta

* update swagger

* lastname usage goes too deep (storage)

* update swagger

* update test paths

* use 200 OK when no hit

* typo

* log error

* format

* use the correct namespacing for the logger

* shorten method
@HauklandJ HauklandJ added the feature Label Pull requests with new features. Used when generation releasenotes label Dec 6, 2024

_logger.LogInformation(
"Initialize delegated singing action handler invoked for instance {Id}. In task: {CurrentTaskId}",
context.Instance.Id,

Check failure

Code scanning / CodeQL

Log entries created from user input High

This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.

Copilot Autofix AI 5 days ago

To fix the problem, we need to sanitize the context.Instance.Id before logging it. Since the log entries are plain text, we should remove any newline characters from the Instance.Id to prevent log forging attacks. This can be done using the String.Replace method to replace newline characters with an empty string.

Suggested changeset 1
src/Altinn.App.Core/Features/Action/InitializeDelegatedSigningUserAction.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/Altinn.App.Core/Features/Action/InitializeDelegatedSigningUserAction.cs b/src/Altinn.App.Core/Features/Action/InitializeDelegatedSigningUserAction.cs
--- a/src/Altinn.App.Core/Features/Action/InitializeDelegatedSigningUserAction.cs
+++ b/src/Altinn.App.Core/Features/Action/InitializeDelegatedSigningUserAction.cs
@@ -79,5 +79,6 @@
 
+        string sanitizedInstanceId = context.Instance.Id.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
         _logger.LogInformation(
             "Initialize delegated singing action handler invoked for instance {Id}. In task: {CurrentTaskId}",
-            context.Instance.Id,
+            sanitizedInstanceId,
             currentTask.Id
EOF
@@ -79,5 +79,6 @@

string sanitizedInstanceId = context.Instance.Id.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
_logger.LogInformation(
"Initialize delegated singing action handler invoked for instance {Id}. In task: {CurrentTaskId}",
context.Instance.Id,
sanitizedInstanceId,
currentTask.Id
Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
@HauklandJ
Copy link
Contributor Author

/publish

@HauklandJ
Copy link
Contributor Author

/publish

Copy link

github-actions bot commented Dec 6, 2024

bjorntore and others added 2 commits December 9, 2024 12:46
* WIP persisting signee contexts

* test data

* use party id instead of partyuuid in singing context

* wip: persist signature state

* wip: Make SigneeContext classes public because of json serialization/deserialization.

* set debug type to portable for core and api

* working state for persisting and reading signee context

* add missing xml comments

* update swagger

* make models internal

---------

Co-authored-by: Camilla Marie Dalan <[email protected]>
Co-authored-by: Bjørn Tore Gjerde <[email protected]>
List<SigneeContext> organisationSigneeContexts = await GetOrganisationSigneeContexts(taskId, signeesResult, ct);
List<SigneeContext> signeeContexts = [.. personSigneeContexts, .. organisationSigneeContexts];

_logger.LogInformation("Assigning signees to task {TaskId}: {SigneeContexts}", taskId, signeeContexts.Count);

Check failure

Code scanning / CodeQL

Log entries created from user input High

This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.

Copilot Autofix AI 5 days ago

To fix the problem, we need to sanitize the taskId before logging it. Specifically, we should remove any newline characters from the taskId to prevent log forging. This can be done using the Replace method to remove newline characters.

Suggested changeset 1
src/Altinn.App.Core/Features/Signing/SigningService.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/Altinn.App.Core/Features/Signing/SigningService.cs b/src/Altinn.App.Core/Features/Signing/SigningService.cs
--- a/src/Altinn.App.Core/Features/Signing/SigningService.cs
+++ b/src/Altinn.App.Core/Features/Signing/SigningService.cs
@@ -81,3 +81,4 @@
 
-        _logger.LogInformation("Assigning signees to task {TaskId}: {SigneeContexts}", taskId, signeeContexts.Count);
+        string sanitizedTaskId = taskId.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
+        _logger.LogInformation("Assigning signees to task {TaskId}: {SigneeContexts}", sanitizedTaskId, signeeContexts.Count);
 
EOF
@@ -81,3 +81,4 @@

_logger.LogInformation("Assigning signees to task {TaskId}: {SigneeContexts}", taskId, signeeContexts.Count);
string sanitizedTaskId = taskId.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
_logger.LogInformation("Assigning signees to task {TaskId}: {SigneeContexts}", sanitizedTaskId, signeeContexts.Count);

Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options

AltinnSignatureConfiguration signatureConfiguration = GetAltinnSignatureConfiguration(taskId);
ApplicationMetadata appMetadata = await _appMetadata.GetApplicationMetadata();
_logger.LogInformation($"Starting signing task for instance {instance.Id}");

Check failure

Code scanning / CodeQL

Log entries created from user input High

This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.
This log entry depends on a
user-provided value
.

Copilot Autofix AI 5 days ago

To fix the problem, we need to sanitize the instance.Id before logging it. Since the log entries are plain text, we should remove any newline characters from the instance.Id to prevent log forging. This can be done using the Replace method to remove newline characters.

Suggested changeset 1
src/Altinn.App.Core/Internal/Process/ProcessTasks/SigningProcessTask.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/Altinn.App.Core/Internal/Process/ProcessTasks/SigningProcessTask.cs b/src/Altinn.App.Core/Internal/Process/ProcessTasks/SigningProcessTask.cs
--- a/src/Altinn.App.Core/Internal/Process/ProcessTasks/SigningProcessTask.cs
+++ b/src/Altinn.App.Core/Internal/Process/ProcessTasks/SigningProcessTask.cs
@@ -72,3 +72,3 @@
         ApplicationMetadata appMetadata = await _appMetadata.GetApplicationMetadata();
-        _logger.LogInformation($"Starting signing task for instance {instance.Id}");
+        _logger.LogInformation($"Starting signing task for instance {instance.Id.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "")}");
         _logger.LogInformation($"Signature configuration: {signatureConfiguration.SigneeStatesDataTypeId}");
EOF
@@ -72,3 +72,3 @@
ApplicationMetadata appMetadata = await _appMetadata.GetApplicationMetadata();
_logger.LogInformation($"Starting signing task for instance {instance.Id}");
_logger.LogInformation($"Starting signing task for instance {instance.Id.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "")}");
_logger.LogInformation($"Signature configuration: {signatureConfiguration.SigneeStatesDataTypeId}");
Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
bjorntore and others added 9 commits December 16, 2024 11:12
* adds self links to signing data elements

* updates oas
* rename method

* add terlemetry to singing delegation

* use instancemuitator instead of instance

* lastname changes

* format

* temp fix for bad model

* add debug logging

* format

* domain model for application resource id

* format

* use app resource id

* add AppResourceId and simplify parameters to signing delegation

* debug logging

* lets try loggin again

* format

* update instantiation of AppIdentifier

* public

* use actual instance id

* inject taskId as param, due to being unable to resolve it

* add delegation builder test

* better logging for access management issues

* rm unused using

* better logging

* just log everything

* just log everything but better

* forgot one

* add summary for all public props

* use party uuid

* clarify vars, rm comments

* log response

* summaries

* add app and org delegation

* simplify delegation abstractions

* move appResourceId into a named namespace

* rm builders, use domain objects

* client cleanup

* add revoke signee rights

* format

* rm debug logging

* workaround -> work around

* block scoped variables

* rm debug logging of sensitive data

* delagate from current user

* use UserParty instead of Party
* simplify lastname handling

* get lastname from fullname

* use invariant culture

* rm redundant semi

* update summary for PersonSignee.FullName
Comment on lines +31 to +89
foreach (SigneeContext signeeContext in signeeContexts)
{
if (signeeContext.SigneeState.IsAccessDelegated is true)
{
try
{
DelegationRequest delegationRequest = new()
{
ResourceId = appResourceId.Value,
InstanceId = instanceGuid,
From = new DelegationParty
{
Value =
delegatorParty.PartyUuid.ToString()
?? throw new InvalidOperationException("Delegator: PartyUuid is null"),
},
To = new DelegationParty
{
Value =
signeeContext.Party.PartyUuid.ToString()
?? throw new InvalidOperationException("Delegatee: PartyUuid is null"),
},
Rights =
[
new RightRequest
{
Resource =
[
new AppResource { Value = appIdentifier.App },
new OrgResource { Value = appIdentifier.Org },
new TaskResource { Value = taskId },
],
Action = new AltinnAction { Value = ActionType.Read },
},
new RightRequest
{
Resource =
[
new AppResource { Value = appIdentifier.App },
new OrgResource { Value = appIdentifier.Org },
new TaskResource { Value = taskId },
],
Action = new AltinnAction { Value = ActionType.Sign },
},
],
};
DelegationResponse? response = await accessManagementClient.RevokeRights(delegationRequest, ct);
signeeContext.SigneeState.IsAccessDelegated = false;
telemetry?.RecordDelegationRevoke(DelegationResult.Success);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to revoke signee rights");
signeeContext.SigneeState.DelegationFailedReason = "Failed to revoke signee rights: " + ex.Message;
telemetry?.RecordDelegationRevoke(DelegationResult.Error);
success = false;
}
}
}

Check notice

Code scanning / CodeQL

Missed opportunity to use Where Note

This foreach loop
implicitly filters its target sequence
- consider filtering the sequence explicitly using '.Where(...)'.
},
],
};
DelegationResponse? response = await accessManagementClient.RevokeRights(delegationRequest, ct);

Check warning

Code scanning / CodeQL

Useless assignment to local variable Warning

This assignment to
response
is useless, since its value is never read.
Comment on lines +81 to +87
catch (Exception ex)
{
logger.LogError(ex, "Failed to revoke signee rights");
signeeContext.SigneeState.DelegationFailedReason = "Failed to revoke signee rights: " + ex.Message;
telemetry?.RecordDelegationRevoke(DelegationResult.Error);
success = false;
}

Check notice

Code scanning / CodeQL

Generic catch clause Note

Generic catch clause.
},
],
};
DelegationResponse? response = await accessManagementClient.DelegateRights(delegationRequest, ct);

Check warning

Code scanning / CodeQL

Useless assignment to local variable Warning

This assignment to
response
is useless, since its value is never read.
Comment on lines +163 to +169
catch (Exception ex)
{
logger.LogError(ex, "Failed to delegate signee rights");
state.DelegationFailedReason = "Failed to delegate signee rights: " + ex.Message;
telemetry?.RecordDelegation(DelegationResult.Error);
success = false;
}

Check notice

Code scanning / CodeQL

Generic catch clause Note

Generic catch clause.
Comment on lines +111 to +114
if (delegateSuccess)
{
// await signingNotificationService.NotifySignatureTask(signeeContexts, ct);
}

Check warning

Code scanning / CodeQL

Futile conditional Warning

If-statement with an empty then-branch and no else-branch.
{
using var activity = telemetry?.StartAppInstanceRevokeActivity();

HttpResponseMessage? httpResponseMessage = null;

Check notice

Code scanning / CodeQL

Missed 'using' opportunity Note

This variable is manually
disposed
in a
finally block
- consider a C# using statement as a preferable resource management technique.
Comment on lines +68 to +83
catch (Exception e)
{
var ex =
e is AccessManagementRequestException
? e
: new AccessManagementRequestException(
$"Something went wrong when processing the access management request.",
null,
httpResponseMessage?.StatusCode,
httpContent,
e
);
logger.LogError(ex, "Error when processing access management request.");

throw ex;
}

Check notice

Code scanning / CodeQL

Generic catch clause Note

Generic catch clause.
{
using var activity = telemetry?.StartAppInstanceDelegationActivity();

HttpResponseMessage? httpResponseMessage = null;

Check notice

Code scanning / CodeQL

Missed 'using' opportunity Note

This variable is manually
disposed
in a
finally block
- consider a C# using statement as a preferable resource management technique.
Comment on lines +131 to +146
catch (Exception e)
{
var ex =
e is AccessManagementRequestException
? e
: new AccessManagementRequestException(
$"Something went wrong when processing the access management request.",
null,
httpResponseMessage?.StatusCode,
httpContent,
e
);
logger.LogError(ex, "Error when processing access management request.");

throw ex;
}

Check notice

Code scanning / CodeQL

Generic catch clause Note

Generic catch clause.
@HauklandJ
Copy link
Contributor Author

/publish

Copy link

github-actions bot commented Jan 6, 2025

Copy link

sonarqubecloud bot commented Jan 7, 2025

Quality Gate Failed Quality Gate failed

Failed conditions
12.2% Coverage on New Code (required ≥ 65%)
5.2% Duplication on New Code (required ≤ 3%)
E Reliability Rating on New Code (required ≥ A)
10.0% Condition Coverage on New Code (required ≥ 65%)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Label Pull requests with new features. Used when generation releasenotes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants