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

feat: Add support for apps as serviceresource #658

Merged
merged 6 commits into from
Apr 22, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ public CreateDialogCommandValidator(
.NotNull()
.IsValidUri()
.MaximumLength(Constants.DefaultMaxUriLength)
.Must(x => x?.StartsWith(Constants.ServiceResourcePrefix, StringComparison.InvariantCulture) ?? false)
.WithMessage($"'{{PropertyName}}' must start with '{Constants.ServiceResourcePrefix}'.");
.Must(x =>
(x?.StartsWith(Constants.ServiceResourcePrefixGeneric, StringComparison.InvariantCulture) ?? false)
|| (x?.StartsWith(Constants.ServiceResourcePrefixApp, StringComparison.InvariantCulture) ?? false))
.WithMessage($"'{{PropertyName}}' must start with '{Constants.ServiceResourcePrefixGeneric}' or '{Constants.ServiceResourcePrefixApp}'.");

RuleFor(x => x.Party)
.IsValidPartyIdentifier()
Expand Down
3 changes: 2 additions & 1 deletion src/Digdir.Domain.Dialogporten.Domain/Common/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ public static class Constants
public const int DefaultMaxStringLength = 255;
public const int DefaultMaxUriLength = 1023;

public const string ServiceResourcePrefix = "urn:altinn:resource:";
public const string ServiceResourcePrefixGeneric = "urn:altinn:resource:";
public const string ServiceResourcePrefixApp = "urn:altinn:app:";
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ internal static class DecisionRequestHelper
private const string AttributeIdAction = "urn:oasis:names:tc:xacml:1.0:action:action-id";
private const string AttributeIdResource = "urn:altinn:resource";
private const string AttributeIdResourceInstance = "urn:altinn:resourceinstance";
private const string AttributeIdOrg = "urn:altinn:org";
private const string AttributeIdApp = "urn:altinn:app";
private const string AttributeIdAppInstance = "urn:altinn:instance-id";
private const string AttributeIdSubResource = "urn:altinn:subresource";
private const string PermitResponse = "Permit";

Expand Down Expand Up @@ -117,20 +120,47 @@ private static List<XacmlJsonCategory> CreateResourceCategories(

private static XacmlJsonCategory CreateResourceCategory(string id, string serviceResource, Guid? dialogId, XacmlJsonAttribute? partyAttribute, string? subResource = null)
{
var (ns, value) = SplitNsAndValue(serviceResource);
var (ns, value, org) = SplitNsAndValue(serviceResource);
var attributes = new List<XacmlJsonAttribute>
{
new() { AttributeId = ns, Value = value }
};

if (org is not null)
{
attributes.Add(new XacmlJsonAttribute { AttributeId = AttributeIdOrg, Value = org });
}

if (partyAttribute is not null)
{
attributes.Add(partyAttribute);
}

if (dialogId is not null)
{
attributes.Add(new() { AttributeId = AttributeIdResourceInstance, Value = dialogId.ToString() });
if (ns == AttributeIdResource)
{
attributes.Add(new()
{
AttributeId = AttributeIdResourceInstance,
Value = dialogId.ToString()
});
}
else if (ns == AttributeIdAppInstance)
{
// TODO!
// For app instances, we the syntax of the value is "{partyID}/{instanceID}".
// We do not have Altinn partyID in the request, so we cannot support this.
// This means we cannot easily support instance specific authorizations for apps.
// This should probably be fixed in the PDP, lest we use the party lookup service
// to get this value (which would suck).
/*
{
AttributeId = AttributeIdAppInstance,
Value = dialogId.ToString()
});
*/
}
}

if (subResource is not null)
Expand All @@ -145,20 +175,29 @@ private static XacmlJsonCategory CreateResourceCategory(string id, string servic
};
}

private static (string, string) SplitNsAndValue(string serviceResource)
private static (string, string, string?) SplitNsAndValue(string serviceResource)
{
var lastColonIndex = serviceResource.LastIndexOf(':');
if (lastColonIndex == -1 || lastColonIndex == serviceResource.Length - 1)
{
// If we don't recognize the format, we just return the whole string as the value and assume
// that the caller wants to refer a resource in the Resource Registry namespace.
return (AttributeIdResource, serviceResource);
return (AttributeIdResource, serviceResource, null);
}

var ns = serviceResource[..lastColonIndex];
var value = serviceResource[(lastColonIndex + 1)..];

return (ns, value);
if (ns != AttributeIdApp) return (ns, value, null);

// If the namespace is "urn:altinn:app", the value should have the format "app_{org}_{app_id}".
// We want to split this into the org and app id. If not, something is borked in the data,
// and we will probably cause an error in the PDP API (since it throws if the org/app combo
// doesn't let it get to the app policy)
var parts = value.Split('_');
return parts.Length >= 3
? (AttributeIdApp, string.Join('_', parts[2..]), parts[1])
: (AttributeIdApp, value, null);
}

private static XacmlJsonAttribute? GetPartyAttribute(string party)
Expand Down Expand Up @@ -248,10 +287,19 @@ public static DialogSearchAuthorizationResult CreateDialogSearchResponse(
continue;
}

// Get the name of the resource.
// Get the name of the resource. This may be either an app or an generic service resource.
var resourceId = $"r{i + 1}";
var serviceResource = $"{AttributeIdResource}:" + xamlJsonRequestRoot.Request.Resource.First(r => r.Id == resourceId).Attribute
.First(a => a.AttributeId == AttributeIdResource).Value;
var resourceList = xamlJsonRequestRoot.Request.Resource.First(r => r.Id == resourceId).Attribute;
var resource = resourceList.First(a => a.AttributeId is AttributeIdResource or AttributeIdApp);

// If it's an app, we need to include the org code in the service resource
if (resource.AttributeId == AttributeIdApp)
{
var orgCode = resourceList.First(a => a.AttributeId == AttributeIdOrg).Value;
resource.Value = $"app_{orgCode}_{resource.Value}";
}

var serviceResource = resource.AttributeId + ":" + resource.Value;

string party;
var partyOrgNr = xamlJsonRequestRoot.Request.Resource.First(r => r.Id == resourceId).Attribute
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@
using System.Net.Http.Json;
using Digdir.Domain.Dialogporten.Application.Externals;
using Digdir.Domain.Dialogporten.Domain.Common;
using Microsoft.Extensions.Caching.Distributed;
using ZiggyCreatures.Caching.Fusion;

namespace Digdir.Domain.Dialogporten.Infrastructure.Altinn.ResourceRegistry;

internal sealed class ResourceRegistryClient : IResourceRegistry
{
private const string OrgResourceReferenceCacheKey = "OrgResourceReference";
private static readonly DistributedCacheEntryOptions OneDayCacheDuration = new() { AbsoluteExpiration = DateTimeOffset.UtcNow.AddDays(1) };
private static readonly DistributedCacheEntryOptions ZeroCacheDuration = new() { AbsoluteExpiration = DateTimeOffset.MinValue };
private const string ResourceTypeGenericAccess = "GenericAccessResource";
private const string ResourceTypeAltinnApp = "AltinnApp";

private readonly IFusionCache _cache;
private readonly HttpClient _client;
Expand All @@ -34,16 +33,20 @@ public async Task<IReadOnlyCollection<string>> GetResourceIds(string org, Cancel

private async Task<Dictionary<string, string[]>> GetResourceIdsByOrg(CancellationToken cancellationToken)
{
const string searchEndpoint = "resourceregistry/api/v1/resource/search";
const string searchEndpoint = "resourceregistry/api/v1/resource/resourcelist";
var response = await _client
.GetFromJsonAsync<List<ResourceRegistryResponse>>(searchEndpoint, cancellationToken)
?? throw new UnreachableException();

var resourceIdsByOrg = response
.GroupBy(x => x.HasCompetentAuthority.Organization)
.Where(x => x.ResourceType is ResourceTypeGenericAccess or ResourceTypeAltinnApp)
.GroupBy(x => x.HasCompetentAuthority.Organization ?? string.Empty)
.ToDictionary(
x => x.Key,
x => x.Select(x => $"{Constants.ServiceResourcePrefix}{x.Identifier}")
x => x.Select(
x => x.ResourceType == ResourceTypeAltinnApp
? $"{Constants.ServiceResourcePrefixApp}{x.Identifier}"
: $"{Constants.ServiceResourcePrefixGeneric}{x.Identifier}")
.ToArray()
);

Expand All @@ -54,10 +57,14 @@ private sealed class ResourceRegistryResponse
{
public required string Identifier { get; init; }
public required CompetentAuthority HasCompetentAuthority { get; init; }
public required string ResourceType { get; init; }
}

private sealed class CompetentAuthority
{
public required string Organization { get; init; }
// Altinn 2 resources does not always have an organization number as competent authority, only service owner code
// We filter these out anyway, but we need to allow null here
public string? Organization { get; init; }
public required string OrgCode { get; init; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,19 @@ public static IServiceCollection AddInfrastructure(this IServiceCollection servi

services.ConfigureFusionCache(nameof(Altinn.NameRegistry), new()
{
Duration = TimeSpan.FromDays(1)
Duration = TimeSpan.FromHours(24),
FailSafeMaxDuration = TimeSpan.FromHours(26)
elsand marked this conversation as resolved.
Show resolved Hide resolved
})
.ConfigureFusionCache(nameof(Altinn.ResourceRegistry), new()
{
Duration = TimeSpan.FromMinutes(20)
Duration = TimeSpan.FromMinutes(20),
// The resource list is several megabytes and might take a while to process
FactoryHardTimeout = TimeSpan.FromSeconds(10)
})
.ConfigureFusionCache(nameof(Altinn.OrganizationRegistry), new()
{
Duration = TimeSpan.FromDays(1)
Duration = TimeSpan.FromHours(24),
FailSafeMaxDuration = TimeSpan.FromHours(26)
elsand marked this conversation as resolved.
Show resolved Hide resolved
})
.ConfigureFusionCache(nameof(Altinn.Authorization), new()
{
Expand Down Expand Up @@ -187,8 +191,8 @@ public class FusionCacheSettings
public TimeSpan Duration { get; set; } = TimeSpan.FromMinutes(1);
public TimeSpan FailSafeMaxDuration { get; set; } = TimeSpan.FromHours(2);
public TimeSpan FailSafeThrottleDuration { get; set; } = TimeSpan.FromSeconds(30);
public TimeSpan FactorySoftTimeout { get; set; } = TimeSpan.FromMilliseconds(100);
public TimeSpan FactoryHardTimeout { get; set; } = TimeSpan.FromMilliseconds(1500);
public TimeSpan FactorySoftTimeout { get; set; } = TimeSpan.FromSeconds(1);
elsand marked this conversation as resolved.
Show resolved Hide resolved
public TimeSpan FactoryHardTimeout { get; set; } = TimeSpan.FromSeconds(5);
public TimeSpan DistributedCacheSoftTimeout { get; set; } = TimeSpan.FromSeconds(1);
public TimeSpan DistributedCacheHardTimeout { get; set; } = TimeSpan.FromSeconds(2);
public bool AllowBackgroundDistributedCacheOperations { get; set; } = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,40 @@ public void CreateDialogDetailsRequestShouldReturnCorrectRequest()
Assert.Contains(result.Request.MultiRequests.RequestReference, rr => ContainsSameElements(rr.ReferenceId, new List<string> { "s1", "r4", "a4" }));
}

[Fact]
public void CreateDialogDetailsRequestShouldReturnCorrectRequestForApp()
{
// Arrange
var request = CreateDialogDetailsAuthorizationRequest(
GetAsClaims(
("pid", "12345678901"),

// This should not be copied as subject claim since there's a "pid"-claim
("consumer", ConsumerClaimValue)
),
$"{NorwegianOrganizationIdentifier.PrefixWithSeparator}713330310",
isApp: true);

var dialogId = request.DialogId;

// Act
var result = DecisionRequestHelper.CreateDialogDetailsRequest(request);

// Assert
Assert.NotNull(result);
Assert.NotNull(result.Request);
Assert.NotNull(result.Request.Resource);

// Check Resource attributes
var resource1 = result.Request.Resource.FirstOrDefault(r => r.Id == "r1");
Assert.NotNull(resource1);
Assert.Contains(resource1.Attribute, a => a.AttributeId == "urn:altinn:org" && a.Value == "ttd");
Assert.Contains(resource1.Attribute, a => a.AttributeId == "urn:altinn:app" && a.Value == "some-app_with_underscores");

// We cannot support instance id for apps since we don't have a partyId
// Assert.Contains(resource1.Attribute, a => a.AttributeId == "urn:altinn:instance-id" && a.Value == dialogId.ToString());
}

[Fact]
public void CreateDialogDetailsRequestShouldReturnCorrectRequestForConsumerOrgAndPersonParty()
{
Expand Down Expand Up @@ -130,7 +164,7 @@ public void CreateDialogDetailsResponseShouldReturnCorrectResponse()
Assert.DoesNotContain(new AltinnAction("failaction", Constants.MainResource), response.AuthorizedAltinnActions);
}

private static DialogDetailsAuthorizationRequest CreateDialogDetailsAuthorizationRequest(List<Claim> principalClaims, string party)
private static DialogDetailsAuthorizationRequest CreateDialogDetailsAuthorizationRequest(List<Claim> principalClaims, string party, bool isApp = false)
{
var allClaims = new List<Claim>
{
Expand All @@ -140,7 +174,7 @@ private static DialogDetailsAuthorizationRequest CreateDialogDetailsAuthorizatio
return new DialogDetailsAuthorizationRequest
{
Claims = allClaims,
ServiceResource = "urn:altinn:resource:some-service",
ServiceResource = isApp ? "urn:altinn:app:app_ttd_some-app_with_underscores" : "urn:altinn:resource:some-service",
DialogId = Guid.NewGuid(),

// This should be copied resources with attributes "urn:altinn:organizationnumber" if starting with "urn:altinn:organization:identifier-no::"
Expand Down