Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,23 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.0.8.1] - 2024-05-07
### Cleanup

- Spring cleanup of the project.

### Fixed

- Redirect after login did not work correctly.

## [0.0.8] - 2023-08-05
### Added

- Introduced an optional daily backup feature controlled by the `PICOBLOG_ENABLE_BACKUP` environment variable.
- Implemented global usings through `GlobalUsings.cs` for cleaner code (if applicable to your .NET version).
- Parallel processing of markdown files during search
- Log failed login attempts

### Changed
- Updated the README to reflect new environment variables and features.

Expand Down
2 changes: 1 addition & 1 deletion Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ await HttpContext.SignInAsync(
if (!String.IsNullOrEmpty(model.ReturnURL) && Url.IsLocalUrl(model.ReturnURL) && IsValidReturnUrl(model.ReturnURL))
return Redirect(model.ReturnURL);

return RedirectToAction("/");
return Redirect("/");
}

[Route("")]
Expand Down
131 changes: 57 additions & 74 deletions Controllers/PostController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ public async Task<IActionResult> Index(Payload payload)
{
if (Config.Password != null && !User.Identity.IsAuthenticated)
{
_logger.LogWarning("Unauthenticated request with Config.Password set.");
return NotFound();
_logger.LogWarning("Unauthenticated request with Config.Password set for image not as Cover");
return Unauthorized();
}
}

Expand All @@ -52,46 +52,34 @@ public async Task<IActionResult> Index(Payload payload)
}
}


