Enrich AD thumbnailPhoto from SGU profile images
This commit is contained in:
1 parent
21890047e2
commit
77091c023d
9 files changed
+336
-11
No files matched your search
@@ -13,7 +13,8 @@ public sealed record InstitutionalProfile(
|
||||
string? City = null,
|
||||
string? State = null,
|
||||
string? PostalCode = null,
|
||||
InstitutionalGender? Gender = null)
|
||||
InstitutionalGender? Gender = null,
|
||||
byte[]? ThumbnailPhoto = null)
|
||||
{
|
||||
public bool HasValues =>
|
||||
EmployeeNumber is not null ||
|
||||
@@ -28,7 +29,8 @@ public sealed record InstitutionalProfile(
|
||||
City is not null ||
|
||||
State is not null ||
|
||||
PostalCode is not null ||
|
||||
Gender is not null;
|
||||
Gender is not null ||
|
||||
ThumbnailPhoto is not null;
|
||||
|
||||
public InstitutionalProfile Overlay(InstitutionalProfile? values) =>
|
||||
values is null
|
||||
@@ -47,6 +49,7 @@ public sealed record InstitutionalProfile(
|
||||
City = values.City ?? City,
|
||||
State = values.State ?? State,
|
||||
PostalCode = values.PostalCode ?? PostalCode,
|
||||
Gender = values.Gender ?? Gender
|
||||
Gender = values.Gender ?? Gender,
|
||||
ThumbnailPhoto = values.ThumbnailPhoto ?? ThumbnailPhoto
|
||||
};
|
||||
}
|
||||
@@ -17,10 +17,13 @@ internal static class BrokerEventIds
|
||||
internal static readonly EventId ProfileEnrichmentTimeout = new(1202, nameof(ProfileEnrichmentTimeout));
|
||||
internal static readonly EventId ProfileEnrichmentFailure = new(1203, nameof(ProfileEnrichmentFailure));
|
||||
internal static readonly EventId ProfilePageUnavailable = new(1204, nameof(ProfilePageUnavailable));
|
||||
internal static readonly EventId ProfilePhotoUnavailable = new(1205, nameof(ProfilePhotoUnavailable));
|
||||
internal static readonly EventId ProfilePhotoInvalid = new(1206, nameof(ProfilePhotoInvalid));
|
||||
|
||||
internal static readonly EventId DirectorySynchronizationFailure = new(1300, nameof(DirectorySynchronizationFailure));
|
||||
internal static readonly EventId DirectoryOptionalMetadataFailure = new(1301, nameof(DirectoryOptionalMetadataFailure));
|
||||
internal static readonly EventId DirectoryGroupMembershipFailure = new(1302, nameof(DirectoryGroupMembershipFailure));
|
||||
internal static readonly EventId DirectoryRoleGroupMembershipAdded = new(1303, nameof(DirectoryRoleGroupMembershipAdded));
|
||||
internal static readonly EventId DirectoryPasswordChangeDenied = new(1304, nameof(DirectoryPasswordChangeDenied));
|
||||
internal static readonly EventId DirectoryPhotoFailure = new(1305, nameof(DirectoryPhotoFailure));
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
<ProjectReference Include="..\SGU.AuthBroker.Core\SGU.AuthBroker.Core.csproj" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.11" />
|
||||
<PackageReference Include="System.DirectoryServices" Version="10.0.11" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="10.0.11" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -142,6 +142,7 @@ public sealed class ActiveDirectorySynchronizer(
|
||||
user.CommitChanges();
|
||||
|
||||
TryApplyProfile(user, identity, profile, options.DefaultCompany, logger);
|
||||
TryApplyPhoto(user, identity.UserName, profile?.ThumbnailPhoto);
|
||||
TryEnsureRemoteDesktopGroupMembership(user, identity.UserName);
|
||||
|
||||
return new DirectorySyncResult(
|
||||
@@ -264,6 +265,42 @@ public sealed class ActiveDirectorySynchronizer(
|
||||
}
|
||||
}
|
||||
|
||||
private void TryApplyPhoto(DirectoryEntry user, string institutionalUser, byte[]? photo)
|
||||
{
|
||||
if (photo is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (user.Properties["thumbnailPhoto"].Value is byte[] existing &&
|
||||
existing.AsSpan().SequenceEqual(photo))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
user.Properties["thumbnailPhoto"].Value = photo;
|
||||
user.CommitChanges();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogWarning(
|
||||
BrokerEventIds.DirectoryPhotoFailure,
|
||||
exception,
|
||||
"Optional Active Directory thumbnailPhoto could not be committed for {InstitutionalUser}; account synchronization remains completed.",
|
||||
institutionalUser);
|
||||
try
|
||||
{
|
||||
user.RefreshCache();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Photo metadata must not change the successful authentication result.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetGenderMetadata(
|
||||
DirectoryEntry entry,
|
||||
InstitutionalGender? gender,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
@@ -11,6 +13,9 @@ namespace SGU.AuthBroker.Services;
|
||||
|
||||
public sealed class NtlmCredentialValidator : INtlmCredentialValidator
|
||||
{
|
||||
private const int MaximumPhotoBytes = 100 * 1024;
|
||||
private const int MinimumPhotoBytes = 128;
|
||||
private static readonly TimeSpan PhotoTimeout = TimeSpan.FromSeconds(3);
|
||||
private readonly NtlmOptions options;
|
||||
private readonly ILogger<NtlmCredentialValidator> logger;
|
||||
private readonly Func<CredentialCache, CookieContainer, HttpMessageHandler> handlerFactory;
|
||||
@@ -353,6 +358,20 @@ public sealed class NtlmCredentialValidator : INtlmCredentialValidator
|
||||
elapsed).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (string.Equals(profile?.EmployeeNumber, identity.NumericId, StringComparison.Ordinal))
|
||||
{
|
||||
byte[]? photo = await TryFetchPhotoAsync(
|
||||
client,
|
||||
identity,
|
||||
allowedHosts,
|
||||
timeout.Token,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
if (photo is not null)
|
||||
{
|
||||
profile = profile! with { ThumbnailPhoto = photo };
|
||||
}
|
||||
}
|
||||
|
||||
if (profile is null)
|
||||
{
|
||||
logger.LogWarning(
|
||||
@@ -680,6 +699,135 @@ public sealed class NtlmCredentialValidator : INtlmCredentialValidator
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task<byte[]?> TryFetchPhotoAsync(
|
||||
HttpClient client,
|
||||
UserIdentity identity,
|
||||
HashSet<string> allowedHosts,
|
||||
CancellationToken profileTimeoutToken,
|
||||
CancellationToken requestCancellationToken)
|
||||
{
|
||||
// Only a number verified against the authenticated profile is used.
|
||||
// Never follow an image URL supplied by SGU HTML to an arbitrary host.
|
||||
int photoType = identity.Role == InstitutionalRole.Student ? 1 : 2;
|
||||
Uri photoUri = GetProfileUri(
|
||||
$"/psulsa/gadmon/admonPersonal/ashx/Fotografia.ashx?id={identity.NumericId}&tp={photoType}");
|
||||
if (!IsAllowedHttpsUri(photoUri, allowedHosts))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(profileTimeoutToken);
|
||||
timeout.CancelAfter(PhotoTimeout);
|
||||
try
|
||||
{
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, photoUri);
|
||||
using HttpResponseMessage response = await client.SendAsync(
|
||||
request,
|
||||
HttpCompletionOption.ResponseHeadersRead,
|
||||
timeout.Token).ConfigureAwait(false);
|
||||
if (response.StatusCode != HttpStatusCode.OK)
|
||||
{
|
||||
logger.LogWarning(
|
||||
BrokerEventIds.ProfilePhotoUnavailable,
|
||||
"SGU photo for role {Role} returned HTTP {StatusCode}; preserving existing Active Directory photo.",
|
||||
identity.Role,
|
||||
(int)response.StatusCode);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!string.Equals(
|
||||
response.Content.Headers.ContentType?.MediaType,
|
||||
"image/jpeg",
|
||||
StringComparison.OrdinalIgnoreCase) ||
|
||||
response.Content.Headers.ContentLength is > MaximumPhotoBytes)
|
||||
{
|
||||
logger.LogWarning(
|
||||
BrokerEventIds.ProfilePhotoInvalid,
|
||||
"SGU photo for role {Role} had an unsupported media type or size; preserving existing Active Directory photo.",
|
||||
identity.Role);
|
||||
return null;
|
||||
}
|
||||
|
||||
await using Stream stream = await response.Content.ReadAsStreamAsync(timeout.Token)
|
||||
.ConfigureAwait(false);
|
||||
using MemoryStream buffer = new();
|
||||
byte[] chunk = new byte[8192];
|
||||
while (true)
|
||||
{
|
||||
int read = await stream.ReadAsync(chunk.AsMemory(), timeout.Token).ConfigureAwait(false);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (buffer.Length + read > MaximumPhotoBytes)
|
||||
{
|
||||
logger.LogWarning(
|
||||
BrokerEventIds.ProfilePhotoInvalid,
|
||||
"SGU photo for role {Role} exceeded the size limit; preserving existing Active Directory photo.",
|
||||
identity.Role);
|
||||
return null;
|
||||
}
|
||||
|
||||
buffer.Write(chunk, 0, read);
|
||||
}
|
||||
|
||||
byte[] photo = buffer.ToArray();
|
||||
if (photo.Length < MinimumPhotoBytes ||
|
||||
photo[0] != 0xFF || photo[1] != 0xD8 || photo[2] != 0xFF ||
|
||||
photo[^2] != 0xFF || photo[^1] != 0xD9 ||
|
||||
!IsDecodableJpeg(photo))
|
||||
{
|
||||
logger.LogWarning(
|
||||
BrokerEventIds.ProfilePhotoInvalid,
|
||||
"SGU photo for role {Role} was not a valid JPEG payload; preserving existing Active Directory photo.",
|
||||
identity.Role);
|
||||
return null;
|
||||
}
|
||||
|
||||
return photo;
|
||||
}
|
||||
catch (OperationCanceledException) when (requestCancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
logger.LogWarning(
|
||||
BrokerEventIds.ProfilePhotoUnavailable,
|
||||
"SGU photo request for role {Role} timed out; preserving existing Active Directory photo.",
|
||||
identity.Role);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogWarning(
|
||||
BrokerEventIds.ProfilePhotoUnavailable,
|
||||
exception,
|
||||
"SGU photo request for role {Role} failed; preserving existing Active Directory photo.",
|
||||
identity.Role);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsDecodableJpeg(byte[] photo)
|
||||
{
|
||||
try
|
||||
{
|
||||
using MemoryStream input = new(photo, writable: false);
|
||||
using Image image = Image.FromStream(input, useEmbeddedColorManagement: false, validateImageData: true);
|
||||
return image.RawFormat.Guid == ImageFormat.Jpeg.Guid &&
|
||||
image.Width is >= 1 and <= 4096 &&
|
||||
image.Height is >= 1 and <= 4096;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Image decoding is optional metadata validation; malformed input
|
||||
// from the portal must never interrupt account provisioning.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string?> TryPostProfilePageMethodAsync(
|
||||
HttpClient client,
|
||||
Uri requestedUri,
|
||||
|
||||
Reference in new issue
Block a user