refactor(auth): decouple Steam handler from request DTO shape

Translation middleware now extracts viewer_id/steam_id/steam_session_ticket
from the decrypted msgpack dict into HttpContext.Items before the typed
DTO deserialize. The Steam handler reads from there instead of re-parsing
Request.Body — so authed action DTOs no longer need to inherit BaseRequest
to keep the auth fields alive through the msgpack→DTO→JSON pivot.

Retires the recurring footgun documented in
docs/superpowers/specs/2026-06-02-baseRequest-auth-footgun-improvement.md
(2026-05-25 basic-puzzle, 2026-05-28 deck-code, 2026-06-02 Phase 3 Bot,
2026-06-10 profile/index + item_acquire_history/info + user_mypage/update).

Pinned by AuthDecouplingTests — posts an encrypted msgpack body to
/profile/index (DTO does not inherit BaseRequest) through the real
translation middleware + auth handler and asserts 200. Adds an
EncryptedMsgpackHelper + useRealAuthHandler factory flag, reusable for
future wire-shape tests.

ProfileIndexRequest, ItemAcquireHistoryInfoRequest, and
UserMyPageUpdateRequest revert to the naked shape — the per-DTO
workarounds become vestigial under the new architecture.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
gamer147
2026-06-10 12:29:10 -04:00
parent b18b24b085
commit 1960e28298
9 changed files with 247 additions and 67 deletions

View File

@@ -123,17 +123,30 @@ public class ShadowverseTranslationMiddleware : IMiddleware
throw;
}
// Peek the decrypted msgpack as a raw dict to extract the auth tuple BEFORE the typed
// DTO deserialize drops anything the action's DTO doesn't model. Stash the result in
// HttpContext.Items so SteamSessionAuthenticationHandler can read it without depending
// on the DTO shape — that's the whole point of the decoupling, see
// docs/superpowers/specs/2026-06-02-baseRequest-auth-footgun-improvement.md. Failures
// here are non-fatal: the auth handler will surface a 401 with a more specific reason
// (missing ticket vs corrupt body) than we could from middleware.
if (!skipEncryption)
{
TryStashAuthFields(context, decryptedBytes);
}
var firstParam = endpointDescriptor.Parameters.FirstOrDefault();
if (firstParam is null)
{
// Action method has no parameters — middleware can't bind the (encrypted+msgpacked)
// body to anything. The codebase convention is to take a BaseRequest even for body-
// less endpoints (see e.g. PuzzleController.Info(BaseRequest _)). Fail loud with a
// specific message rather than NREing below on .ParameterType.
// body to anything. Fail loud with a specific message rather than NREing below on
// .ParameterType. Authed actions can declare any DTO shape (auth fields are already
// stashed via TryStashAuthFields above); they just need ONE parameter so the binder
// has somewhere to put the rewritten JSON body.
throw new InvalidOperationException(
$"Action {endpointDescriptor.DisplayName} has no parameters; the SV translation " +
"middleware needs at least one to bind the decrypted body. Add a BaseRequest parameter " +
"(or a derived DTO) — see other *Info/*Top actions for the convention.");
"middleware needs at least one to bind the decrypted body. Add a request DTO " +
"parameter — even an empty one (see ProfileIndexRequest for the minimal shape).");
}
Type requestType = firstParam.ParameterType;
object? data;
@@ -271,6 +284,54 @@ public class ShadowverseTranslationMiddleware : IMiddleware
context.Response.Body = originalResponsebody;
}
/// <summary>
/// Pulls <c>viewer_id</c> / <c>steam_id</c> / <c>steam_session_ticket</c> out of the
/// decrypted msgpack body and stashes them in <c>HttpContext.Items[AuthFields.ContextKey]</c>.
/// Lets the Steam handler read the auth tuple from a separate channel so action DTOs no
/// longer need to inherit <c>BaseRequest</c> just so the handler can find the ticket.
/// Failures (corrupt body, non-map root, missing keys) are silent on purpose: the auth
/// handler will surface a more specific 401 reason than we can here.
/// </summary>
private static void TryStashAuthFields(HttpContext context, byte[] decryptedBytes)
{
try
{
var raw = MessagePackSerializer.Deserialize<Dictionary<object, object?>>(
decryptedBytes,
MessagePackSerializerOptions.Standard.WithResolver(ContractlessStandardResolver.Instance));
if (raw is null) return;
context.Items[Security.SteamSessionAuthentication.AuthFields.ContextKey] =
new Security.SteamSessionAuthentication.AuthFields
{
ViewerId = TryGetString(raw, "viewer_id"),
SteamId = TryGetUlong(raw, "steam_id"),
SteamSessionTicket = TryGetString(raw, "steam_session_ticket"),
};
}
catch
{
// Malformed body — auth handler will fail with its own diagnostic.
}
}
private static string? TryGetString(Dictionary<object, object?> raw, string key) =>
raw.TryGetValue(key, out var v) ? v as string : null;
private static ulong TryGetUlong(Dictionary<object, object?> raw, string key)
{
if (!raw.TryGetValue(key, out var v) || v is null) return 0;
return v switch
{
ulong u => u,
long l => unchecked((ulong)l),
int i => unchecked((ulong)(long)i),
uint ui => ui,
string s => ulong.TryParse(s, out var parsed) ? parsed : 0,
_ => 0,
};
}
/// <summary>
/// Walks a parsed JSON tree into the plain CLR shape MessagePack-CSharp's contractless
/// resolver understands: objects → <c>Dictionary&lt;string, object?&gt;</c>, arrays →

