feat!: sensitive actions need a fresh passkey touch (elevation windows), plus login page hint cleanup [CI]
This commit is contained in:
1 parent
1379b8c7cb
commit
ff45ad086e
27 files changed
+1305
-58
No files matched your search
@@ -37,6 +37,7 @@ public static class ApplicationServiceCollectionExtensions
|
||||
services.AddSingleton<AuthService>();
|
||||
services.AddSingleton<PasskeyService>();
|
||||
services.AddSingleton<AuditService>();
|
||||
services.AddSingleton<ElevationService>();
|
||||
services.AddSingleton<SettingsService>();
|
||||
services.AddSingleton<ReleaseService>();
|
||||
services.AddSingleton<ScheduleService>();
|
||||
|
||||
@@ -15,6 +15,9 @@ public sealed record Principal(PrincipalKind Kind, IReadOnlySet<string> Capabili
|
||||
/// <summary>会话是怎么登录的(<see cref="AuthMethods"/>):只有 passkey 登录的会话以后能提权。API key 为空。</summary>
|
||||
public string AuthMethod { get; init; } = "";
|
||||
|
||||
/// <summary>会话的标识(令牌哈希的十六进制):提权窗口按它记。API key 为空。</summary>
|
||||
public string? SessionId { get; init; }
|
||||
|
||||
/// <summary>审计和归属里显示的名字:用户名,或者 <c>key:令牌名</c>。</summary>
|
||||
public string Label => Kind == PrincipalKind.Token && UserId is null ? "key:" + (Username ?? TokenId) : Username ?? "anonymous";
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ public sealed partial class AuthService
|
||||
}
|
||||
|
||||
UserRecord? user = await _store.GetUserAsync(session.UserId, ct);
|
||||
return user is null ? null : new Principal(PrincipalKind.Session, Principal.SetOf(CapabilityCatalog.ForSession()), user.Id, user.Username, Base64Url.Encode(session.CsrfToken), null) { AuthMethod = session.AuthMethod };
|
||||
return user is null ? null : new Principal(PrincipalKind.Session, Principal.SetOf(CapabilityCatalog.ForSession()), user.Id, user.Username, Base64Url.Encode(session.CsrfToken), null) { AuthMethod = session.AuthMethod, SessionId = Convert.ToHexString(session.IdSha256) };
|
||||
}
|
||||
|
||||
public async ValueTask<Principal?> AuthenticateTokenAsync(string bearer, CancellationToken ct)
|
||||
|
||||
@@ -32,6 +32,7 @@ public static class Capability
|
||||
public const string KeysRead = "keys.read";
|
||||
public const string KeysManage = "keys.manage";
|
||||
|
||||
public const string AccountsRead = "accounts.read";
|
||||
public const string AccountsManage = "accounts.manage";
|
||||
|
||||
public const string AuditRead = "audit.read";
|
||||
@@ -78,7 +79,8 @@ public static class CapabilityCatalog
|
||||
new(Capability.KeysRead, "keys"),
|
||||
new(Capability.KeysManage, "keys", false, false, Capability.KeysRead),
|
||||
|
||||
new(Capability.AccountsManage, "accounts", true),
|
||||
new(Capability.AccountsRead, "accounts"),
|
||||
new(Capability.AccountsManage, "accounts", true, false, Capability.AccountsRead),
|
||||
|
||||
new(Capability.EventsRead, "ops"),
|
||||
new(Capability.AuditRead, "ops"),
|
||||
@@ -130,6 +132,6 @@ public static class CapabilityCatalog
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>登录会话的能力。在 passkey 提权落地之前(docs/access.md 第 12 节步骤 2)会话直接拥有全部能力,包括信任类。</summary>
|
||||
/// <summary>登录会话的能力:全部,包括信任类;信任类的操作还要有效的提权窗口(<see cref="ElevationService"/>)。</summary>
|
||||
public static IReadOnlyList<string> ForSession() => [.. All.Select(c => c.Id)];
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
namespace MoShiro.Backend.Application;
|
||||
|
||||
/// <summary>
|
||||
/// 提权窗口的种类(docs/access.md 第 4 节):加节点(15 分钟)、吊销和删除(5 分钟)、改凭证(60 秒,用一次就没有)。
|
||||
/// 窗口属于会话,不属于用户:换一台设备、一个浏览器就要重新触碰 passkey。
|
||||
/// </summary>
|
||||
public enum ElevationClass
|
||||
{
|
||||
Enroll,
|
||||
Revoke,
|
||||
Credential,
|
||||
}
|
||||
|
||||
public sealed record ElevationWindow(ElevationClass Class, long ExpiresAtMs);
|
||||
|
||||
public static class Elevation
|
||||
{
|
||||
public static string IdOf(ElevationClass elevation) => elevation switch
|
||||
{
|
||||
ElevationClass.Enroll => "enroll",
|
||||
ElevationClass.Revoke => "revoke",
|
||||
_ => "credential",
|
||||
};
|
||||
|
||||
public static bool TryParse(string? id, out ElevationClass elevation)
|
||||
{
|
||||
(bool ok, elevation) = id switch
|
||||
{
|
||||
"enroll" => (true, ElevationClass.Enroll),
|
||||
"revoke" => (true, ElevationClass.Revoke),
|
||||
"credential" => (true, ElevationClass.Credential),
|
||||
_ => (false, default),
|
||||
};
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// <summary>端点要求的能力需要哪一种窗口;不是信任类的能力返回 null。</summary>
|
||||
public static ElevationClass? For(string capability) => capability switch
|
||||
{
|
||||
Capability.FleetEnroll => ElevationClass.Enroll,
|
||||
Capability.FleetRevoke => ElevationClass.Revoke,
|
||||
Capability.AccountsManage => ElevationClass.Credential,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 会话的提权窗口,只在内存里:重启之后需要重新触碰 passkey,这正是想要的。API key 不经过这里(它自己带着能力,创建时已经签过)。
|
||||
/// </summary>
|
||||
public sealed class ElevationService
|
||||
{
|
||||
private readonly BackendOptions _options;
|
||||
private readonly TimeProvider _time;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, Dictionary<ElevationClass, long>> _windows = [];
|
||||
|
||||
public ElevationService(BackendOptions options, TimeProvider time)
|
||||
{
|
||||
_options = options;
|
||||
_time = time;
|
||||
}
|
||||
|
||||
public TimeSpan LifetimeOf(ElevationClass elevation) => elevation switch
|
||||
{
|
||||
ElevationClass.Enroll => TimeSpan.FromMinutes(_options.ElevationEnrollMinutes),
|
||||
ElevationClass.Revoke => TimeSpan.FromMinutes(_options.ElevationRevokeMinutes),
|
||||
_ => TimeSpan.FromSeconds(_options.ElevationCredentialSeconds),
|
||||
};
|
||||
|
||||
/// <summary>开窗口;已经有的窗口重新计时。返回到期时间。</summary>
|
||||
public long Grant(string sessionId, ElevationClass elevation)
|
||||
{
|
||||
long now = _time.GetUtcNow().ToUnixTimeMilliseconds();
|
||||
long expires = now + (long)LifetimeOf(elevation).TotalMilliseconds;
|
||||
lock (_gate)
|
||||
{
|
||||
Prune(now);
|
||||
if (!_windows.TryGetValue(sessionId, out Dictionary<ElevationClass, long>? own))
|
||||
{
|
||||
_windows[sessionId] = own = [];
|
||||
}
|
||||
|
||||
own[elevation] = expires;
|
||||
}
|
||||
|
||||
return expires;
|
||||
}
|
||||
|
||||
/// <summary>窗口是否有效。<paramref name="consume"/> 且是凭证类:同时用掉(一次有效)。</summary>
|
||||
public bool Check(string sessionId, ElevationClass elevation, bool consume)
|
||||
{
|
||||
long now = _time.GetUtcNow().ToUnixTimeMilliseconds();
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_windows.TryGetValue(sessionId, out Dictionary<ElevationClass, long>? own) || !own.TryGetValue(elevation, out long expires) || expires <= now)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (consume && elevation == ElevationClass.Credential)
|
||||
{
|
||||
own.Remove(elevation);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<ElevationWindow> Active(string sessionId)
|
||||
{
|
||||
long now = _time.GetUtcNow().ToUnixTimeMilliseconds();
|
||||
lock (_gate)
|
||||
{
|
||||
return _windows.TryGetValue(sessionId, out Dictionary<ElevationClass, long>? own)
|
||||
? [.. own.Where(w => w.Value > now).OrderBy(w => w.Key).Select(w => new ElevationWindow(w.Key, w.Value))]
|
||||
: [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>主动结束全部窗口(点「结束」或退出登录)。</summary>
|
||||
public void End(string sessionId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_windows.Remove(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
private void Prune(long now)
|
||||
{
|
||||
foreach (string session in _windows.Where(p => p.Value.All(w => w.Value <= now)).Select(p => p.Key).ToList())
|
||||
{
|
||||
_windows.Remove(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ public sealed record PasskeyContext(string RpId, IReadOnlySet<string> Origins);
|
||||
|
||||
public sealed record CreationOptions(string Challenge, string RpId, string RpName, string UserId, string UserName, IReadOnlyList<string> ExcludeCredentials, int TimeoutMs);
|
||||
|
||||
public sealed record RequestOptions(string Challenge, string RpId, int TimeoutMs);
|
||||
public sealed record RequestOptions(string Challenge, string RpId, int TimeoutMs, IReadOnlyList<string>? AllowCredentials = null);
|
||||
|
||||
public sealed record PasskeyRegistration(string Name, string CredentialId, string AttestationObject, string ClientDataJson, IReadOnlyList<string>? Transports);
|
||||
|
||||
@@ -33,16 +33,23 @@ public sealed class PasskeyService
|
||||
|
||||
private readonly IAuthStore _store;
|
||||
private readonly AuthService _auth;
|
||||
private readonly ElevationService _elevation;
|
||||
private readonly TimeProvider _time;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, PendingChallenge> _challenges = [];
|
||||
|
||||
private sealed record PendingChallenge(bool Registration, string? UserId, long ExpiresAtMs);
|
||||
private sealed record PendingChallenge(string Purpose, string? UserId, long ExpiresAtMs);
|
||||
|
||||
public PasskeyService(IAuthStore store, AuthService auth, TimeProvider time)
|
||||
private const string RegisterPurpose = "register";
|
||||
private const string LoginPurpose = "login";
|
||||
|
||||
private static string ElevatePurpose(ElevationClass elevation) => "elevate:" + Elevation.IdOf(elevation);
|
||||
|
||||
public PasskeyService(IAuthStore store, AuthService auth, ElevationService elevation, TimeProvider time)
|
||||
{
|
||||
_store = store;
|
||||
_auth = auth;
|
||||
_elevation = elevation;
|
||||
_time = time;
|
||||
}
|
||||
|
||||
@@ -59,7 +66,7 @@ public sealed class PasskeyService
|
||||
return ValidationError.Fail<CreationOptions>("passkeys", $"at most {MaxPasskeysPerUser} passkeys per user");
|
||||
}
|
||||
|
||||
string challenge = Issue(registration: true, userId);
|
||||
string challenge = Issue(RegisterPurpose, userId);
|
||||
return Result<CreationOptions>.Ok(new CreationOptions(challenge, context.RpId, "MoShiro", Base64Url.Encode(Encoding.UTF8.GetBytes(userId)), username, [.. existing.Select(p => p.Id)], 60_000));
|
||||
}
|
||||
|
||||
@@ -82,7 +89,7 @@ public sealed class PasskeyService
|
||||
}
|
||||
|
||||
// 挑战在 clientDataJSON 里:先取出来,一次有效
|
||||
if (!TryTakeChallenge(clientData, registration: true, userId, out byte[] challenge))
|
||||
if (!TryTakeChallenge(clientData, RegisterPurpose, userId, out byte[] challenge))
|
||||
{
|
||||
return Result<PasskeyRecord>.Fail(MoShiroErrors.ValidationFailed, "the registration challenge is unknown, expired or already used");
|
||||
}
|
||||
@@ -100,43 +107,82 @@ public sealed class PasskeyService
|
||||
: Result<PasskeyRecord>.Fail(MoShiroErrors.NameConflict, "this passkey is already registered");
|
||||
}
|
||||
|
||||
public RequestOptions BeginLogin(PasskeyContext context) => new(Issue(registration: false, null), context.RpId, 60_000);
|
||||
public RequestOptions BeginLogin(PasskeyContext context) => new(Issue(LoginPurpose, null), context.RpId, 60_000);
|
||||
|
||||
/// <summary>验证断言并建立会话。失败一律 unauthorized,不区分原因。</summary>
|
||||
public async ValueTask<Result<LoginResult>> LoginAsync(PasskeyAssertion request, PasskeyContext context, CancellationToken ct)
|
||||
{
|
||||
Result<LoginResult> denied = Result<LoginResult>.Fail(MoShiroErrors.Unauthorized, "invalid credentials");
|
||||
if (!TryDecode(request.CredentialId, out _) || !TryDecode(request.AuthenticatorData, out byte[] authData) || !TryDecode(request.ClientDataJson, out byte[] clientData) || !TryDecode(request.Signature, out byte[] signature))
|
||||
PasskeyRecord? passkey = await VerifyAsync(request, context, LoginPurpose, null, ct);
|
||||
return passkey is null
|
||||
? Result<LoginResult>.Fail(MoShiroErrors.Unauthorized, "invalid credentials")
|
||||
: await _auth.CreateSessionForAsync(passkey.UserId, AuthMethods.Passkey, ct);
|
||||
}
|
||||
|
||||
/// <summary>提权的挑战:绑定用户和窗口种类,并列出这个用户的 passkey 让浏览器只选它们。没有 passkey 的用户没法提权。</summary>
|
||||
public async ValueTask<Result<RequestOptions>> BeginElevationAsync(Principal principal, ElevationClass elevation, PasskeyContext context, CancellationToken ct)
|
||||
{
|
||||
if (principal.UserId is not { } userId || principal.SessionId is null)
|
||||
{
|
||||
return denied;
|
||||
return Result<RequestOptions>.Fail(MoShiroErrors.Forbidden, "only a signed-in user can elevate; API keys carry their capabilities already");
|
||||
}
|
||||
|
||||
if (!TryTakeChallenge(clientData, registration: false, null, out byte[] challenge))
|
||||
IReadOnlyList<PasskeyRecord> own = await _store.ListPasskeysAsync(userId, ct);
|
||||
if (own.Count == 0)
|
||||
{
|
||||
return denied;
|
||||
return Result<RequestOptions>.Fail(MoShiroErrors.ValidationFailed, "register a passkey first (Users, My passkeys)");
|
||||
}
|
||||
|
||||
return Result<RequestOptions>.Ok(new RequestOptions(Issue(ElevatePurpose(elevation), userId), context.RpId, 60_000, [.. own.Select(p => p.Id)]));
|
||||
}
|
||||
|
||||
/// <summary>验证提权的断言(必须是这个用户自己的 passkey)并给这个会话开窗口。失败一律 unauthorized。</summary>
|
||||
public async ValueTask<Result<ElevationWindow>> ElevateAsync(Principal principal, ElevationClass elevation, PasskeyAssertion request, PasskeyContext context, CancellationToken ct)
|
||||
{
|
||||
if (principal.UserId is not { } userId || principal.SessionId is not { } sessionId)
|
||||
{
|
||||
return Result<ElevationWindow>.Fail(MoShiroErrors.Forbidden, "only a signed-in user can elevate; API keys carry their capabilities already");
|
||||
}
|
||||
|
||||
PasskeyRecord? passkey = await VerifyAsync(request, context, ElevatePurpose(elevation), userId, ct);
|
||||
return passkey is null || passkey.UserId != userId
|
||||
? Result<ElevationWindow>.Fail(MoShiroErrors.Unauthorized, "invalid credentials")
|
||||
: Result<ElevationWindow>.Ok(new ElevationWindow(elevation, _elevation.Grant(sessionId, elevation)));
|
||||
}
|
||||
|
||||
/// <summary>验证一份断言:挑战(一次有效、种类和用户对得上)、签名、计数器;通过则记下使用并返回那个 passkey。</summary>
|
||||
private async ValueTask<PasskeyRecord?> VerifyAsync(PasskeyAssertion request, PasskeyContext context, string purpose, string? userId, CancellationToken ct)
|
||||
{
|
||||
if (!TryDecode(request.CredentialId, out _) || !TryDecode(request.AuthenticatorData, out byte[] authData) || !TryDecode(request.ClientDataJson, out byte[] clientData) || !TryDecode(request.Signature, out byte[] signature))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!TryTakeChallenge(clientData, purpose, userId, out byte[] challenge))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
PasskeyRecord? passkey = await _store.FindPasskeyAsync(request.CredentialId, ct);
|
||||
if (passkey is null || !WebAuthnAssertion.Verify(passkey.PublicKeySpki, authData, clientData, signature, context.RpId, challenge, context.Origins.Contains, requireUserVerification: true, out uint signCount))
|
||||
{
|
||||
return denied;
|
||||
return null;
|
||||
}
|
||||
|
||||
// 计数器只增不减;很多同步的 passkey 一直报 0,两边都是 0 时不检查
|
||||
if ((signCount != 0 || passkey.SignCount != 0) && signCount <= passkey.SignCount)
|
||||
{
|
||||
return denied;
|
||||
return null;
|
||||
}
|
||||
|
||||
await _store.TouchPasskeyAsync(passkey.Id, signCount, _time.GetUtcNow().ToUnixTimeMilliseconds(), ct);
|
||||
return await _auth.CreateSessionForAsync(passkey.UserId, AuthMethods.Passkey, ct);
|
||||
return passkey;
|
||||
}
|
||||
|
||||
public ValueTask<IReadOnlyList<PasskeyRecord>> ListAsync(string userId, CancellationToken ct) => _store.ListPasskeysAsync(userId, ct);
|
||||
|
||||
public ValueTask<bool> DeleteAsync(string userId, string passkeyId, CancellationToken ct) => _store.DeletePasskeyAsync(userId, passkeyId, ct);
|
||||
|
||||
private string Issue(bool registration, string? userId)
|
||||
private string Issue(string purpose, string? userId)
|
||||
{
|
||||
byte[] challenge = RandomNumberGenerator.GetBytes(ChallengeBytes);
|
||||
string key = Base64Url.Encode(challenge);
|
||||
@@ -156,14 +202,14 @@ public sealed class PasskeyService
|
||||
}
|
||||
}
|
||||
|
||||
_challenges[key] = new PendingChallenge(registration, userId, now + (long)s_challengeLifetime.TotalMilliseconds);
|
||||
_challenges[key] = new PendingChallenge(purpose, userId, now + (long)s_challengeLifetime.TotalMilliseconds);
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
/// <summary>从 clientDataJSON 取出 challenge,按它找到并移除(一次有效)。</summary>
|
||||
private bool TryTakeChallenge(byte[] clientDataJson, bool registration, string? userId, out byte[] challenge)
|
||||
private bool TryTakeChallenge(byte[] clientDataJson, string purpose, string? userId, out byte[] challenge)
|
||||
{
|
||||
challenge = [];
|
||||
string? text;
|
||||
@@ -185,7 +231,7 @@ public sealed class PasskeyService
|
||||
long now = _time.GetUtcNow().ToUnixTimeMilliseconds();
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_challenges.Remove(Base64Url.Encode(raw), out PendingChallenge? pending) || pending.ExpiresAtMs <= now || pending.Registration != registration || pending.UserId != userId)
|
||||
if (!_challenges.Remove(Base64Url.Encode(raw), out PendingChallenge? pending) || pending.ExpiresAtMs <= now || pending.Purpose != purpose || pending.UserId != userId)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,15 @@ public sealed class BackendOptions
|
||||
/// <summary>允许的来源(逗号分隔,如 <c>https://panel.example.com</c>);缺省是 <see cref="PublicUrl"/> 的来源,没有就取请求自己的来源。</summary>
|
||||
public string? WebAuthnOrigins { get; set; }
|
||||
|
||||
/// <summary>提权窗口的长度(passkey 触碰一次之后):加节点类的分钟数。</summary>
|
||||
public int ElevationEnrollMinutes { get; set; } = 15;
|
||||
|
||||
/// <summary>吊销和删除类的分钟数。</summary>
|
||||
public int ElevationRevokeMinutes { get; set; } = 5;
|
||||
|
||||
/// <summary>改凭证类(用一次就没有)的秒数。</summary>
|
||||
public int ElevationCredentialSeconds { get; set; } = 60;
|
||||
|
||||
/// <summary>会话 Cookie 带 Secure 标记(只提供 HTTPS)。本机用 HTTP 调试时才关闭。</summary>
|
||||
public bool SecureCookies { get; set; } = true;
|
||||
|
||||
|
||||
Reference in new issue
Block a user