Public Access
The last backend piece of M1. A client can now log in, discover it must enroll, publish its identity key, and get a usable personal vault. Enrollment is one indivisible act. One transaction writes the key, its wraps, the device, the key log entry, the vault and the vault key grant, because none of them is useful alone: a key with no vault leaves a user unable to store anything, and a vault with no grant is a container nobody can ever open -- including its owner, since only the client can wrap the key and it has already moved on. Two independent checks run, and neither substitutes for the other. The Ed25519 self-signature proves possession of the private key. The identity-provider binding proves whose key it is: the client hashed its statement, used the hash as an OIDC nonce, and the resulting ID token is the provider's signature over exactly those public keys. This server cannot mint that signature, so it cannot invent a key for a user who never enrolled -- which is the attack that would otherwise let an operator read every vault by publishing its own key as yours. The binding token is stored verbatim, not just summarised. Clients must repeat the check against the provider's JWKS fetched directly, and storing only our conclusion would ask them to trust the server about the one question the design exists to avoid trusting it about. Key log appends take a deployment-wide advisory lock. The falsification matters more than the passing test: with the lock removed, Enroll_ConcurrentEnrollmentsByDifferentUsers_LeaveAnUnbrokenChain fails with entry 11 linked to the wrong predecessor. Different users trip no unique index, so without serialising they all read the same head and the chain forks -- indistinguishable from the key substitution the log exists to make detectable, and permanent, because the log is append-only. Enrollment is idempotent. Vault ids and keys are client-chosen, so a client whose response was lost re-sends the identical body and gets the identical result. Without that, a lost response leaves a user enrolled against a vault they never learned the id of. Contract change, breaking the v0.1 freeze deliberately. EnrollmentRequest had DevicePublicKey but no wrap to go with it, which is unsatisfiable: only the holder of the secret bundle can seal it, so the server could never fill the gap. Added DeviceWrappedPrivateKey, and PersonalVault so enrollment can be atomic rather than leaving an unopenable vault behind two endpoints that do not exist yet. No client exists and no package is published, which is exactly when PublicAPI.Unshipped.txt expects this. Sync now requires the Enrolled policy, which until now was a stub whose name promised a check it never made. The sync denial tests use enrolled intruders instead of unenrolled ones -- an unenrolled caller is stopped before the vault check runs, which would have left those tests passing without exercising the thing they exist to prove. Also fixed: omitting kdfParameters from the JSON body was a 500. A record's non-nullable parameters are a compile-time promise, not a runtime one. 268 tests pass, zero warnings on a clean rebuild, format clean.
105 lines
4.0 KiB
C#
105 lines
4.0 KiB
C#
using DodoSSH.Contracts;
|
|
using DodoSSH.Infrastructure;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Authorization.Policy;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace DodoSSH.Api.Authorization;
|
|
|
|
/// <summary>
|
|
/// Requires that the caller has published an identity key.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Not a confidentiality boundary — vault access is decided by ownership and grants, and an
|
|
/// unenrolled user holds neither. What this prevents is a client with no key material writing
|
|
/// ciphertext nobody can ever decrypt, and reading vault contents it has no way to open. Both
|
|
/// present to a user as data corruption, so the server refuses early and says why.
|
|
/// </remarks>
|
|
internal sealed class EnrolledRequirement : IAuthorizationRequirement;
|
|
|
|
/// <summary>Checks enrollment state against the database.</summary>
|
|
/// <remarks>
|
|
/// Scoped, not singleton, because it uses the request's <see cref="DodoDbContext"/>. Registering it
|
|
/// with the default singleton lifetime would capture one context for the process.
|
|
/// </remarks>
|
|
internal sealed class EnrolledHandler(
|
|
ICurrentUserContext currentUser,
|
|
DodoDbContext database,
|
|
IHttpContextAccessor accessor)
|
|
: AuthorizationHandler<EnrolledRequirement>
|
|
{
|
|
/// <inheritdoc />
|
|
protected override async Task HandleRequirementAsync(
|
|
AuthorizationHandlerContext context,
|
|
EnrolledRequirement requirement)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(context);
|
|
|
|
// Anonymous callers are already refused by the policy's authentication requirement, which
|
|
// produces a 401. Leaving this one unmet as well would turn that into a 403.
|
|
if (context.User.Identity?.IsAuthenticated != true)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var cancellationToken = accessor.HttpContext?.RequestAborted ?? CancellationToken.None;
|
|
|
|
var user = await currentUser.GetOrProvisionAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
var enrolled = await database.UserKeys
|
|
.AnyAsync(k => k.UserId == user.Id && k.IsCurrent, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
|
|
if (enrolled)
|
|
{
|
|
context.Succeed(requirement);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Turns an unmet <see cref="EnrolledRequirement"/> into a ProblemDetails response carrying
|
|
/// <see cref="ProblemCodes.EnrollmentRequired"/>.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// A bare 403 has an empty body, so a client cannot tell "you have not enrolled" — which it can
|
|
/// fix on its own — from "you may not touch this vault", which it cannot. Every other failure falls
|
|
/// through to the framework's default handling unchanged.
|
|
/// </remarks>
|
|
internal sealed class DodoAuthorizationResultHandler : IAuthorizationMiddlewareResultHandler
|
|
{
|
|
private readonly AuthorizationMiddlewareResultHandler defaultHandler = new();
|
|
|
|
/// <inheritdoc />
|
|
public async Task HandleAsync(
|
|
RequestDelegate next,
|
|
HttpContext context,
|
|
AuthorizationPolicy policy,
|
|
PolicyAuthorizationResult authorizeResult)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(context);
|
|
ArgumentNullException.ThrowIfNull(authorizeResult);
|
|
|
|
var enrollmentMissing = authorizeResult.Forbidden
|
|
&& authorizeResult.AuthorizationFailure is { } failure
|
|
&& failure.FailedRequirements.OfType<EnrolledRequirement>().Any();
|
|
|
|
if (!enrollmentMissing)
|
|
{
|
|
await defaultHandler.HandleAsync(next, context, policy, authorizeResult).ConfigureAwait(false);
|
|
return;
|
|
}
|
|
|
|
await TypedResults.Problem(
|
|
detail: "Publish an identity key at POST /api/v1/me/enrollment before using vaults.",
|
|
statusCode: StatusCodes.Status403Forbidden,
|
|
type: ProblemCodes.TypeBaseUri + ProblemCodes.EnrollmentRequired,
|
|
extensions: new Dictionary<string, object?>(StringComparer.Ordinal)
|
|
{
|
|
["code"] = ProblemCodes.EnrollmentRequired,
|
|
})
|
|
.ExecuteAsync(context)
|
|
.ConfigureAwait(false);
|
|
}
|
|
}
|