View File

@@ -3,8 +3,10 @@ using MessagePack;
namespace SVSim.EmulatedEntrypoint.Models.Dtos.ItemAcquireHistory;
/// <summary>
/// Empty request body. The endpoint takes no parameters; this DTO exists so model binding
/// resolves the envelope correctly.
/// Empty request body — the endpoint takes no parameters. Does not inherit BaseRequest: the
/// translation middleware stashes the auth tuple into HttpContext.Items before the typed DTO
/// deserialize, so the Steam handler reads them from there. See ProfileIndexRequest +
/// AuthDecouplingTests for the pattern.
/// </summary>
[MessagePackObject(true)]
public sealed class ItemAcquireHistoryInfoRequest

View File

@@ -3,8 +3,12 @@ using MessagePack;
namespace SVSim.EmulatedEntrypoint.Models.Dtos.Profile;
/// <summary>
/// Empty request body. The endpoint takes no parameters (client task uses BaseParam directly);
/// this DTO exists so model binding resolves the envelope correctly.
/// Empty request body — the endpoint takes no parameters and deliberately does NOT inherit
/// BaseRequest. The translation middleware pulls the auth tuple
/// (viewer_id / steam_id / steam_session_ticket) straight out of the decrypted msgpack dict
/// into <c>HttpContext.Items[AuthFields.ContextKey]</c> before deserializing into this DTO,
/// so the Steam handler reads them from there rather than re-parsing the rewritten body.
/// See <c>AuthDecouplingTests</c> for the integration test that pins this contract down.
/// </summary>
[MessagePackObject(true)]
public sealed class ProfileIndexRequest

View File

@@ -6,7 +6,9 @@ namespace SVSim.EmulatedEntrypoint.Models.Dtos.UserMyPage;
/// <summary>
/// Body of <c>POST /user_mypage/update</c>. Client task: <c>MyPageSettingUpdateTask</c>
/// (Shadowverse_Code_2026-05-23/Wizard/MyPageSettingUpdateTask.cs). Note that
/// <c>select_type</c> is the only int on the wire — id fields are strings.
/// <c>select_type</c> is the only int on the wire — id fields are strings. Does not inherit
/// BaseRequest: the translation middleware stashes the auth tuple into HttpContext.Items
/// before the typed DTO deserialize, so the Steam handler reads them from there.
/// </summary>
[MessagePackObject]
public sealed class UserMyPageUpdateRequest

View File

