mirror of
https://github.com/DorkSquadRR/DorkNet.git
synced 2026-10-25 23:18:44 -07:00
Import march-2020-03-10 from private repo (scrubbed 2026-05-27)
Targets Rec Room 2020.03.10 client (also serves 2020.03.06).
Re-import after adding:
- DorkNet.ClientMod/dorknet-clientmod.json.template — config schema
the launcher's manifest-driven patcher renders into UserData/.
- tools/build-patcher-zip.ps1 — produces dorknet-clientpatch-{key}.zip
for v1-march-* Release uploads.
- .github/workflows/release.yml — on tag push publishes both
dorknet-server-march_2020_03_10-win-x64.zip and
dorknet-clientpatch-march_2020_03_10.zip as Release assets.
Same scrub rules as december; tools/build-patcher-zip.ps1 added to
the maintainer-side allow-list so it survives.
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using DorkNet.Server.Data;
|
||||
|
||||
namespace DorkNet.Server.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Action / controller filter that 403s any request whose
|
||||
/// JWT-resolved player doesn't have <c>IsAdmin == true</c>. Does not
|
||||
/// itself authenticate — pair it with <c>[Authorize]</c> to ensure a
|
||||
/// valid bearer is present before this runs.
|
||||
///
|
||||
/// Usage:
|
||||
/// <code>
|
||||
/// [Authorize]
|
||||
/// [AdminOnly]
|
||||
/// [Route("api/admin/v1")]
|
||||
/// public class AdminController { ... }
|
||||
/// </code>
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
|
||||
public class AdminOnlyAttribute : Attribute, IAsyncAuthorizationFilter
|
||||
{
|
||||
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
||||
{
|
||||
// AuthorizationFilterContext.HttpContext is always populated and
|
||||
// exposes the same ClaimsPrincipal a controller would see, so
|
||||
// there's no reason to round-trip through IHttpContextAccessor
|
||||
// (which isn't even registered in this app's DI container — the
|
||||
// earlier lookup crashed every admin request with
|
||||
// "No service for type IHttpContextAccessor has been registered").
|
||||
if (ControllerBaseExtensions.CurrentPlayerId(context.HttpContext.User) is not long id)
|
||||
{
|
||||
// No JWT → defer to [Authorize]'s 401.
|
||||
context.Result = new UnauthorizedResult();
|
||||
return;
|
||||
}
|
||||
|
||||
var db = context.HttpContext.RequestServices
|
||||
.GetRequiredService<DorkNetDbContext>();
|
||||
var isAdmin = await db.Players
|
||||
.Where(p => p.Id == id)
|
||||
.Select(p => p.IsAdmin)
|
||||
.FirstOrDefaultAsync();
|
||||
if (!isAdmin)
|
||||
context.Result = new ForbidResult();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using DorkNet.Server.Data;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DorkNet.Server.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Short-circuits any authenticated request whose JWT-resolved player has
|
||||
/// a non-null <c>BannedUntil</c> in the future. Sits AFTER
|
||||
/// <c>UseAuthentication</c>/<c>UseAuthorization</c> in the pipeline so the
|
||||
/// claims principal is populated before we look at it.
|
||||
///
|
||||
/// Anonymous requests (no/invalid bearer) pass through unchanged — this
|
||||
/// middleware never short-circuits them. Whether they're allowed is the
|
||||
/// per-endpoint <c>[Authorize]</c> decision, not ours.
|
||||
///
|
||||
/// Lookup is one query per request against the Players table. Cached for
|
||||
/// the request lifetime via the scoped DbContext, so repeated bearer
|
||||
/// checks within one request hit the EF first-level cache.
|
||||
/// </summary>
|
||||
public class BanCheckMiddleware(RequestDelegate next)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext ctx, DorkNetDbContext db)
|
||||
{
|
||||
// Cheap early-out for anonymous traffic — no DB hit.
|
||||
var sub = ctx.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (!long.TryParse(sub, out var playerId))
|
||||
{
|
||||
await next(ctx);
|
||||
return;
|
||||
}
|
||||
|
||||
// Project just the BannedUntil column — no need to materialise the
|
||||
// full player entity for every request.
|
||||
var bannedUntil = await db.Players
|
||||
.Where(p => p.Id == playerId)
|
||||
.Select(p => p.BannedUntil)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (bannedUntil.HasValue && bannedUntil.Value > DateTime.UtcNow)
|
||||
{
|
||||
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
ctx.Response.ContentType = "application/json";
|
||||
await ctx.Response.WriteAsync(JsonSerializer.Serialize(new
|
||||
{
|
||||
Error = "banned",
|
||||
Until = bannedUntil.Value.ToString("o"),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
await next(ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace DorkNet.Server.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Single canonical place for "who is the bearer-resolved player on this
|
||||
/// request." Replaces the per-controller copy-paste of:
|
||||
/// <code>
|
||||
/// private long CurrentPlayerId =>
|
||||
/// long.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
/// </code>
|
||||
/// which historically existed in 10 controllers and silently NPE-bombed
|
||||
/// the action when the bearer was missing instead of returning 401.
|
||||
/// </summary>
|
||||
public static class ControllerBaseExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the bearer-resolved player id, or null when the caller is
|
||||
/// anonymous / the bearer is malformed. Use on optional-auth endpoints.
|
||||
/// </summary>
|
||||
public static long? CurrentPlayerId(this ControllerBase controller) =>
|
||||
CurrentPlayerId(controller.User);
|
||||
|
||||
/// <summary>Overload for non-controller callers (filters,
|
||||
/// middleware) that hold a <see cref="ClaimsPrincipal"/> directly.</summary>
|
||||
public static long? CurrentPlayerId(ClaimsPrincipal user)
|
||||
{
|
||||
var claim = user.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
return long.TryParse(claim, out var id) ? id : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the bearer-resolved player id; throws
|
||||
/// <see cref="UnauthorizedAccessException"/> when missing. Use on
|
||||
/// <c>[Authorize]</c>-decorated endpoints where a missing id is a
|
||||
/// programming error (the framework should have already 401'd).
|
||||
/// </summary>
|
||||
public static long RequireCurrentPlayerId(this ControllerBase controller) =>
|
||||
controller.CurrentPlayerId()
|
||||
?? throw new UnauthorizedAccessException(
|
||||
"Bearer token claim 'NameIdentifier' is missing or non-numeric. " +
|
||||
"If this fired on an [Authorize] endpoint, JWT validation upstream " +
|
||||
"is misconfigured.");
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using DorkNet.Server.Data;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace DorkNet.Server.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Short-circuits any incoming request whose remote IP falls under an
|
||||
/// active <see cref="DorkNet.Server.Data.Entities.IpBanEntity"/> row
|
||||
/// with 403. Sits BEFORE authentication so banned IPs can't spend a
|
||||
/// round-trip negotiating a JWT — the connection terminates as early
|
||||
/// as possible.
|
||||
///
|
||||
/// Lookup is one query against IpBans per request. The table is small
|
||||
/// (a few rows in practice) and the simple "Cidr matches?" filter is
|
||||
/// done in C# rather than SQL because CIDR maths in SQLite is awkward.
|
||||
/// </summary>
|
||||
public class IpBanCheckMiddleware(RequestDelegate next)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext ctx, DorkNetDbContext db)
|
||||
{
|
||||
var remote = ctx.Connection.RemoteIpAddress;
|
||||
if (remote is null)
|
||||
{
|
||||
await next(ctx);
|
||||
return;
|
||||
}
|
||||
|
||||
// Materialise the active-ban list once per request. Could be
|
||||
// cached for ~30s with a hosted service if it ever becomes a
|
||||
// hot path, but right now this is unmeasurable.
|
||||
var bans = await db.IpBans
|
||||
.Where(b => b.Until == null || b.Until > DateTime.UtcNow)
|
||||
.Select(b => b.Cidr)
|
||||
.ToListAsync();
|
||||
|
||||
foreach (var cidr in bans)
|
||||
{
|
||||
if (CidrMatches(cidr, remote))
|
||||
{
|
||||
ctx.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
await ctx.Response.WriteAsync("ip_banned");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await next(ctx);
|
||||
}
|
||||
|
||||
/// <summary>Match a single IP against a CIDR-or-bare-IP string.
|
||||
/// Bare IPs match exactly; CIDRs match if the prefix bits agree.
|
||||
/// Falls back to false on any parse error.</summary>
|
||||
private static bool CidrMatches(string cidr, IPAddress remote)
|
||||
{
|
||||
try
|
||||
{
|
||||
var slash = cidr.IndexOf('/');
|
||||
if (slash < 0)
|
||||
{
|
||||
return IPAddress.TryParse(cidr, out var single) &&
|
||||
single.Equals(remote);
|
||||
}
|
||||
|
||||
var addrPart = cidr[..slash];
|
||||
var prefixPart = cidr[(slash + 1)..];
|
||||
if (!IPAddress.TryParse(addrPart, out var net) ||
|
||||
!int.TryParse(prefixPart, out var prefix))
|
||||
return false;
|
||||
|
||||
// Only IPv4 networks for now — IPv6 CIDR matching is
|
||||
// straightforward but we'd need to mask 128-bit values
|
||||
// and the user's setup is single-host IPv4 anyway.
|
||||
if (net.AddressFamily != AddressFamily.InterNetwork ||
|
||||
remote.AddressFamily != AddressFamily.InterNetwork)
|
||||
return false;
|
||||
|
||||
var netBytes = net.GetAddressBytes();
|
||||
var remoteBytes = remote.GetAddressBytes();
|
||||
int fullBytes = prefix / 8;
|
||||
int extraBits = prefix % 8;
|
||||
|
||||
for (int i = 0; i < fullBytes; i++)
|
||||
if (netBytes[i] != remoteBytes[i]) return false;
|
||||
if (extraBits == 0) return true;
|
||||
|
||||
int mask = 0xFF << (8 - extraBits) & 0xFF;
|
||||
return (netBytes[fullBytes] & mask) == (remoteBytes[fullBytes] & mask);
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user