private async Task<IActionResult> Synology(string path) {
if (Config.Synology)
{
var synologyFile = Path.GetFileName(path);
var directory = Path.GetDirectoryName(path);
var synologyPath = $"@eaDir/{synologyFile}/{Config.SynologySize()}";
synologyPath = $"{directory}/{synologyPath}";

if (System.IO.File.Exists(synologyPath)) {
path = synologyPath;
_logger.LogDebug("Synology file exists. Updated path to: {0}", path);
if (Config.Synology) {
var synologyFile = Path.GetFileName(path);
var directory = Path.GetDirectoryName(path);
var synologyPath = $"{directory}/@eaDir/{synologyFile}/{Config.SynologySize()}";

if (System.IO.File.Exists(synologyPath)) {
path = synologyPath;
_logger.LogDebug("Synology file exists. Updated path to: {0}", path);

Check failure

Code scanning / CodeQL

Log entries created from user input

This log entry depends on a [user-provided value](1).

Copilot Autofix

AI about 1 year ago

To fix the problem, we need to sanitize the user input before logging it. Since the log entries are plain text, we should remove any newline characters from the user input to prevent log forgery. We can use the String.Replace method to achieve this.

Specifically, we need to sanitize the path variable before logging it on line 63. We will replace any newline characters in the path variable with an empty string.

Suggested changeset 1
Controllers/PostController.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/Controllers/PostController.cs b/Controllers/PostController.cs
--- a/Controllers/PostController.cs
+++ b/Controllers/PostController.cs
@@ -62,3 +62,4 @@
               path = synologyPath;
-              _logger.LogDebug("Synology file exists. Updated path to: {0}", path);
+              var sanitizedPath = path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
+              _logger.LogDebug("Synology file exists. Updated path to: {0}", sanitizedPath);
               return await ReturnFileResponse(path);
EOF
@@ -62,3 +62,4 @@
path = synologyPath;
_logger.LogDebug("Synology file exists. Updated path to: {0}", path);
var sanitizedPath = path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
_logger.LogDebug("Synology file exists. Updated path to: {0}", sanitizedPath);
return await ReturnFileResponse(path);
Copilot is powered by AI and may make mistakes. Always verify output.
return await ReturnFileResponse(path);
}
}
}

if (!System.IO.File.Exists(path)){
if(path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".JPG", StringComparison.OrdinalIgnoreCase)){
path = ToggleCaseExtension(path);
if (!System.IO.File.Exists(path)){
_logger.LogWarning("File does not exist after toggling case of extension: {0}", path);
if (!System.IO.File.Exists(path)) {
_logger.LogWarning("File does not exist at path: {0}", path);

Check failure

Code scanning / CodeQL

Log entries created from user input

This log entry depends on a [user-provided value](1).

Copilot Autofix

AI about 1 year ago

To fix the problem, we need to sanitize the user input before logging it. Since the log entries are plain text, we should remove any new line characters from the user input to prevent log forging. This can be done using the String.Replace method to replace new line characters with an empty string. We will apply this sanitization to the path variable before it is logged.

Suggested changeset 1
Controllers/PostController.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/Controllers/PostController.cs b/Controllers/PostController.cs
--- a/Controllers/PostController.cs
+++ b/Controllers/PostController.cs
@@ -68,3 +68,4 @@
       if (!System.IO.File.Exists(path)) {
-          _logger.LogWarning("File does not exist at path: {0}", path);
+          var sanitizedPath = path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
+          _logger.LogWarning("File does not exist at path: {0}", sanitizedPath);
           return NotFound();
EOF
@@ -68,3 +68,4 @@
if (!System.IO.File.Exists(path)) {
_logger.LogWarning("File does not exist at path: {0}", path);
var sanitizedPath = path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
_logger.LogWarning("File does not exist at path: {0}", sanitizedPath);
return NotFound();
Copilot is powered by AI and may make mistakes. Always verify output.
return NotFound();
}
} else {
_logger.LogWarning("File does not exist after toggling case of extension: {0}", path);
return NotFound();
}
}

HttpContext.Response.Headers.Add("ETag", ComputeMD5(path));
HttpContext.Response.Headers.Add("Cache-Control", "private, max-age=12000");
await HttpContext.Response.Body.WriteAsync(await resize(path));
return new EmptyResult();
path = await ResizeIfNeeded(path);
return await ReturnFileResponse(path);
}

private string ToggleCaseExtension(string path)
{
string ext = System.IO.Path.GetExtension(path);
string oppositeCaseExt = ext.Equals(ext.ToLower()) ? ext.ToUpper() : ext.ToLower();
_logger.LogDebug("Toggled case of extension. New path: {0}\nOld path: {1}", oppositeCaseExt, path);
return System.IO.Path.ChangeExtension(path, oppositeCaseExt);

private async Task<IActionResult> ReturnFileResponse(string filePath) {
HttpContext.Response.Headers.Add("ETag", ComputeMD5(filePath));
HttpContext.Response.Headers.Add("Cache-Control", "private, max-age=12000");
await HttpContext.Response.Body.WriteAsync(System.IO.File.ReadAllBytes(filePath));
return new EmptyResult();
}

private string ComputeMD5(string s)
Expand All @@ -103,48 +91,43 @@ private string ComputeMD5(string s)
}
}

private async Task<byte[]> resize(string path) {
_logger.LogDebug("Resize method started for path: {0}", path);
try{
var fileName = $"{Config.ConfigDir}/images{path}";
if (System.IO.File.Exists(fileName)) {
using (var SourceStream = System.IO.File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var result = new byte[SourceStream.Length];
await SourceStream.ReadAsync(result, 0, (int)SourceStream.Length);
return result;
}
private async Task<string> ResizeIfNeeded(string path) {
_logger.LogDebug("Checking if resize is needed for path: {0}", path);

Check failure

Code scanning / CodeQL

Log entries created from user input

This log entry depends on a [user-provided value](1).

Copilot Autofix

AI about 1 year ago

To fix the problem, we need to sanitize the user input before logging it. Since the log entries are plain text, we should remove any newline characters from the user input to prevent log forging. This can be done using the String.Replace method to replace newline characters with an empty string. We will apply this sanitization to the path variable before it is logged.

Suggested changeset 1
Controllers/PostController.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/Controllers/PostController.cs b/Controllers/PostController.cs
--- a/Controllers/PostController.cs
+++ b/Controllers/PostController.cs
@@ -94,2 +94,3 @@
   private async Task<string> ResizeIfNeeded(string path) {
+      path = path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
       _logger.LogDebug("Checking if resize is needed for path: {0}", path);
EOF
@@ -94,2 +94,3 @@
private async Task<string> ResizeIfNeeded(string path) {
path = path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", "");
_logger.LogDebug("Checking if resize is needed for path: {0}", path);
Copilot is powered by AI and may make mistakes. Always verify output.
var resizedPath = $"{Config.ConfigDir}/resized{path}";

if (System.IO.File.Exists(resizedPath))
return resizedPath;

try {
using (var image = await Image.LoadAsync(path)) {
int width, height;

if (image.Height > image.Width) {
// Portrait or square
height = Math.Min(image.Height, Config.ImageMaxSize);
width = (image.Width * height) / image.Height;
} else {
// Landscape
width = Math.Min(image.Width, Config.ImageMaxSize);
height = (image.Height * width) / image.Width;
}

if (image.Width != width || image.Height != height) {
image.Mutate(x => x.Resize(width, height));
await SaveResizedImage(image, resizedPath);
}
}
} catch (Exception e) {
_logger.LogError(e, "Error resizing file: {0}", path);

Check failure

Code scanning / CodeQL

Log entries created from user input

This log entry depends on a [user-provided value](1).

Copilot Autofix

AI about 1 year ago

To fix the problem, we need to sanitize the user input before logging it. Since the log entries are plain text, we should remove any newline characters from the user input to prevent log forging. This can be done using the String.Replace method to replace newline characters with an empty string. We will apply this sanitization to the path variable before it is used in any log entries.

Suggested changeset 1
Controllers/PostController.cs

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/Controllers/PostController.cs b/Controllers/PostController.cs
--- a/Controllers/PostController.cs
+++ b/Controllers/PostController.cs
@@ -62,3 +62,3 @@
               path = synologyPath;
-              _logger.LogDebug("Synology file exists. Updated path to: {0}", path);
+              _logger.LogDebug("Synology file exists. Updated path to: {0}", path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", ""));
               return await ReturnFileResponse(path);
@@ -68,3 +68,3 @@
       if (!System.IO.File.Exists(path)) {
-          _logger.LogWarning("File does not exist at path: {0}", path);
+          _logger.LogWarning("File does not exist at path: {0}", path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", ""));
           return NotFound();
@@ -94,3 +94,3 @@
   private async Task<string> ResizeIfNeeded(string path) {
-      _logger.LogDebug("Checking if resize is needed for path: {0}", path);
+      _logger.LogDebug("Checking if resize is needed for path: {0}", path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", ""));
       var resizedPath = $"{Config.ConfigDir}/resized{path}";
@@ -120,3 +120,3 @@
       } catch (Exception e) {
-          _logger.LogError(e, "Error resizing file: {0}", path);
+          _logger.LogError(e, "Error resizing file: {0}", path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", ""));
       }
EOF
@@ -62,3 +62,3 @@
path = synologyPath;
_logger.LogDebug("Synology file exists. Updated path to: {0}", path);
_logger.LogDebug("Synology file exists. Updated path to: {0}", path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", ""));
return await ReturnFileResponse(path);
@@ -68,3 +68,3 @@
if (!System.IO.File.Exists(path)) {
_logger.LogWarning("File does not exist at path: {0}", path);
_logger.LogWarning("File does not exist at path: {0}", path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", ""));
return NotFound();
@@ -94,3 +94,3 @@
private async Task<string> ResizeIfNeeded(string path) {
_logger.LogDebug("Checking if resize is needed for path: {0}", path);
_logger.LogDebug("Checking if resize is needed for path: {0}", path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", ""));
var resizedPath = $"{Config.ConfigDir}/resized{path}";
@@ -120,3 +120,3 @@
} catch (Exception e) {
_logger.LogError(e, "Error resizing file: {0}", path);
_logger.LogError(e, "Error resizing file: {0}", path.Replace(Environment.NewLine, "").Replace("\n", "").Replace("\r", ""));
}
Copilot is powered by AI and may make mistakes. Always verify output.
}

using (var outputStream = new MemoryStream())
{
using (var image = await Image.LoadAsync(path))
{
int width = image.Width / 2;
int height = image.Height / 2;
width = 0;
height = 0;
if(image.Height > image.Width && height > Config.ImageMaxSize)
height = Config.ImageMaxSize;
if (image.Width > image.Height && width > Config.ImageMaxSize)
width = Config.ImageMaxSize;

if (width + height != 0)
image.Mutate(x => x.Resize(width, height));
JpegEncoder encoder = new JpegEncoder();
encoder.Quality = Config.ImageQuality;
await image.SaveAsJpegAsync(outputStream, encoder);
}
outputStream.Position = 0;
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
using var destination = System.IO.File.Create(fileName, bufferSize: 4096);
await outputStream.CopyToAsync(destination);
return resizedPath;
}

return outputStream.ToArray();
}
} catch(Exception e){
_logger.LogError(e, "Error Reading File: {0}", path);
throw;
}
private async Task SaveResizedImage(Image image, string path) {
JpegEncoder encoder = new JpegEncoder { Quality = Config.ImageQuality };
Directory.CreateDirectory(Path.GetDirectoryName(path));
await image.SaveAsync(path, encoder);
}

}
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2023 Jonasbg
Copyright (c) 2024 Jonasbg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
2 changes: 1 addition & 1 deletion Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
}
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2023 - picoblog -
&copy; 2024 - picoblog -
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
Expand Down
2 changes: 1 addition & 1 deletion picoblog.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

<ItemGroup>
<PackageReference Include="Markdig" Version="0.37.0" />
<PackageReference Include="SixLabors.ImageSharp.Web" Version="2.0.2" />
<PackageReference Include="SixLabors.ImageSharp.Web" Version="3.1.2" />
<PackageReference Include="SharpCompress" Version="0.39.0" />
<!-- <PackageReference Include="LigerShark.WebOptimizer.Core" Version="3.0.391" /> -->
</ItemGroup>
Expand Down