@@ -0,0 +1,22 @@
namespace SVSim.EmulatedEntrypoint.Security.SteamSessionAuthentication;
/// <summary>
/// Auth tuple extracted from the decrypted msgpack request body BEFORE it gets pivoted into
/// the action's typed DTO. Stashed into <c>HttpContext.Items</c> under <see cref="ContextKey"/>
/// by <c>ShadowverseTranslationMiddleware</c> so <c>SteamSessionAuthenticationHandler</c> can
/// read the ticket without depending on the DTO modelling these fields.
///
/// History: see <c>docs/superpowers/specs/2026-06-02-baseRequest-auth-footgun-improvement.md</c>.
/// The pre-existing route required every authed DTO to inherit <c>BaseRequest</c> (otherwise
/// the msgpack→DTO→JSON pivot dropped the auth fields and the handler silently 401'd live).
/// Surfacing the fields via a separate channel decouples auth from DTO shape entirely.
/// </summary>
public sealed class AuthFields
{
/// <summary>Items key under which the middleware stashes / the handler reads the auth tuple.</summary>
public const string ContextKey = "SVSim.AuthFields";
public string? ViewerId { get; init; }
public ulong SteamId { get; init; }
public string? SteamSessionTicket { get; init; }
}

View File

@@ -1,7 +1,5 @@
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using SVSim.Database.Enums;
@@ -9,21 +7,12 @@ using SVSim.Database.Models;
using SVSim.Database.Repositories.Viewer;
using SVSim.EmulatedEntrypoint.Constants;
using SVSim.EmulatedEntrypoint.Extensions;
using SVSim.EmulatedEntrypoint.Models.Dtos.Requests;
using SVSim.EmulatedEntrypoint.Services;
namespace SVSim.EmulatedEntrypoint.Security.SteamSessionAuthentication;
public class SteamSessionAuthenticationHandler : AuthenticationHandler<SteamAuthenticationHandlerOptions>
{
// Must mirror the controller-side JSON options — the translation middleware rewrites the
// request body in snake_case, and we have to read it back the same way or every property
// binds to null and we NRE downstream against the Steam ticket.
private static readonly JsonSerializerOptions RequestJsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
};
private readonly SteamSessionService _sessionService;
private readonly IViewerRepository _viewerRepository;
public SteamSessionAuthenticationHandler(IOptionsMonitor<SteamAuthenticationHandlerOptions> options, ILoggerFactory logger, UrlEncoder encoder, SteamSessionService sessionService, IViewerRepository viewerRepository) : base(options, logger, encoder)
@@ -48,65 +37,43 @@ public class SteamSessionAuthenticationHandler : AuthenticationHandler<SteamAuth
{
return AuthenticateResult.NoResult();
}
byte[] requestBytes;
try
{
using (var requestBytesStream = new MemoryStream())
{
// Reset request stream
Request.Body.Seek(0, SeekOrigin.Begin);
await Request.Body.CopyToAsync(requestBytesStream);
requestBytes = requestBytesStream.ToArray();
// Reset request stream
Request.Body.Seek(0, SeekOrigin.Begin);
}
}
catch (Exception e)
// Read the auth tuple from HttpContext.Items, populated by ShadowverseTranslationMiddleware
// off the raw decrypted msgpack dict BEFORE the action's typed DTO deserialize. This
// decouples auth from DTO shape — see AuthFields and the design spec at
// docs/superpowers/specs/2026-06-02-baseRequest-auth-footgun-improvement.md. The prior
// approach re-parsed Request.Body as JSON into a BaseRequest; any action whose DTO didn't
// inherit BaseRequest silently 401'd because the msgpack→DTO→JSON pivot dropped the fields.
if (Context.Items[AuthFields.ContextKey] is not AuthFields auth)
{
Logger.LogWarning(e, "Auth: failed to read request body on {Path}.", path);
return AuthenticateResult.Fail("Failed to read request body.");
}
// Convert bytes to json
string requestString = Encoding.UTF8.GetString(requestBytes);
BaseRequest? requestJson;
try
{
requestJson = JsonSerializer.Deserialize<BaseRequest>(requestString, RequestJsonOptions);
}
catch (JsonException ex)
{
Logger.LogWarning(ex,
"Auth: failed to JSON-parse request body on {Path} (bodyLen={BodyLen}). " +
"Translation middleware should have rewritten this to JSON — if it didn't, the request bypassed translation (non-Unity UA?).",
path, requestBytes.Length);
Logger.LogWarning(
"Auth: no AuthFields in HttpContext.Items on {Path}. The translation middleware " +
"either didn't run (non-Unity UA?) or the body wasn't a msgpack map.",
path);
return AuthenticateResult.Fail("Invalid request body.");
}
if (requestJson is null || string.IsNullOrEmpty(requestJson.SteamSessionTicket))
if (string.IsNullOrEmpty(auth.SteamSessionTicket))
{
Logger.LogWarning(
"Auth: request body missing steam_session_ticket on {Path} (bodyLen={BodyLen}, hasViewerId={HasViewerId}, steamId={SteamId}).",
path, requestBytes.Length,
!string.IsNullOrEmpty(requestJson?.ViewerId), requestJson?.SteamId ?? 0);
"Auth: request body missing steam_session_ticket on {Path} (hasViewerId={HasViewerId}, steamId={SteamId}).",
path, !string.IsNullOrEmpty(auth.ViewerId), auth.SteamId);
return AuthenticateResult.Fail("Invalid request body.");
}
// Check steam session validity
bool sessionIsValid = _sessionService.IsTicketValidForUser(requestJson.SteamSessionTicket, requestJson.SteamId);
bool sessionIsValid = _sessionService.IsTicketValidForUser(auth.SteamSessionTicket, auth.SteamId);
if (!sessionIsValid)
{
Logger.LogWarning(
"Auth: Steam ticket rejected on {Path} for steamId={SteamId} (ticketLen={TicketLen}). " +
"See SteamSessionService logs above for the underlying Steam reason (BeginAuthSession failure, duplicate, etc.).",
path, requestJson.SteamId, requestJson.SteamSessionTicket.Length);
path, auth.SteamId, auth.SteamSessionTicket.Length);
return AuthenticateResult.Fail("Invalid ticket.");
}
Viewer? viewer =
await _viewerRepository.GetViewerBySocialConnection(SocialAccountType.Steam, requestJson.SteamId);
await _viewerRepository.GetViewerBySocialConnection(SocialAccountType.Steam, auth.SteamId);
if (viewer is null)
{
@@ -123,12 +90,12 @@ public class SteamSessionAuthenticationHandler : AuthenticationHandler<SteamAuth
viewer = await _viewerRepository.GetViewerByUdid(u);
if (viewer is not null)
{
await _viewerRepository.LinkSteamToViewer(viewer.Id, requestJson.SteamId);
await _viewerRepository.LinkSteamToViewer(viewer.Id, auth.SteamId);
// Re-read with socials so transition_account_data downstream sees the new link.
viewer = await _viewerRepository.GetViewerWithSocials(viewer.Id) ?? viewer;
Logger.LogInformation(
"Auth: linked steamId={SteamId} to UDID-keyed viewer_id={ViewerId} on {Path} (first-Steam-touch).",
requestJson.SteamId, viewer.Id, path);
auth.SteamId, viewer.Id, path);
}
}
@@ -137,7 +104,7 @@ public class SteamSessionAuthenticationHandler : AuthenticationHandler<SteamAuth
Logger.LogWarning(
"Auth: no viewer linked to steamId={SteamId} on {Path}, and no UDID-keyed viewer to link to. " +
"Client must call /tool/signup before authenticated endpoints.",
requestJson.SteamId, path);
auth.SteamId, path);
return AuthenticateResult.Fail("User not found.");
}
}
@@ -150,7 +117,7 @@ public class SteamSessionAuthenticationHandler : AuthenticationHandler<SteamAuth
identity.AddClaim(new Claim(ClaimTypes.Name, viewer.DisplayName));
identity.AddClaim(new Claim(ShadowverseClaimTypes.ShortUdidClaim, viewer.ShortUdid.ToString()));
identity.AddClaim(new Claim(ShadowverseClaimTypes.ViewerIdClaim, viewer.Id.ToString()));
identity.AddClaim(new Claim(SteamAuthenticationConstants.SteamIdClaim, requestJson.SteamId.ToString()));
identity.AddClaim(new Claim(SteamAuthenticationConstants.SteamIdClaim, auth.SteamId.ToString()));
// Build and return final ticket
AuthenticationTicket ticket =