Harden backend auth, validation and error handling

- Rate limit login (5 attempts/min per IP) with a JSON 429 response
- Constant-time password comparison; refuse login if no password is configured
- Explicit SameSite=Strict auth cookie; log failed logins with client IP
- Stop logging door codes (update log lines and the SMS body)
- Replace per-action try/catch -> 400 with a global exception handler (JSON 500)
- Return proper statuses: 404 for missing person, 502 for failed lock writes
- Validate codes as ASCII digits only (int.TryParse accepted +/-/whitespace)
- Validate person name and E.164 phone number; reject sending an unset code
- Rename TwiloOptions -> TwilioOptions and fix message typos
- Expose Program for integration tests
This commit is contained in:
LiamPietralla committed 2026-11-16 12:23:31 +11:00
1 parent 768bcc90e4
commit d0425c8cb2
38 files changed
+189 -487

No files matched your search

@@ -3,8 +3,11 @@ using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using YaleAccess.Models;
namespace YaleAccess.Controllers
@@ -15,54 +18,60 @@ namespace YaleAccess.Controllers
[Authorize]
public class AuthenticationController(IOptions<Models.Options.AuthenticationOptions> authenticationOptions, ILogger<AuthenticationController> logger) : ControllerBase
{
public const string LoginRateLimitPolicy = "login";
[HttpPost("login")]
[AllowAnonymous]
[EnableRateLimiting(LoginRateLimitPolicy)]
public async Task<IActionResult> Login([FromBody] string password)
{
try
// Refuse to authenticate at all if no password has been configured
string expectedPassword = authenticationOptions.Value.Password;
if (string.IsNullOrEmpty(expectedPassword))
{
// Check if the password is correct
if (password != authenticationOptions.Value.Password)
{
return Unauthorized(new ApiResponse("Incorrect password."));
}
// Log the user in
List<Claim> claims = new()
{
new Claim(ClaimTypes.Name, "YaleAccess")
};
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal claimsPrincipal = new(claimsIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
// Return the response
return Ok(new ApiResponse(true));
logger.LogError("No authentication password has been configured, refusing all logins.");
return StatusCode(StatusCodes.Status500InternalServerError, new ApiResponse("Authentication is not configured."));
}
catch(Exception ex)
// Check if the password is correct
if (!PasswordMatches(password, expectedPassword))
{
logger.LogError(ex, "An error occurred logging in.");
return BadRequest(new ApiResponse("An error occurred logging in."));
logger.LogWarning("Failed login attempt from {RemoteIp}.", HttpContext.Connection.RemoteIpAddress);
return Unauthorized(new ApiResponse("Incorrect password."));
}
// Log the user in
List<Claim> claims = new()
{
new Claim(ClaimTypes.Name, "YaleAccess")
};
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal claimsPrincipal = new(claimsIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
// Return the response
return Ok(new ApiResponse(true));
}
[HttpPost("logout")]
[AllowAnonymous]
public async Task<IActionResult> Logout()
{
try
{
// Sign the user out
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
// Sign the user out
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok(new ApiResponse(true));
}
catch (Exception ex)
{
logger.LogError(ex, "An error occured logging out.");
return BadRequest(new ApiResponse("An error occured logging out."));
}
return Ok(new ApiResponse(true));
}
/// <summary>
/// Compares the passwords in constant time (by comparing hashes, so differing lengths don't leak either).
/// </summary>
private static bool PasswordMatches(string? provided, string expected)
{
byte[] providedHash = SHA256.HashData(Encoding.UTF8.GetBytes(provided ?? string.Empty));
byte[] expectedHash = SHA256.HashData(Encoding.UTF8.GetBytes(expected));
return CryptographicOperations.FixedTimeEquals(providedHash, expectedHash);
}
}
}
}
@@ -2,6 +2,7 @@
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.RegularExpressions;
using YaleAccess.Data;
using YaleAccess.Models;
@@ -11,66 +12,62 @@ namespace YaleAccess.Controllers
[Route("api/[controller]")]
[EnableCors]
[Authorize]
public class PeopleController(ILogger<PeopleController> logger, YaleContext context) : ControllerBase
public partial class PeopleController(YaleContext context) : ControllerBase
{
// Twilio requires numbers in E.164 format, e.g. +61400000000
[GeneratedRegex(@"^\+[1-9]\d{6,14}$")]
private static partial Regex PhoneNumberRegex();
[HttpGet]
public async Task<IActionResult> GetPeople()
{
try
{
// Return all people
List<Person> people = await context.People.ToListAsync();
return Ok(new ApiResponse(people));
}
catch (Exception ex)
{
logger.LogError(ex, "An error occured retriving the people.");
return BadRequest(new ApiResponse("An error occured retriving the people."));
}
// Return all people
List<Person> people = await context.People.ToListAsync();
return Ok(new ApiResponse(people));
}
[HttpPost]
public async Task<IActionResult> CreatePerson([FromBody] Person person)
{
try
{
// Create a new person
Person newPerson = new() { Name = person.Name, PhoneNumber = person.PhoneNumber };
// Validate the person
string name = person.Name?.Trim() ?? string.Empty;
string phoneNumber = person.PhoneNumber?.Trim() ?? string.Empty;
// Add the person
await context.AddAsync(newPerson);
await context.SaveChangesAsync();
// Return the newly created person
return Ok(new ApiResponse(newPerson));
}
catch (Exception ex)
if (name.Length == 0 || name.Length > 100)
{
logger.LogError(ex, "An error occured creating the person.");
return BadRequest(new ApiResponse("An error occured creating the person."));
return BadRequest(new ApiResponse("The name is required and must be 100 characters or fewer."));
}
if (!PhoneNumberRegex().IsMatch(phoneNumber))
{
return BadRequest(new ApiResponse("The phone number must be in international format, e.g. +61400000000."));
}
// Create a new person and add them
Person newPerson = new() { Name = name, PhoneNumber = phoneNumber };
await context.AddAsync(newPerson);
await context.SaveChangesAsync();
// Return the newly created person
return Ok(new ApiResponse(newPerson));
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeletePerson([FromRoute] int id)
{
try
// Ensure the person exists
Person? person = await context.People.FindAsync(id);
if (person is null)
{
// Ensure the person exists
Person person = await context.People.FindAsync(id) ?? throw new Exception("Person not found.");
// Remove the person
context.Remove(person);
await context.SaveChangesAsync();
// Return the newly removed person
return Ok(new ApiResponse(person));
}
catch (Exception ex)
{
logger.LogError(ex, "An error occured deletiong the person.");
return BadRequest(new ApiResponse("An error occured deletiong the person."));
return NotFound(new ApiResponse("Person not found."));
}
// Remove the person
context.Remove(person);
await context.SaveChangesAsync();
// Return the removed person
return Ok(new ApiResponse(person));
}
}
}
+54 -86
View File
@@ -23,119 +23,87 @@ namespace YaleAccess.Controllers
[HttpGet("codes")]
public async Task<IActionResult> GetUserCodes()
{
try
// Get the home code first
YaleUserCode homeCode = await yaleAccessor.GetCodeInformationAsync(codeOptions.Value.Home);
homeCode.IsHome = true;
// Get the guest codes
List<YaleUserCode> guestCodes = new();
foreach (int code in Enumerable.Range(codeOptions.Value.GuestCodeRangeStart, codeOptions.Value.GuestCodeRangeCount))
{
// Get the home code first
YaleUserCode homeCode = await yaleAccessor.GetCodeInformationAsync(codeOptions.Value.Home);
homeCode.IsHome = true;
// Get the guest codes
List<YaleUserCode> guestCodes = new();
foreach (int code in Enumerable.Range(codeOptions.Value.GuestCodeRangeStart, codeOptions.Value.GuestCodeRangeCount))
{
guestCodes.Add(await yaleAccessor.GetCodeInformationAsync(code));
}
// Add the home code to the list
guestCodes.Add(homeCode);
// Return the codes
return Ok(new ApiResponse(guestCodes));
}
catch(Exception ex)
{
logger.LogError(ex, "An error occurred retriving the codes.");
return BadRequest(new ApiResponse("An error occurred retriving the codes."));
guestCodes.Add(await yaleAccessor.GetCodeInformationAsync(code));
}
// Add the home code to the list
guestCodes.Add(homeCode);
// Return the codes
return Ok(new ApiResponse(guestCodes));
}
[HttpPost("code/{id}")]
public async Task<IActionResult> SetUserCode([FromRoute] int id, [FromBody] string newCode)
{
try
// First validate the user code
string validCode = YaleAccessor.ValidateCode(newCode);
if (validCode != string.Empty)
{
// First validate the user code
string validCode = YaleAccessor.ValidateCode(newCode);
if (validCode != string.Empty)
{
return BadRequest(new ApiResponse(validCode));
}
// Set the new code
bool result = await yaleAccessor.SetUserCode(id, newCode);
// Return the result
if (result)
{
logger.LogInformation("Updated code for user {id} to {code}", id, newCode);
return Ok(new ApiResponse(true));
}
else
{
logger.LogInformation("Failed to update code for user {id} to {code}", id, newCode);
return BadRequest(new ApiResponse("An error occurred setting the code."));
}
return BadRequest(new ApiResponse(validCode));
}
catch (Exception ex)
// Set the new code (the code itself is never logged)
bool result = await yaleAccessor.SetUserCode(id, newCode);
if (!result)
{
logger.LogError(ex, "An error occurred setting the code.");
return BadRequest(new ApiResponse("An error occurred setting the code."));
logger.LogWarning("Failed to update code for user {Id}", id);
return StatusCode(StatusCodes.Status502BadGateway, new ApiResponse("An error occurred setting the code."));
}
logger.LogInformation("Updated code for user {Id}", id);
return Ok(new ApiResponse(true));
}
[HttpPost("code/{id}/status")]
public async Task<IActionResult> SetUserCodeStatusAsAvailable([FromRoute] int id)
{
try
// First validate the user code
string validCode = YaleAccessor.ValidateClearCode(id, codeOptions.Value.Home);
if (validCode != string.Empty)
{
// First validate the user code
string validCode = YaleAccessor.ValidateClearCode(id, codeOptions.Value.Home);
if (validCode != string.Empty)
{
return BadRequest(new ApiResponse(validCode));
}
// Set the available status
bool result = await yaleAccessor.SetCodeAsAvailable(id);
// Return the result
if (result)
{
logger.LogInformation("Updated code status for user {id} to available", id);
return Ok(new ApiResponse(true));
}
else
{
logger.LogInformation("Failed to update code status for user {id} to available", id);
return BadRequest(new ApiResponse("An error occurred setting the code status."));
}
return BadRequest(new ApiResponse(validCode));
}
catch (Exception ex)
// Set the available status
bool result = await yaleAccessor.SetCodeAsAvailable(id);
if (!result)
{
logger.LogError(ex, "An error occurred setting the code status.");
return BadRequest(new ApiResponse("An error occurred setting the code status."));
logger.LogWarning("Failed to update code status for user {Id} to available", id);
return StatusCode(StatusCodes.Status502BadGateway, new ApiResponse("An error occurred setting the code status."));
}
logger.LogInformation("Updated code status for user {Id} to available", id);
return Ok(new ApiResponse(true));
}
[HttpPost("code/{id}/send")]
public async Task<IActionResult> SendUserCode([FromRoute] int id, [FromBody] string phoneNumber)
{
try
{
// Get the user code
YaleUserCode userCode = await yaleAccessor.GetCodeInformationAsync(id);
// Get the user code
YaleUserCode userCode = await yaleAccessor.GetCodeInformationAsync(id);
// Send the code via SMS to the phone number
await smsService.SendCodeViaSMSAsync(userCode.Code, phoneNumber);
// Return success
return Ok(new ApiResponse(true));
}
catch (Exception ex)
// There is nothing to send if the code isn't set
if (string.IsNullOrEmpty(userCode.Code))
{
logger.LogError(ex, "An error occurred sending the code.");
return BadRequest(new ApiResponse("An error occurred sending the code."));
return BadRequest(new ApiResponse("This code is not set, so it cannot be sent."));
}
// Send the code via SMS to the phone number
await smsService.SendCodeViaSMSAsync(userCode.Code, phoneNumber);
// Return success
return Ok(new ApiResponse(true));
}
}
}
}