fix: lower vulnerabilities + harden docker setup

also includes a github workflow
This commit is contained in:
2026-06-17 22:18:55 -04:00
parent 4f5ca9a069
commit d16f1f872f
16 changed files with 164 additions and 137 deletions
+35
View File
@@ -0,0 +1,35 @@
name: CI
on:
pull_request:
push:
branches:
- main
jobs:
backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: 10.0.x
- run: dotnet restore SharpbinV3.Server/SharpbinV3.Server.csproj
- run: dotnet build SharpbinV3.Server/SharpbinV3.Server.csproj --configuration Release --no-restore
frontend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: SharpbinV3.Client
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: SharpbinV3.Client/package-lock.json
- run: npm ci
- run: npm run check
- run: npm run lint
- run: npm run build
+9 -3
View File
@@ -10,7 +10,13 @@ RUN npm run build
FROM node:20-alpine as runner
WORKDIR /app
COPY --from=build /app .
RUN apk add --no-cache wget
ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=5173
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --ignore-scripts && apk add --no-cache wget
COPY --from=build --chown=node:node /app/build ./build
RUN chown -R node:node /app
EXPOSE 5173
CMD ["npm", "run", "preview", "--", "--host", "0.0.0.0", "--port", "5173"]
USER node
CMD ["node", "build"]
@@ -1,13 +1,15 @@
import type { LayoutServerLoad } from './$types';
import { error } from '@sveltejs/kit';
export const load: LayoutServerLoad = async ({ fetch, url }) => {
try {
const res = await fetch('/api/auth/info');
const pasteOptionsRes = await fetch('/api/paste/info');
if (!res.ok || !pasteOptionsRes.ok) {
throw error(503, 'Failed to load site configuration.');
}
const options = await res.json();
const pasteOptions = await pasteOptionsRes.json();
return { options, pasteOptions, url: url.href };
} catch {
return { options: null, pasteOptions: null, url: url.href };
}
};
@@ -0,0 +1,12 @@
import { apiUrl } from '$lib/server/api';
import { json } from '@sveltejs/kit';
export const GET = async () => {
const res = await fetch(`${apiUrl}/health`);
if (!res.ok) {
return json({ status: 'unhealthy', backend: res.status }, { status: 503 });
}
return json({ status: 'ok' });
};
@@ -15,10 +15,14 @@ export const GET: RequestHandler = async ({ params, request }) => {
statusText: 'Not Found'
});
}
const content = await res.text();
return new Response(content, {
headers: {
'Content-Type': 'text/plain; charset=utf-8'
}
const responseHeaders = new Headers(res.headers);
responseHeaders.delete('content-encoding');
responseHeaders.delete('content-length');
responseHeaders.delete('transfer-encoding');
return new Response(await res.arrayBuffer(), {
status: res.status,
statusText: res.statusText,
headers: responseHeaders
});
};
@@ -4,7 +4,6 @@ import { extractError } from '$lib/utils/misc';
import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ fetch, request }) => {
try {
const headers = new Headers(request.headers);
const res = await fetch('/api/paste/recent', { headers });
if (!res.ok) {
@@ -13,8 +12,4 @@ export const load: PageServerLoad = async ({ fetch, request }) => {
}
const recentPastes: Paste[] = await res.json();
return { recentPastes };
} catch (error) {
console.error(error);
return { recentPastes: [] };
}
};
@@ -179,6 +179,10 @@ namespace SharpbinV3.Server.Controllers
string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (content == null || id == null)
return StatusCode(400, new { success = false, message = "Invalid request." });
if (Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
return BadRequest(
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
);
var paste = await _pasteService.Get(id);
if (paste == null)
@@ -294,7 +298,7 @@ namespace SharpbinV3.Server.Controllers
)
return Unauthorized(new { success = false, message = "Invalid API key." });
if (paste.AuthorUUID == HttpContext.GetJwtUser()?.UUID)
if (paste.AuthorUUID.HasValue && paste.AuthorUUID == HttpContext.GetJwtUser()?.UUID)
return Ok(new { success = true, message = "View not recorded for author's own paste." });
if (paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && paste.Visibility != 0)
return Ok(new { success = true, message = "View not recorded for expired paste." });
@@ -227,10 +227,12 @@ namespace SharpbinV3.Server.Controllers
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
{
var isRequestedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
var requester = HttpContext.GetJwtUser();
var requesterIsStaff = requester != null && (requester.Roles.HasFlag(Role.Admin) || requester.Roles.HasFlag(Role.Moderator));
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
if (!isRequestedUser)
{
if (user.Visibility == Visibility.Private && (!user.Roles.HasFlag(Role.Admin) || !user.Roles.HasFlag(Role.Moderator)))
if (user.Visibility == Visibility.Private && !requesterIsStaff)
return NotFound();
else if (user.Visibility != Visibility.Unlisted)
pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public);
+2 -1
View File
@@ -8,8 +8,9 @@ namespace SharpbinV3.Server.DTOs.User
public string? Username { get; set; }
public string? Email { get; set; }
[Required]
[StringLength(128, MinimumLength = 6)]
public string? Password { get; set; }
public required string Password { get; set; }
public string? Token { get; set; }
public string? TotpCode { get; set; }
}
+1 -1
View File
@@ -9,7 +9,7 @@ namespace SharpbinV3.Server.DTOs
{
public string? DisplayName { get; set; }
public string? Email { get; set; }
public Visibility? Visibility { get; set; } = Data.Enums.Visibility.Public;
public Visibility? Visibility { get; set; }
public Role? Roles { get; set; }
public bool? IsBanned { get; set; }
public string? TotpCode { get; set; }
+2
View File
@@ -9,6 +9,8 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app/out .
RUN apt-get update && apt-get install -y wget && rm -rf /var/lib/apt/lists/*
RUN useradd --create-home --uid 10001 appuser && mkdir -p /app/data && chown -R appuser:appuser /app
ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080
USER appuser
ENTRYPOINT ["dotnet", "SharpbinV3.Server.dll"]
+12 -5
View File
@@ -146,11 +146,18 @@ namespace SharpbinV3.Server.Services
var tokenHash = Utilities.ComputeSha256(refreshToken);
await using var transaction = await _db.Database.BeginTransactionAsync();
var now = DateTimeOffset.UtcNow;
var revokedCount = await _db
.RefreshTokens.Where(rt =>
rt.TokenHash == tokenHash && !rt.Used && !rt.Revoked && rt.ExpiresAt >= now && rt.JwtId == jti && rt.UserUUID == userGuid
)
.ExecuteUpdateAsync(setters => setters.SetProperty(rt => rt.Used, true).SetProperty(rt => rt.Revoked, true));
var revokedCount = await _db.Database.ExecuteSqlInterpolatedAsync(
$"""
UPDATE RefreshTokens
SET Used = 1, Revoked = 1
WHERE TokenHash = {tokenHash}
AND Used = 0
AND Revoked = 0
AND ExpiresAt >= {now}
AND JwtId = {jti}
AND UserUUID = {userGuid}
"""
);
if (revokedCount != 1)
return new CreateJWT { Success = false, Errors = ["Invalid or expired refresh token."] };
+10 -6
View File
@@ -22,15 +22,17 @@ namespace SharpbinV3.Server.Services
data = _cs.Compress(content);
double compressionRatio = (double)data.Length / originalSize;
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(content);
var comment = new Comment
{
PastePID = paste.PID,
ParentCommentID = parentCommentId,
Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content),
StoredSize = data.Length,
Content = storedContent,
StoredSize = storedContent.Length,
OriginalSize = originalSize,
IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold,
IsCompressed = isCompressed,
UserUUID = author.UUID,
CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
};
@@ -51,12 +53,14 @@ namespace SharpbinV3.Server.Services
data = _cs.Compress(newContent);
double compressionRatio = (double)data.Length / originalSize;
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(newContent);
comment.Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(newContent);
comment.StoredSize = data.Length;
comment.Content = storedContent;
comment.StoredSize = storedContent.Length;
comment.OriginalSize = originalSize;
comment.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
comment.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
comment.IsCompressed = isCompressed;
_db.Comments.Update(comment);
var result = await _db.SaveChangesAsync();
+17 -68
View File
@@ -1,6 +1,5 @@
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
@@ -10,14 +9,11 @@ using SharpbinV3.Server.Settings;
namespace SharpbinV3.Server.Services
{
public sealed class PasteService(AppDbContext db, ICompressionService cs, IMemoryCache cache, IOptions<PasteSettings> options)
public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions<PasteSettings> options)
{
private readonly AppDbContext _db = db;
private readonly ICompressionService _cs = cs;
private readonly IMemoryCache _cache = cache;
private readonly PasteSettings _pasteSettings = options.Value;
private readonly Lock _invalidationLock = new();
private readonly HashSet<string> _pasteListCacheKeys = [];
public async Task<Paste> Create(
User? author,
@@ -35,6 +31,8 @@ namespace SharpbinV3.Server.Services
data = _cs.Compress(content);
double compressionRatio = (double)data.Length / originalSize;
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(content);
var paste = new Paste
{
@@ -43,10 +41,10 @@ namespace SharpbinV3.Server.Services
Title = title,
AuthorUUID = author?.UUID,
User = author,
Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content),
StoredSize = data.Length,
Content = storedContent,
StoredSize = storedContent.Length,
OriginalSize = originalSize,
IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold,
IsCompressed = isCompressed,
Syntax = syntax,
Visibility = visibility,
ExpiresAt = expiresAt,
@@ -59,8 +57,6 @@ namespace SharpbinV3.Server.Services
}
await _db.SaveChangesAsync();
InvalidatePasteListCache();
return paste;
}
@@ -69,8 +65,6 @@ namespace SharpbinV3.Server.Services
_db.Pastes.Remove(paste);
var result = await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return result > 0;
}
@@ -79,8 +73,6 @@ namespace SharpbinV3.Server.Services
_db.Pastes.Update(paste);
await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return paste;
}
@@ -102,17 +94,17 @@ namespace SharpbinV3.Server.Services
data = _cs.Compress(text);
double compressionRatio = (double)data.Length / originalSize;
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(text);
paste.Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(text);
paste.StoredSize = data.Length;
paste.Content = storedContent;
paste.StoredSize = storedContent.Length;
paste.OriginalSize = originalSize;
paste.EditedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
paste.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
paste.IsCompressed = isCompressed;
_db.Pastes.Update(paste);
var result = await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return result > 0;
}
@@ -151,7 +143,6 @@ namespace SharpbinV3.Server.Services
return (null, true);
}
InvalidatePasteCache(paste.ID);
return (paste, false);
}
@@ -172,7 +163,6 @@ namespace SharpbinV3.Server.Services
try
{
await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return interaction;
}
catch (DbUpdateException)
@@ -192,57 +182,32 @@ namespace SharpbinV3.Server.Services
_db.PasteInteractions.Remove(interaction);
await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return true;
}
public async Task<Paste?> Get(string id)
{
string key = $"v1:paste:{id}";
var paste = await _cache.GetOrCreateAsync(
key,
async entry =>
var paste = await _db.Pastes.AsNoTracking().Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
if (paste != null)
{
entry.SetSlidingExpiration(TimeSpan.FromMinutes(10));
var _paste = await _db.Pastes.AsNoTracking().Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
if (_paste != null)
{
_paste.PositiveInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == _paste.PID && pi.Type == Interaction.Positive)
paste.PositiveInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == paste.PID && pi.Type == Interaction.Positive)
.CountAsync();
_paste.NegativeInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == _paste.PID && pi.Type == Interaction.Negative)
paste.NegativeInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == paste.PID && pi.Type == Interaction.Negative)
.CountAsync();
}
return _paste;
}
);
return paste ?? null;
}
public async Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false)
{
string key = $"v1:list:pastes:public={publicOnly}:offset={offset}:count={count}";
var pastes = await _cache.GetOrCreateAsync(
key,
async entry =>
{
entry.SetSlidingExpiration(TimeSpan.FromMinutes(5));
lock (_invalidationLock)
_pasteListCacheKeys.Add(key);
var query = _db.Pastes.AsQueryable();
if (publicOnly)
query = query.Where(p => p.Visibility == 0);
return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).Include(p => p.User).ToListAsync();
}
);
return pastes ?? [];
}
public async Task<PasteInteraction?> GetUserInteraction(Paste paste, Guid userUUID)
{
@@ -275,21 +240,5 @@ namespace SharpbinV3.Server.Services
return expiresAt > currentTime - 1000;
}
private void InvalidatePasteCache(string pasteId)
{
string key = $"v1:paste:{pasteId}";
_cache.Remove(key);
}
private void InvalidatePasteListCache()
{
lock (_invalidationLock)
{
foreach (var listKey in _pasteListCacheKeys)
_cache.Remove(listKey);
_pasteListCacheKeys.Clear();
}
}
}
}
+21 -17
View File
@@ -85,27 +85,31 @@ namespace SharpbinV3.Server.Services
public async Task<List<ReportResponseDto>> GetReports(ReportQuery query)
{
return await BuildReportQuery(query)
var pagedReports = BuildReportQuery(query)
.OrderByDescending(r => r.CreatedAt)
.Skip((query.Page - 1) * query.PageSize)
.Take(query.PageSize)
.Take(query.PageSize);
return await pagedReports
.GroupJoin(_db.Users, r => r.ReporterUUID, reporter => reporter.UUID, (report, reporters) => new { report, reporters })
.SelectMany(r => r.reporters.DefaultIfEmpty(), (r, reporter) => new { r.report, reporter })
.Select(r => new ReportResponseDto
{
ReportID = r.ReportID,
Type = r.Type,
Status = r.Status,
Description = r.Description,
CreatedAt = r.CreatedAt,
UpdatedAt = r.UpdatedAt,
ReporterUUID = r.ReporterUUID,
ReporterUsername = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.Username).FirstOrDefault(),
ReporterDisplayName = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.DisplayName).FirstOrDefault(),
TargetType = r.TargetType,
PasteId = r.Paste != null ? r.Paste.ID : null,
PasteTitle = r.Paste != null ? r.Paste.Title : null,
UserUUID = r.UserUUID,
TargetUsername = r.User != null ? r.User.Username : null,
TargetDisplayName = r.User != null ? r.User.DisplayName : null,
ReportID = r.report.ReportID,
Type = r.report.Type,
Status = r.report.Status,
Description = r.report.Description,
CreatedAt = r.report.CreatedAt,
UpdatedAt = r.report.UpdatedAt,
ReporterUUID = r.report.ReporterUUID,
ReporterUsername = r.reporter != null ? r.reporter.Username : null,
ReporterDisplayName = r.reporter != null ? r.reporter.DisplayName : null,
TargetType = r.report.TargetType,
PasteId = r.report.Paste != null ? r.report.Paste.ID : null,
PasteTitle = r.report.Paste != null ? r.report.Paste.Title : null,
UserUUID = r.report.UserUUID,
TargetUsername = r.report.User != null ? r.report.User.Username : null,
TargetDisplayName = r.report.User != null ? r.report.User.DisplayName : null,
})
.ToListAsync();
}
+1 -1
View File
@@ -41,7 +41,7 @@ services:
networks:
- sharpbin-net
healthcheck:
test: 'wget --no-verbose --spider http://localhost:5173/health || exit 1'
test: 'wget --no-verbose --spider http://localhost:5173/health/ready || exit 1'
interval: 30s
timeout: 30s
retries: 5