diff --git a/SharpbinV3.Client/src/routes/+page.svelte b/SharpbinV3.Client/src/routes/+page.svelte index 6c6a3a8..735d0e2 100644 --- a/SharpbinV3.Client/src/routes/+page.svelte +++ b/SharpbinV3.Client/src/routes/+page.svelte @@ -132,9 +132,9 @@ data.auth?.cf_turnstile_site_key && window.turnstile ) { - const token = window.turnstile.getResponse(); - if (token) { - params.append('token', token); + const verificationToken = window.turnstile.getResponse(); + if (verificationToken) { + params.append('verificationToken', verificationToken); } } diff --git a/SharpbinV3.Server/Authorization/NotBannedHandler.cs b/SharpbinV3.Server/Authorization/NotBannedHandler.cs index 2636626..fe4d9a2 100644 --- a/SharpbinV3.Server/Authorization/NotBannedHandler.cs +++ b/SharpbinV3.Server/Authorization/NotBannedHandler.cs @@ -1,5 +1,6 @@ using System.Security.Claims; using Microsoft.AspNetCore.Authorization; +using SharpbinV3.Server.Extensions; namespace SharpbinV3.Server.Authorization { @@ -9,13 +10,26 @@ namespace SharpbinV3.Server.Authorization protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement) { + var httpContext = context.Resource as HttpContext; var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false; + if (!isAuthenticated && httpContext != null) + { + var apiKey = httpContext.GetApiKeyFromContext(); + if (apiKey != null) + { + isAuthenticated = true; + } + } + if (_requireAuth && !isAuthenticated) return Task.CompletedTask; var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403"); + if (httpContext?.GetApiKeyFromContext()?.User?.Roles?.Contains(403) == true) + isBanned = true; + if (!isBanned) context.Succeed(requirement); diff --git a/SharpbinV3.Server/Controllers/AuthController.cs b/SharpbinV3.Server/Controllers/AuthController.cs index 024f21f..5374297 100644 --- a/SharpbinV3.Server/Controllers/AuthController.cs +++ b/SharpbinV3.Server/Controllers/AuthController.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Options; using SharpbinV3.Server.Data; using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.DTOs; +using SharpbinV3.Server.DTOs.ApiKey; using SharpbinV3.Server.DTOs.Auth; using SharpbinV3.Server.DTOs.User; using SharpbinV3.Server.Extensions; @@ -22,6 +23,7 @@ namespace SharpbinV3.Server.Controllers public class AuthController( UserService userService, AuthService authService, + ApiKeyService apiKeyService, IOptions options, VerificationService verification, TotpVerificationProvider totp, @@ -30,6 +32,7 @@ namespace SharpbinV3.Server.Controllers { private readonly AuthService _authService = authService; private readonly UserService _userService = userService; + private readonly ApiKeyService _apiKeyService = apiKeyService; private readonly VerificationService _verification = verification; private readonly TotpVerificationProvider _totp = totp; private readonly AppDbContext _db = db; @@ -240,5 +243,88 @@ namespace SharpbinV3.Server.Controllers await _db.SaveChangesAsync(); return Ok(new { success = true, message = "TOTP disabled." }); } + + [HttpPost] + [Authorize] + [Route("apikey/create")] + [EnableRateLimiting("Strict")] + public async Task CreateApiKey([FromBody] CreateApiKeyRequest request) + { + if (string.IsNullOrWhiteSpace(request.Name)) + return BadRequest(new { success = false, message = "API key name is required." }); + if (request.Name.Length > 26) + return BadRequest(new { success = false, message = "API key name must not exceed 26 characters." }); + + var user = await _authService.GetUserFromHttpContext(HttpContext); + if (user == null) + return BadRequest(new { success = false, message = "User not found." }); + + var existingKeys = await _apiKeyService.GetUserKeysAsync(user.UUID); + if (existingKeys.Count >= 10) + return BadRequest(new { success = false, message = "API key limit reached. Please delete existing keys before creating new ones." }); + + var (apiKey, key) = await _apiKeyService.CreateAsync(user.UUID, request.Name); + + return Ok( + new + { + success = true, + message = "API key created. Save it now as you won't be able to see it again.", + apiKey = new ApiKeyResponseDto + { + UUID = apiKey.UUID, + Key = key, + Name = apiKey.Name, + CreatedAt = apiKey.CreatedAt, + }, + } + ); + } + + [HttpGet] + [Authorize] + [Route("apikey/list")] + public async Task ListApiKeys() + { + var user = await _authService.GetUserFromHttpContext(HttpContext); + if (user == null) + return BadRequest(new { success = false, message = "User not found." }); + + var apiKeys = await _apiKeyService.GetUserKeysAsync(user.UUID); + return Ok( + new + { + success = true, + apiKeys = apiKeys + .Select(k => new ApiKeyListItemDto + { + UUID = k.UUID, + Name = k.Name, + CreatedAt = k.CreatedAt, + LastUsedAt = k.LastUsedAt, + }) + .ToList(), + } + ); + } + + [HttpDelete] + [Authorize] + [Route("apikey/{uuid}")] + public async Task DeleteApiKey(string uuid) + { + if (!Guid.TryParse(uuid, out var keyUUID)) + return BadRequest(new { success = false, message = "Invalid API key UUID." }); + + var user = await _authService.GetUserFromHttpContext(HttpContext); + if (user == null) + return BadRequest(new { success = false, message = "User not found." }); + + var deleted = await _apiKeyService.DeleteAsync(user.UUID, keyUUID); + if (!deleted) + return NotFound(new { success = false, message = "API key not found." }); + + return Ok(new { success = true, message = "API key deleted." }); + } } } diff --git a/SharpbinV3.Server/Controllers/PasteController.cs b/SharpbinV3.Server/Controllers/PasteController.cs index 74f4ab0..d728fea 100644 --- a/SharpbinV3.Server/Controllers/PasteController.cs +++ b/SharpbinV3.Server/Controllers/PasteController.cs @@ -40,7 +40,7 @@ namespace SharpbinV3.Server.Controllers string syntax = "plaintext", int visibility = 0, long expiresAt = 0, - string? token = null + string? verificationToken = null ) { if (!_pasteService.ValidateExpiresAt(expiresAt)) @@ -60,11 +60,18 @@ namespace SharpbinV3.Server.Controllers new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." } ); - if ( - _pasteSettings.RequiresVerification - && !await _verificationService.VerifyAsync(new VerificationContext { Token = token, Ip = HttpContext.GetRequestIP() }) - ) - return BadRequest(new { success = false, message = "Verification failed." }); + if (_pasteSettings.RequiresVerification && !HttpContext.IsApiKeyAuthenticated()) + { + var providedApiKey = HttpContext.GetApiKey(); + if (providedApiKey != null) + return BadRequest(new { success = false, message = "Invalid API key." }); + + var verifyResult = await _verificationService.VerifyAsync( + new VerificationContext { Token = verificationToken, Ip = HttpContext.GetRequestIP() } + ); + if (!verifyResult) + return BadRequest(new { success = false, message = "Verification failed." }); + } var user = await _authService.GetUserFromHttpContext(HttpContext); Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression); diff --git a/SharpbinV3.Server/DTOs/ApiKey/ApiKeyListItemDto.cs b/SharpbinV3.Server/DTOs/ApiKey/ApiKeyListItemDto.cs new file mode 100644 index 0000000..416466f --- /dev/null +++ b/SharpbinV3.Server/DTOs/ApiKey/ApiKeyListItemDto.cs @@ -0,0 +1,10 @@ +namespace SharpbinV3.Server.DTOs.ApiKey +{ + public sealed class ApiKeyListItemDto + { + public required string Name { get; set; } + public required Guid UUID { get; set; } + public required long CreatedAt { get; set; } + public long? LastUsedAt { get; set; } + } +} diff --git a/SharpbinV3.Server/DTOs/ApiKey/ApiKeyResponseDto.cs b/SharpbinV3.Server/DTOs/ApiKey/ApiKeyResponseDto.cs new file mode 100644 index 0000000..4ed27c2 --- /dev/null +++ b/SharpbinV3.Server/DTOs/ApiKey/ApiKeyResponseDto.cs @@ -0,0 +1,10 @@ +namespace SharpbinV3.Server.DTOs.ApiKey +{ + public sealed class ApiKeyResponseDto + { + public required string Key { get; set; } + public required string Name { get; set; } + public required Guid UUID { get; set; } + public required long CreatedAt { get; set; } + } +} diff --git a/SharpbinV3.Server/DTOs/ApiKey/CreateApiKeyRequest.cs b/SharpbinV3.Server/DTOs/ApiKey/CreateApiKeyRequest.cs new file mode 100644 index 0000000..a72ea38 --- /dev/null +++ b/SharpbinV3.Server/DTOs/ApiKey/CreateApiKeyRequest.cs @@ -0,0 +1,7 @@ +namespace SharpbinV3.Server.DTOs.ApiKey +{ + public sealed class CreateApiKeyRequest + { + public required string Name { get; set; } + } +} diff --git a/SharpbinV3.Server/Data/AppDbContext.cs b/SharpbinV3.Server/Data/AppDbContext.cs index b45d438..5288106 100644 --- a/SharpbinV3.Server/Data/AppDbContext.cs +++ b/SharpbinV3.Server/Data/AppDbContext.cs @@ -11,6 +11,7 @@ namespace SharpbinV3.Server.Data public DbSet RefreshTokens => Set(); public DbSet UserTotps => Set(); public DbSet Reports => Set(); + public DbSet ApiKeys => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -56,6 +57,12 @@ namespace SharpbinV3.Server.Data .WithMany(u => u.Reports) .HasForeignKey(r => r.UserUUID) .OnDelete(DeleteBehavior.SetNull); + + modelBuilder.Entity() + .HasOne(a => a.User) + .WithMany(u => u.ApiKeys) + .HasForeignKey(a => a.UserUUID) + .OnDelete(DeleteBehavior.Cascade); } } } diff --git a/SharpbinV3.Server/Data/Entities/ApiKey.cs b/SharpbinV3.Server/Data/Entities/ApiKey.cs new file mode 100644 index 0000000..0f641ce --- /dev/null +++ b/SharpbinV3.Server/Data/Entities/ApiKey.cs @@ -0,0 +1,16 @@ +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Server.Data.Entities +{ + public sealed class ApiKey + { + [Key] + public Guid UUID { get; set; } = Guid.CreateVersion7(); + public required Guid UserUUID { get; set; } + public User? User { get; set; } + public required string KeyHash { get; set; } + public required string Name { get; set; } + public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + public long? LastUsedAt { get; set; } + } +} diff --git a/SharpbinV3.Server/Data/Entities/User.cs b/SharpbinV3.Server/Data/Entities/User.cs index 764b908..0bae13b 100644 --- a/SharpbinV3.Server/Data/Entities/User.cs +++ b/SharpbinV3.Server/Data/Entities/User.cs @@ -23,6 +23,7 @@ namespace SharpbinV3.Server.Data.Entities public List Pastes { get; set; } = []; public List RefreshTokens { get; set; } = []; public List Reports { get; set; } = []; + public List ApiKeys { get; set; } = []; public UserTotp? Totp { get; set; } } } diff --git a/SharpbinV3.Server/Extensions/HttpContextExtensions.cs b/SharpbinV3.Server/Extensions/HttpContextExtensions.cs index 80a7a03..85b634d 100644 --- a/SharpbinV3.Server/Extensions/HttpContextExtensions.cs +++ b/SharpbinV3.Server/Extensions/HttpContextExtensions.cs @@ -1,5 +1,6 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; +using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Services; namespace SharpbinV3.Server.Extensions @@ -16,6 +17,38 @@ namespace SharpbinV3.Server.Extensions "X-ProxyUser-IP", ]; + private const string ApiKeyContextKey = "ApiKey"; + + public static string? GetApiKey(this HttpContext context) + { + var apiKeyHeader = context.Request.Headers["X-API-Key"].FirstOrDefault(); + if (string.IsNullOrEmpty(apiKeyHeader)) + return null; + + if (apiKeyHeader.Length != ApiKeyService.KeyLength) + return null; + + return apiKeyHeader; + } + + public static ApiKey? GetApiKeyFromContext(this HttpContext context) + { + if (context.Items.TryGetValue(ApiKeyContextKey, out var apiKey)) + return apiKey as ApiKey; + + return null; + } + + public static void SetApiKeyContext(this HttpContext context, ApiKey apiKey) + { + context.Items[ApiKeyContextKey] = apiKey; + } + + public static bool IsApiKeyAuthenticated(this HttpContext context) + { + return context.GetApiKeyFromContext() != null; + } + public static JwtUser? GetJwtUser(this HttpContext context) { if (context.User == null || !context.User.Identity?.IsAuthenticated == true) diff --git a/SharpbinV3.Server/Middleware/ApiKeyAuthenticationMiddleware.cs b/SharpbinV3.Server/Middleware/ApiKeyAuthenticationMiddleware.cs new file mode 100644 index 0000000..9020c5c --- /dev/null +++ b/SharpbinV3.Server/Middleware/ApiKeyAuthenticationMiddleware.cs @@ -0,0 +1,26 @@ +using SharpbinV3.Server.Extensions; +using SharpbinV3.Server.Services; + +namespace SharpbinV3.Server.Middleware +{ + public sealed class ApiKeyAuthenticationMiddleware(RequestDelegate next) + { + private readonly RequestDelegate _next = next; + + public async Task InvokeAsync(HttpContext context, ApiKeyService apiKeyService) + { + var apiKeyString = context.GetApiKey(); + if (!string.IsNullOrEmpty(apiKeyString)) + { + var apiKey = await apiKeyService.GetByKeyAsync(apiKeyString); + if (apiKey != null) + { + context.SetApiKeyContext(apiKey); + await apiKeyService.UpdateLastUsedAsync(apiKey.UUID); + } + } + + await _next(context); + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260210231315_AddApiKeys.Designer.cs b/SharpbinV3.Server/Migrations/20260210231315_AddApiKeys.Designer.cs new file mode 100644 index 0000000..e4d0fb5 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260210231315_AddApiKeys.Designer.cs @@ -0,0 +1,405 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SharpbinV3.Server.Data; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260210231315_AddApiKeys")] + partial class AddApiKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.1"); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("KeyHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Property("PID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorUUID") + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EditedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("ID") + .HasColumnType("TEXT"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("Syntax") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.Property("TrueSize") + .HasColumnType("INTEGER"); + + b.Property("UUID") + .HasColumnType("TEXT"); + + b.Property("Views") + .HasColumnType("INTEGER"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("PID"); + + b.HasIndex("AuthorUUID"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("ID") + .IsUnique(); + + b.HasIndex("PID") + .IsUnique(); + + b.HasIndex("Size"); + + b.HasIndex("Syntax"); + + b.HasIndex("UUID") + .IsUnique(); + + b.HasIndex("Views"); + + b.HasIndex("Visibility"); + + b.ToTable("Pastes"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ViewedAt") + .HasColumnType("INTEGER"); + + b.Property("ViewerHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PastePID", "ViewerHash") + .IsUnique(); + + b.ToTable("PasteViews"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReplacedByToken") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserUUID"); + + b.ToTable("RefreshTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.Property("ReportID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ReporterUUID") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("TargetType") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("ReportID"); + + b.HasIndex("PastePID"); + + b.HasIndex("ReportID") + .IsUnique(); + + b.HasIndex("ReporterUUID"); + + b.HasIndex("TargetType"); + + b.HasIndex("UserUUID"); + + b.ToTable("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("LastLogin") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.PrimitiveCollection("Roles") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UID") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("UUID"); + + b.HasIndex("UID"); + + b.HasIndex("UUID") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EncryptedSecret") + .IsRequired() + .HasColumnType("BLOB"); + + b.HasKey("UserUUID"); + + b.ToTable("UserTotps"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("ApiKeys") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Pastes") + .HasForeignKey("AuthorUUID") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("PasteViews") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("RefreshTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Reports") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Reports") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithOne("Totp") + .HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Navigation("PasteViews"); + + b.Navigation("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Navigation("ApiKeys"); + + b.Navigation("Pastes"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Reports"); + + b.Navigation("Totp"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260210231315_AddApiKeys.cs b/SharpbinV3.Server/Migrations/20260210231315_AddApiKeys.cs new file mode 100644 index 0000000..cb258a8 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260210231315_AddApiKeys.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + /// + public partial class AddApiKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ApiKeys", + columns: table => new + { + UUID = table.Column(type: "TEXT", nullable: false), + UserUUID = table.Column(type: "TEXT", nullable: false), + KeyHash = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false), + LastUsedAt = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiKeys", x => x.UUID); + table.ForeignKey( + name: "FK_ApiKeys_Users_UserUUID", + column: x => x.UserUUID, + principalTable: "Users", + principalColumn: "UUID", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeys_UserUUID", + table: "ApiKeys", + column: "UserUUID"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiKeys"); + } + } +} diff --git a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs index a4730d5..eb27212 100644 --- a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs +++ b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs @@ -17,6 +17,36 @@ namespace SharpbinV3.Server.Migrations #pragma warning disable 612, 618 modelBuilder.HasAnnotation("ProductVersion", "10.0.1"); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("KeyHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("ApiKeys"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => { b.Property("PID") @@ -276,6 +306,17 @@ namespace SharpbinV3.Server.Migrations b.ToTable("UserTotps"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("ApiKeys") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => { b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") @@ -345,6 +386,8 @@ namespace SharpbinV3.Server.Migrations modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => { + b.Navigation("ApiKeys"); + b.Navigation("Pastes"); b.Navigation("RefreshTokens"); diff --git a/SharpbinV3.Server/Program.cs b/SharpbinV3.Server/Program.cs index e44f53e..9986c0a 100644 --- a/SharpbinV3.Server/Program.cs +++ b/SharpbinV3.Server/Program.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.DataProtection; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; +using Microsoft.OpenApi; using SharpbinV3.Server.Authorization; using SharpbinV3.Server.Data; using SharpbinV3.Server.Extensions; @@ -38,7 +39,21 @@ namespace SharpbinV3.Server options.AddDocumentTransformer( (document, context, cancellationToken) => { + document?.Components ??= new(); document?.Servers?.Clear(); + document?.Components?.SecuritySchemes ??= new Dictionary(); + + document + ?.Components + ?.SecuritySchemes + ?["ApiKey"] = new OpenApiSecurityScheme + { + Type = SecuritySchemeType.ApiKey, + Name = "X-API-Key", + In = ParameterLocation.Header, + Description = "Bypass authentication and captcha by providing a valid API key.", + }; + return Task.CompletedTask; } ); @@ -54,6 +69,7 @@ namespace SharpbinV3.Server builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHttpClient(); @@ -220,6 +236,8 @@ namespace SharpbinV3.Server app.UseHttpsRedirection(); app.UseCors(); + app.UseMiddleware(); + app.UseAuthentication(); app.UseAuthorization(); diff --git a/SharpbinV3.Server/Services/ApiKeyService.cs b/SharpbinV3.Server/Services/ApiKeyService.cs new file mode 100644 index 0000000..c4d4b06 --- /dev/null +++ b/SharpbinV3.Server/Services/ApiKeyService.cs @@ -0,0 +1,74 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using SharpbinV3.Server.Data; +using SharpbinV3.Server.Data.Entities; +using SharpbinV3.Server.Settings; + +namespace SharpbinV3.Server.Services +{ + public sealed class ApiKeyService(AppDbContext db, IOptions authOptions) + { + private readonly AppDbContext _db = db; + private readonly AuthSettings _authSettings = authOptions.Value; + + public const int KeyLength = 64; + + private string ComputeHash(string input) + { + if (string.IsNullOrEmpty(_authSettings.API_Key_HMAC_Secret)) + return Utilities.ComputeSha256(input); + else + return Utilities.ComputeHmacSha256(input, _authSettings.API_Key_HMAC_Secret); + } + + public async Task GetByKeyAsync(string key) + { + var keyHash = ComputeHash(key); + return await _db.ApiKeys.Include(a => a.User).FirstOrDefaultAsync(a => a.KeyHash == keyHash); + } + + public async Task<(ApiKey apiKey, string key)> CreateAsync(Guid userUUID, string name) + { + var key = Utilities.GenerateRandomString(KeyLength); + var keyHash = ComputeHash(key); + + var apiKey = new ApiKey + { + UserUUID = userUUID, + Name = name, + KeyHash = keyHash, + }; + + _db.ApiKeys.Add(apiKey); + await _db.SaveChangesAsync(); + + return (apiKey, key); + } + + public async Task DeleteAsync(Guid userUUID, Guid keyUUID) + { + var apiKey = await _db.ApiKeys.FirstOrDefaultAsync(a => a.UUID == keyUUID && a.UserUUID == userUUID); + if (apiKey == null) + return false; + + _db.ApiKeys.Remove(apiKey); + await _db.SaveChangesAsync(); + return true; + } + + public async Task> GetUserKeysAsync(Guid userUUID) + { + return await _db.ApiKeys.Where(a => a.UserUUID == userUUID).OrderByDescending(a => a.CreatedAt).ToListAsync(); + } + + public async Task UpdateLastUsedAsync(Guid keyUUID) + { + var apiKey = await _db.ApiKeys.FirstOrDefaultAsync(a => a.UUID == keyUUID); + if (apiKey == null) + return; + + apiKey.LastUsedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + await _db.SaveChangesAsync(); + } + } +} diff --git a/SharpbinV3.Server/Services/AuthService.cs b/SharpbinV3.Server/Services/AuthService.cs index 6e65531..ce8cc43 100644 --- a/SharpbinV3.Server/Services/AuthService.cs +++ b/SharpbinV3.Server/Services/AuthService.cs @@ -7,6 +7,7 @@ using Microsoft.IdentityModel.Tokens; using SharpbinV3.Server.Data; using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.DTOs.Auth; +using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Settings; using Bcrypt = BCrypt.Net.BCrypt; @@ -201,6 +202,10 @@ namespace SharpbinV3.Server.Services public async Task GetUserFromHttpContext(HttpContext context) { + var apiKey = context.GetApiKeyFromContext(); + if (apiKey != null) + return await _db.Users.FirstOrDefaultAsync(u => u.UUID == apiKey.UserUUID); + var uuidClaim = context.User.Claims.FirstOrDefault(c => c.Type == "uuid")?.Value; if (uuidClaim == null) return null; diff --git a/SharpbinV3.Server/Settings/AuthSettings.cs b/SharpbinV3.Server/Settings/AuthSettings.cs index 56f28c6..9246e74 100644 --- a/SharpbinV3.Server/Settings/AuthSettings.cs +++ b/SharpbinV3.Server/Settings/AuthSettings.cs @@ -7,5 +7,6 @@ public bool Registration_Enabled { get; set; } = true; public bool First_User_Admin { get; set; } = true; public bool Admins_Require_2FA { get; set; } = true; + public string API_Key_HMAC_Secret { get; set; } = string.Empty; } }