Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge VNEXT into Main #464

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open

Merge VNEXT into Main #464

wants to merge 28 commits into from

Conversation

tankerkiller125
Copy link
Contributor

@tankerkiller125 tankerkiller125 commented Jan 12, 2025

We're dropping the separation of VNEXT features and main, and bringing them together. New features both big and small will all get released as part of the v0 series of versions.

Summary by CodeRabbit

  • New Features

    • Added PostgreSQL database support
    • Enhanced database configuration options
    • Introduced new environment variables for database configuration
    • Added lazy loading for images in markdown content
    • Updated Docker workflow triggers for focused monitoring
  • Documentation

    • Updated configuration documentation
    • Added upgrade guide for version 0.18+
    • Improved documentation for database settings
    • Enhanced security considerations in documentation
    • Added new sections and tips in installation and configuration guides
  • CI/CD

    • Updated GitHub Actions workflows
    • Added PostgreSQL integration tests
    • Expanded test coverage for different PostgreSQL versions
  • Chores

    • Updated dependencies
    • Modified ESLint configuration
    • Updated Taskfile for improved task management
    • Reorganized menu items in documentation

tankerkiller125 and others added 19 commits October 29, 2024 16:33
* feat: Multi-DB type URL formats and config

* fix: remove legacy sqlite path config and minor other things

* fix: dumb eslint issues

* fix: dumb eslint issues

* fix: application can be tested with sqlite

* fix: minor config formatting

* chore: some cleanup

* feat: postgres migration creation now works

The migration creation for postgres now works properly.
Removed MySQL support, having too many issues with it at this time.

* chore: revert some strings back to bytes as they should be

* feat: improve languages support

* feat: add locale time ago formatting and the local name for the language in language dropdown

* Update FUNDING.yml

* chore: remove some more mysql stuff

* fix: coderabbit security recommendations

* fix: validate postgres sslmode

* Update migrations.go

* fix: postgres migration creation now works

* fix: errors in raw sql queries

* fix: lint error, and simpler SQL query

* fix: migrations directory string

* fix: stats related test

* fix: sql query

* Update TextArea.vue

* Update TextField.vue

* chore: run integration testing on multiple postgresql versions

* chore: jobs should run for vnext branch PRs

* fix: missed $ for Postgres testing

* fix: environment variable for db ssl mode

* fix: lint issue from a merge

* chore: trying to fix postgresql testing

* chore: trying to fix postgresql testing

* fix: trying to fix postgresql testing

* fix: trying to fix postgresql testing

---------

Co-authored-by: tonya <[email protected]>
* feat: make 404 follow theme and add a return home page

* feat: sanitise translations when using v-html

* chore: Add native API docs to website

* chore: remove try it button from api docs

---------

Co-authored-by: tonyaellie <[email protected]>
Update dockerfile to test the theory of data folder breaking in vnext
* feat: Multi-DB type URL formats and config

* fix: remove legacy sqlite path config and minor other things

* fix: dumb eslint issues

* fix: dumb eslint issues

* fix: application can be tested with sqlite

* fix: minor config formatting

* chore: some cleanup

* feat: postgres migration creation now works

The migration creation for postgres now works properly.
Removed MySQL support, having too many issues with it at this time.

* chore: revert some strings back to bytes as they should be

* feat: improve languages support

* feat: add locale time ago formatting and the local name for the language in language dropdown

* Update FUNDING.yml

* chore: remove some more mysql stuff

* fix: coderabbit security recommendations

* fix: validate postgres sslmode

* Update migrations.go

* fix: postgres migration creation now works

* fix: errors in raw sql queries

* fix: lint error, and simpler SQL query

* fix: migrations directory string

* fix: stats related test

* fix: sql query

* Update TextArea.vue

* Update TextField.vue

* chore: run integration testing on multiple postgresql versions

* chore: jobs should run for vnext branch PRs

* fix: missed $ for Postgres testing

* fix: environment variable for db ssl mode

* fix: lint issue from a merge

* chore: trying to fix postgresql testing

* chore: trying to fix postgresql testing

* fix: trying to fix postgresql testing

* fix: trying to fix postgresql testing

---------

Co-authored-by: tonya <[email protected]>
Update dockerfile to test the theory of data folder breaking in vnext
Copy link
Contributor

coderabbitai bot commented Jan 12, 2025

Walkthrough

This pull request introduces comprehensive support for PostgreSQL in the Homebox application, expanding the database connectivity options beyond SQLite. The changes span multiple components including GitHub Actions workflows, configuration files, migration scripts, and backend code. The implementation enables dynamic database driver selection, PostgreSQL-specific migration files, and enhanced configuration management.

Changes

File Change Summary
.github/workflows/partial-frontend.yaml Added PostgreSQL integration test job with matrix strategy for different PostgreSQL versions; updated existing integration test job to include PostgreSQL service.
.github/workflows/pull-requests.yaml Added vnext branch and .github/workflows/** path triggers.
.gitignore Added SQLite journal and temporary file exclusions.
Taskfile.yml Added PostgreSQL-related tasks and environment variables.
backend/app/api/main.go Enhanced database connection logic with PostgreSQL support and improved error handling.
backend/app/tools/migrations/main.go Updated migration tool to support multiple database drivers.
backend/go.mod Updated dependency versions and added new PostgreSQL driver dependency.
backend/internal/data/migrations/migrations.go Updated migration file handling for multiple dialects.
backend/internal/sys/config/conf.go, conf_database.go Introduced new Database configuration struct.
docs/en/configure-homebox.md, docs/en/upgrade.md Updated with PostgreSQL-related environment variables and configuration changes.
docs/.vitepress/config.mts, docs/.vitepress/menus/en.mts Added new configuration for markdown and modified menu items.
frontend/.eslintrc.js Added new ESLint rules for Vue and Tailwind CSS.
backend/internal/data/migrations/postgres/20250112202302_catchup.sql Added new column to items table in PostgreSQL database.

Sequence Diagram

sequenceDiagram
    participant User
    participant Config
    participant DatabaseDriver
    participant Migrations
    participant Backend

    User->>Config: Specify database configuration
    Config->>DatabaseDriver: Select driver (sqlite3/postgres)
    DatabaseDriver->>Migrations: Generate dialect-specific migrations
    Migrations->>Backend: Apply database schema
    Backend->>User: Start application
Loading

Suggested Labels

⬆️ enhancement, 📖 documentation

Security Recommendations

  1. Ensure database credentials are stored securely, preferably using environment variables or secure secret management systems.
  2. Implement strong password policies for database user accounts.
  3. Configure SSL/TLS for PostgreSQL connections to encrypt data in transit.
  4. Limit database user permissions to the minimum required for application functionality.
  5. Regularly update database dependencies to patch potential security vulnerabilities.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3753a3a and 8694e62.

⛔ Files ignored due to path filters (1)
  • backend/go.sum is excluded by !**/*.sum
📒 Files selected for processing (4)
  • .github/workflows/docker-publish-rootless.yaml (1 hunks)
  • .github/workflows/docker-publish.yaml (2 hunks)
  • backend/app/api/main.go (6 hunks)
  • backend/internal/data/repo/repo_group_test.go (2 hunks)
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/docker-publish-rootless.yaml

14-14: unexpected key "ignore" for "push" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows"

(syntax-check)


25-25: unexpected key "ignore" for "pull_request" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows"

(syntax-check)

.github/workflows/docker-publish.yaml

14-14: unexpected key "ignore" for "push" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows"

(syntax-check)


25-25: unexpected key "ignore" for "pull_request" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows"

(syntax-check)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Backend Server Tests / Go
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: build (linux/arm64)
  • GitHub Check: build (linux/arm64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Analyze (go)
  • GitHub Check: Cloudflare Pages
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 20

🔭 Outside diff range comments (4)
frontend/pages/reports/label-generator.vue (1)

Line range hint 191-201: Add URL validation for QR code generation

The getQRCodeUrl function uses user input without proper URL validation, which could lead to security issues.

Add URL validation:

  function getQRCodeUrl(assetID: string): string {
    let origin = displayProperties.baseURL.trim();

+   try {
+     const url = new URL(origin);
+     if (!['http:', 'https:'].includes(url.protocol)) {
+       throw new Error('Invalid protocol');
+     }
+   } catch (e) {
+     notifier.error('Invalid base URL');
+     return '';
+   }

    // remove trailing slash
    if (origin.endsWith("/")) {
      origin = origin.slice(0, -1);
    }

    const data = `${origin}/a/${assetID}`;
    return route(`/qrcode`, { data: encodeURIComponent(data) });
  }
docs/.vitepress/config.mts (1)

🔒 API Documentation Security Review Required

The API documentation exposes sensitive implementation details that could aid potential attackers:

  • API documentation is publicly hosted on CDN (cdn.jsdelivr.net)
  • Authentication mechanisms and token handling are exposed in OpenAPI spec
  • Sensitive endpoints like password change and token refresh are fully documented
  • Example URLs contain API key parameters

Recommendations:

  • Move API documentation behind authentication
  • Sanitize examples to remove token references
  • Consider using API documentation versioning
  • Implement rate limiting on sensitive endpoints
  • Add security headers to prevent documentation indexing
🔗 Analysis chain

Line range hint 41-43: Review external link security in API documentation

The API documentation link should be reviewed to ensure it doesn't expose sensitive endpoints or implementation details.

Run this check to scan API documentation for potential security concerns:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for API endpoints in documentation
rg -g "*.md" "(GET|POST|PUT|DELETE) /api/" docs/en/

# Look for potential sensitive information patterns
rg -g "*.md" "(password|secret|key|token)" docs/en/api

Length of output: 162


Script:

#!/bin/bash
# Find all documentation files
echo "=== Documentation files ==="
fd -e md -e mts -e ts docs/

# Search for API-related content
echo -e "\n=== API-related content ==="
rg -i "api|endpoint|route" docs/

# Look for potential sensitive information
echo -e "\n=== Sensitive information patterns ==="
rg -i "(password|secret|key|token|credential)" docs/

# Find external URLs
echo -e "\n=== External URLs ==="
rg -i "https?://" docs/

Length of output: 11645

backend/internal/data/migrations/migrations.go (1)

Line range hint 38-47: Add validation for migration file contents.

Before writing files to disk, consider adding validation:

  1. Verify file size limits
  2. Validate file names against a whitelist
  3. Consider scanning SQL content for potentially harmful operations
+ const maxFileSize = 1024 * 1024 // 1MB limit
+ if len(b) > maxFileSize {
+   return fmt.Errorf("migration file too large: %s", f.Name())
+ }
+ if !isValidMigrationName(f.Name()) {
+   return fmt.Errorf("invalid migration file name: %s", f.Name())
+ }
  err = os.WriteFile(path.Join(temp, f.Name()), b, 0o644)
backend/go.mod (1)

Line range hint 3-3: Invalid Go version specified

The Go version 1.23.0 specified in the go.mod file does not exist. The latest stable version as of January 2025 is 1.22.0.

Apply this diff to fix the version:

-go 1.23.0
+go 1.22.0
🧹 Nitpick comments (7)
frontend/pages/reports/label-generator.vue (1)

72-74: Enhance measure validation

The current regex validation could be improved for better maintainability and type safety.

Consider using a constant or enum for valid measures:

-    const measureRegex = /in|cm|mm/;
-    const measure = measureRegex.test(input.measure) ? input.measure : "in";
+    const VALID_MEASURES = ["in", "cm", "mm"] as const;
+    type ValidMeasure = typeof VALID_MEASURES[number];
+    const measure = VALID_MEASURES.includes(input.measure as ValidMeasure) ? input.measure : "in";
backend/internal/data/migrations/migrations.go (1)

22-27: Consider more restrictive file permissions for security.

The directory permissions 0o755 might be more permissive than necessary. Consider using 0o750 to restrict access to owner and group only.

backend/internal/data/repo/repo_group.go (1)

226-236: Consider implementing rate limiting

While the query is secure against SQL injection, consider implementing rate limiting for this statistics endpoint to prevent potential DoS attacks on large datasets.

.github/workflows/partial-frontend.yaml (1)

81-82: Fix YAML formatting issues.

Address the following yamllint warnings:

  • Incorrect indentation in matrix strategy
  • Missing spaces after commas in database versions

Apply this diff:

-        matrix:
-            database_version: [17,16,15]
+      matrix:
+        database_version: [17, 16, 15]

Also applies to: 82-82

🧰 Tools
🪛 yamllint (1.35.1)

[warning] 81-81: wrong indentation: expected 6 but found 8

(indentation)


[warning] 82-82: wrong indentation: expected 10 but found 12

(indentation)


[warning] 82-82: too few spaces after comma

(commas)


[warning] 82-82: too few spaces after comma

(commas)

Taskfile.yml (1)

186-200: Add retry mechanism for PostgreSQL tests.

The current implementation uses a fixed sleep duration. Consider implementing a retry mechanism with proper connection testing.

docs/en/configure-homebox.md (1)

27-34: Enhance security recommendations for database configuration

Please add security recommendations for database configuration:

  1. Recommend using environment variables via secrets management
  2. Add a note about securing the PostgreSQL connection with SSL/TLS in production
  3. Document password complexity requirements
backend/internal/data/migrations/postgres/20241027025146_init.sql (1)

8-8: Consider table partitioning for items table

The items table might grow large over time. Consider:

  1. Implement table partitioning by created_at or group_items
  2. Add partial indexes for common query patterns

Example partitioning strategy:

CREATE TABLE items (
  -- existing columns
) PARTITION BY RANGE (created_at);

CREATE TABLE items_2024 PARTITION OF items
  FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');
🛑 Comments failed to post (20)
frontend/pages/reports/label-generator.vue (2)

410-414: ⚠️ Potential issue

Sanitize measure values in style bindings

Direct use of user input in style bindings could potentially lead to XSS attacks if the validation is bypassed.

Add a sanitization layer:

+ const sanitizeMeasure = (value: number, unit: string) => {
+   const sanitizedUnit = VALID_MEASURES.includes(unit as ValidMeasure) ? unit : "in";
+   return `${Number(value)}${sanitizedUnit}`;
+ };

  :style="{
-   paddingTop: `${out.page.pt}${out.measure}`,
+   paddingTop: sanitizeMeasure(out.page.pt, out.measure),
    // Apply similar changes to other style bindings
  }"

Also applies to: 435-436, 443-445


125-129: 🛠️ Refactor suggestion

Add input validation for measure type

The measure type input should be restricted to valid units ("in", "cm", "mm") to prevent invalid inputs.

Consider using a select input instead of text:

-      {
-        label: "Measure Type",
-        ref: "measure",
-        type: "text",
-      },
+      {
+        label: "Measure Type",
+        ref: "measure",
+        type: "select",
+        options: ["in", "cm", "mm"],
+      },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      {
        label: "Measure Type",
        ref: "measure",
        type: "select",
        options: ["in", "cm", "mm"],
      },
backend/app/tools/migrations/main.go (3)

68-68: ⚠️ Potential issue

Ensure Sensitive Credentials Are Not Exposed

When constructing the databaseURL for PostgreSQL, sensitive information such as cfg.Database.Username and cfg.Database.Password are embedded directly into the connection string. Ensure that this connection string is not logged or exposed in any error messages or logs to prevent leakage of credentials.


29-35: ⚠️ Potential issue

Validate and Sanitize Database Driver Input

The cfg.Database.Driver value is used to determine the SQL dialect and construct the databaseURL. Ensure that this input is validated and sanitized to prevent injection of unexpected or malicious values that could lead to security vulnerabilities or application crashes.

Also applies to: 63-71


39-39: 🛠️ Refactor suggestion

Secure Path Construction to Prevent Path Traversal

While constructing safePath with filepath.Clean, ensure that the sqlDialect variable is validated against a whitelist of expected values. This prevents potential path traversal attacks if sqlDialect were to contain unexpected values.

backend/app/api/main.go (3)

111-111: ⚠️ Potential issue

Protect Sensitive Information in Connection Strings

The databaseURL for PostgreSQL includes sensitive credentials. To enhance security, ensure that this connection string is kept confidential and not logged or exposed in application logs or error messages.


99-104: ⚠️ Potential issue

Enforce Secure SSL Modes for Database Connections

While the application allows various sslmode settings for PostgreSQL, including insecure modes like disable, consider enforcing secure SSL modes such as require, verify-ca, or verify-full by default. Allowing insecure SSL modes can expose database connections to interception or man-in-the-middle attacks.


121-124: 🛠️ Refactor suggestion

Limit Exposure of Database Details in Logs

Logging database connection errors with details like host, port, and database can inadvertently expose sensitive information. Consider reducing the verbosity of logs in production environments or masking sensitive details to enhance security.

backend/internal/sys/config/conf_database.go (2)

12-20: ⚠️ Potential issue

Secure Handling of Database Credentials in Configuration

Storing sensitive information such as Username, Password, and SslMode directly in configuration files can pose security risks if these files are improperly accessed. Consider using environment variables or a secrets management service to handle sensitive credentials, reducing the risk of exposure.


20-20: 🛠️ Refactor suggestion

Use Absolute Paths for Database Files

The SqlitePath uses a relative path ./.data/homebox.db, which may lead to security issues if the application's working directory is changed or manipulated. To enhance security, use absolute paths or ensure that the relative path resolves to a secure, application-specific directory.

frontend/.eslintrc.js (1)

29-29: ⚠️ Potential issue

Security Warning: Enabling v-html increases XSS risk.

Disabling the vue/no-v-html rule allows the use of v-html directive, which can lead to Cross-Site Scripting (XSS) vulnerabilities if user input is not properly sanitized. Consider:

  1. Re-enabling the rule
  2. Using alternative approaches like markdown renderers
  3. If v-html is necessary, ensure strict input sanitization
backend/internal/sys/config/conf.go (1)

21-29: 🛠️ Refactor suggestion

Implement secure configuration handling.

The Config struct contains sensitive information (database credentials, mailer settings). Consider:

  1. Implementing field masking when logging configurations
  2. Using environment variables for sensitive values
  3. Adding encryption for configuration storage
func (c *Config) Print() {
+   // Create a copy with masked sensitive fields
+   masked := *c
+   masked.Database.Password = "********"
+   masked.Mailer.Password = "********"
    res, err := json.MarshalIndent(&masked, "", "  ")
    if err != nil {
        panic(err)
    }
    fmt.Println(string(res))
}

Committable suggestion skipped: line range outside the PR's diff.

docs/en/upgrade.md (1)

11-13: 🛠️ Refactor suggestion

Add security recommendations for PostgreSQL configuration

Please add the following security recommendations to the upgrade guide:

  1. Use SSL/TLS for PostgreSQL connections
  2. Create a dedicated database user with minimal privileges
  3. Store database credentials securely (e.g., using environment variables or secrets management)
  4. Configure network security groups/firewall rules to restrict database access
backend/go.mod (1)

16-16: 💡 Codebase verification

⚠️ Strengthen PostgreSQL SSL/TLS Configuration

While the PostgreSQL driver is secure, the current SSL mode validation allows insecure options. Consider:

  • Modify validatePostgresSSLMode to reject insecure modes (disable, allow) in production
  • Enforce minimum require mode, preferably verify-ca or verify-full
  • Don't allow empty SSL mode to prevent relying on defaults
🔗 Analysis chain

Verify PostgreSQL driver security advisories

The addition of github.com/lib/pq introduces PostgreSQL support. While this is a well-maintained driver, it's crucial to ensure it's properly configured for security.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for security advisories for lib/pq
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: GO, package: "github.com/lib/pq") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 349


Script:

#!/bin/bash
# Search for database connection patterns and configuration
rg -A 5 "lib/pq" --type go

# Look for connection strings and database configuration
rg -A 5 "postgres://" --type go
rg -A 5 "postgresql://" --type go

# Search for SSL/TLS related configuration
rg -A 5 "sslmode" --type go

Length of output: 3162


Script:

#!/bin/bash
# Check for SSL mode configuration defaults
rg -A 5 "Database.*SslMode" --type go
rg "default.*sslmode" -i --type go

Length of output: 2052


Script:

#!/bin/bash
# Find the validatePostgresSSLMode function implementation
ast-grep --pattern 'func validatePostgresSSLMode($_) $_'

# Alternative search using ripgrep
rg -A 10 "func validatePostgresSSLMode" --type go

Length of output: 2849

Dockerfile (1)

69-71: ⚠️ Potential issue

Security: Restrict directory permissions

Setting chmod -R 777 on the /data directory grants full read/write/execute permissions to all users, which violates the principle of least privilege.

Apply this diff to use more restrictive permissions:

-RUN mkdir -p /app /data && chmod -R 777 /data
+RUN mkdir -p /app /data && chown -R nobody:nobody /data && chmod -R 755 /data
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

# Create application and data directories with the correct permissions
RUN mkdir -p /app /data && chown -R nobody:nobody /data && chmod -R 755 /data

Taskfile.yml (1)

69-75: ⚠️ Potential issue

Review PostgreSQL security configuration.

Security concerns in PostgreSQL configuration:

  1. SSL mode is disabled (ssl_mode: disable)
  2. Hardcoded database credentials
  3. No connection timeout settings

Consider:

  1. Enabling SSL in production
  2. Using environment variables for credentials
  3. Adding connection timeouts
docs/en/configure-homebox.md (1)

28-28: 💡 Codebase verification

🔐 Add Security Guidelines for Database Configuration

The SQLite database configuration needs additional security documentation:

  • For Docker deployments:

    • ✅ Current rootless container setup is secure
    • Add backup procedure documentation
  • For direct binary deployments:

    • Document that ./.data/homebox.db should be changed to an absolute path (e.g., /var/lib/homebox/data/homebox.db)
    • Add file permission requirements (e.g., 0600 for the database file)
    • Include directory ownership recommendations
    • Document backup best practices
🔗 Analysis chain

Review SQLite database path security

The default SQLite path ./.data/homebox.db might expose the database file. Consider:

  1. Using absolute paths in production
  2. Adding file permission recommendations
  3. Documenting backup procedures
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if SQLite database path is exposed in public directories
fd -t f "homebox.db" | grep -v "private\|internal"

Length of output: 50


Script:

#!/bin/bash
# Search for documentation about database configuration and security
echo "=== Searching documentation files ==="
rg -i "database|sqlite" docs/ -A 3 -B 3

echo -e "\n=== Checking for deployment or production setup guides ==="
fd "deploy|production|install" docs/

echo -e "\n=== Looking for security-related documentation ==="
rg -i "security|permission|backup" docs/

Length of output: 12917


Script:

#!/bin/bash
# Check installation guide content
echo "=== Installation Guide Content ==="
cat docs/en/installation.md

echo -e "\n=== Check for data directory references ==="
rg -i "\.data|data dir" docs/ -A 2 -B 2

Length of output: 7391

backend/internal/data/migrations/postgres/20241027025146_init.sql (3)

24-24: ⚠️ Potential issue

Enhance password storage security

The users table stores passwords without explicitly specifying column constraints for hashed passwords. Consider:

  1. Add a CHECK constraint to ensure minimum password hash length
  2. Add a comment specifying the hashing algorithm

Apply this diff:

-"password" character varying NOT NULL,
+"password" character varying NOT NULL CHECK (length(password) >= 60),
+COMMENT ON COLUMN users.password IS 'BCrypt hashed password';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

CREATE TABLE "users" ("id" uuid NOT NULL, "created_at" timestamptz NOT NULL, "updated_at" timestamptz NOT NULL, "name" character varying NOT NULL, "email" character varying NOT NULL, "password" character varying NOT NULL CHECK (length(password) >= 60), "is_superuser" boolean NOT NULL DEFAULT false, "superuser" boolean NOT NULL DEFAULT false, "role" character varying NOT NULL DEFAULT 'user', "activated_on" timestamptz NULL, "group_users" uuid NOT NULL, PRIMARY KEY ("id"), CONSTRAINT "users_groups_users" FOREIGN KEY ("group_users") REFERENCES "groups" ("id") ON UPDATE NO ACTION ON DELETE CASCADE);
COMMENT ON COLUMN users.password IS 'BCrypt hashed password';

50-50: 🛠️ Refactor suggestion

Secure notifier URL storage

The notifiers table stores URLs without validation. Consider:

  1. Add a CHECK constraint for URL format
  2. Add a maximum length constraint

Apply this diff:

-"url" character varying NOT NULL,
+"url" character varying(2048) NOT NULL CHECK (url ~ '^https?://'),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

CREATE TABLE "notifiers" ("id" uuid NOT NULL, "created_at" timestamptz NOT NULL, "updated_at" timestamptz NOT NULL, "name" character varying NOT NULL, "url" character varying(2048) NOT NULL CHECK (url ~ '^https?://'), "is_active" boolean NOT NULL DEFAULT true, "group_id" uuid NOT NULL, "user_id" uuid NOT NULL, PRIMARY KEY ("id"), CONSTRAINT "notifiers_groups_notifiers" FOREIGN KEY ("group_id") REFERENCES "groups" ("id") ON UPDATE NO ACTION ON DELETE CASCADE, CONSTRAINT "notifiers_users_notifiers" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON UPDATE NO ACTION ON DELETE CASCADE);

28-28: 🛠️ Refactor suggestion

Review token storage implementation

The auth_tokens table uses bytea for token storage. Consider:

  1. Add a CHECK constraint for minimum token length
  2. Add index for expires_at for efficient token cleanup

Apply this diff:

-"token" bytea NOT NULL,
+"token" bytea NOT NULL CHECK (length(token) >= 32),
 "expires_at" timestamptz NOT NULL,
+CREATE INDEX "idx_auth_tokens_expires_at" ON "auth_tokens" ("expires_at");

Committable suggestion skipped: line range outside the PR's diff.

# Conflicts:
#	.github/workflows/docker-publish-arm.yaml
#	.github/workflows/docker-publish-rootless-arm.yaml
#	.github/workflows/docker-publish-rootless.yaml
#	.github/workflows/docker-publish.yaml
#	Dockerfile
#	Dockerfile.rootless
#	Taskfile.yml
#	backend/app/api/main.go
#	backend/app/tools/migrations/main.go
#	backend/go.sum
#	backend/internal/data/migrations/sqlite3/20241226183416_sync_childs.sql
#	backend/internal/sys/config/conf_database.go
#	docs/en/configure-homebox.md
#	frontend/pages/reports/label-generator.vue
Copy link

cloudflare-workers-and-pages bot commented Jan 12, 2025

Deploying homebox-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 8694e62
Status: ✅  Deploy successful!
Preview URL: https://e8a473d0.homebox-docs.pages.dev
Branch Preview URL: https://vnext.homebox-docs.pages.dev

View logs

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 4

🔭 Outside diff range comments (1)
backend/app/api/main.go (1)

Line range hint 133-171: Secure temporary migration files handling

The temporary directory handling could be improved for better security:

  1. Directory permissions not explicitly set
  2. Potential race condition between creation and use
  3. Migration files might contain sensitive data

Consider these security improvements:

 tempUUID, err := uuid.NewUUID()
 if err != nil {
     return err
 }
 temp := filepath.Join(os.TempDir(), fmt.Sprintf("homebox-%s", tempUUID.String()))
+
+// Create directory with restricted permissions
+if err := os.MkdirAll(temp, 0700); err != nil {
+    return fmt.Errorf("failed to create temporary directory: %w", err)
+}
+
+// Ensure immediate cleanup
+defer func() {
+    if err := os.RemoveAll(temp); err != nil {
+        log.Error().Err(err).Msg("failed to remove temporary directory for database migrations")
+    }
+}()

 err = migrations.Write(temp, cfg.Database.Driver)
🧹 Nitpick comments (1)
backend/app/api/main.go (1)

Line range hint 1-324: General security recommendations

Several security considerations for the overall implementation:

  1. Debug Server:

    • Ensure debug server is never enabled in production
    • Add IP restrictions for debug endpoints
  2. Demo Mode:

    • Add explicit warning logs when running in demo mode
    • Consider environment-based restrictions
  3. Token Management:

    • Consider adding rate limiting for token purge operations
    • Add metrics/monitoring for failed purge attempts

Consider implementing these security enhancements:

  1. Add environment-based configuration validation:
if cfg.Debug.Enabled && !isDevelopment() {
    log.Fatal().Msg("Debug server cannot be enabled in production")
}
  1. Add IP restrictions for debug server:
debugserver := http.Server{
    Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if !isLocalhost(r.RemoteAddr) {
            http.Error(w, "Forbidden", http.StatusForbidden)
            return
        }
        app.debugRouter().ServeHTTP(w, r)
    }),
}
🛑 Comments failed to post (4)
docs/en/configure-homebox.md (1)

27-34: 🛠️ Refactor suggestion

Enhance security documentation for database configuration

The documentation should include:

  1. Security best practices for production deployments
  2. Warning about SSL requirements for PostgreSQL
  3. Credential management recommendations
  4. File permission requirements for SQLite

Add a security section with these recommendations:

+| HBOX_DATABASE_SSL_MODE          |                                                                            | sets the sslmode for a postgres connection                                             |
+
+::: warning "Security Considerations"
+- For PostgreSQL in production:
+  - Always enable SSL (sslmode=verify-full)
+  - Use strong, unique passwords
+  - Consider using connection pooling
+- For SQLite:
+  - Secure file permissions (600)
+  - Regular backups
+  - Monitor disk space
+:::

Committable suggestion skipped: line range outside the PR's diff.

backend/app/api/main.go (3)

116-124: ⚠️ Potential issue

Secure error logging for database connections

The error logging exposes sensitive connection details.

Consider this security-conscious version:

 c, err := ent.Open(strings.ToLower(cfg.Database.Driver), databaseURL)
 if err != nil {
     log.Fatal().
         Err(err).
         Str("driver", strings.ToLower(cfg.Database.Driver)).
-        Str("host", cfg.Database.Host).
-        Str("port", cfg.Database.Port).
-        Str("database", cfg.Database.Database).
-        Msg("failed opening connection to {driver} database at {host}:{port}/{database}")
+        Msg("failed opening database connection")
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	c, err := ent.Open(strings.ToLower(cfg.Database.Driver), databaseURL)
	if err != nil {
		log.Fatal().
			Err(err).
			Str("driver", strings.ToLower(cfg.Database.Driver)).
			Msg("failed opening database connection")

105-114: ⚠️ Potential issue

Secure database URL construction

The database URL construction includes sensitive credentials that could be exposed through logs or error messages.

Consider these security improvements:

 switch strings.ToLower(cfg.Database.Driver) {
 case "sqlite3":
     databaseURL = cfg.Database.SqlitePath
 case "postgres":
-    databaseURL = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s", cfg.Database.Host, cfg.Database.Port, cfg.Database.Username, cfg.Database.Password, cfg.Database.Database, cfg.Database.SslMode)
+    databaseURL = fmt.Sprintf("host=%s port=%s user=%s password=<redacted> dbname=%s sslmode=%s connect_timeout=10", 
+        cfg.Database.Host, 
+        cfg.Database.Port, 
+        cfg.Database.Username, 
+        cfg.Database.Database, 
+        cfg.Database.SslMode,
+    )
+    // Actual connection string with real password
+    actualURL := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s connect_timeout=10",
+        cfg.Database.Host,
+        cfg.Database.Port,
+        cfg.Database.Username,
+        cfg.Database.Password,
+        cfg.Database.Database,
+        cfg.Database.SslMode,
+    )
 default:
     log.Fatal().Str("driver", cfg.Database.Driver).Msg("unsupported database driver")
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	// Set up the database URL based on the driver because for some reason a common URL format is not used
	databaseURL := ""
	switch strings.ToLower(cfg.Database.Driver) {
	case "sqlite3":
		databaseURL = cfg.Database.SqlitePath
	case "postgres":
		databaseURL = fmt.Sprintf("host=%s port=%s user=%s password=<redacted> dbname=%s sslmode=%s connect_timeout=10", 
			cfg.Database.Host, 
			cfg.Database.Port, 
			cfg.Database.Username, 
			cfg.Database.Database, 
			cfg.Database.SslMode,
		)
		// Actual connection string with real password
		actualURL := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s connect_timeout=10",
			cfg.Database.Host,
			cfg.Database.Port,
			cfg.Database.Username,
			cfg.Database.Password,
			cfg.Database.Database,
			cfg.Database.SslMode,
		)
	default:
		log.Fatal().Str("driver", cfg.Database.Driver).Msg("unsupported database driver")
	}

52-63: ⚠️ Potential issue

Enhance PostgreSQL SSL mode security validation

The current SSL mode validation has security implications:

  1. Empty string is considered valid, which could lead to insecure defaults
  2. No audit logging of the chosen SSL mode

Consider this security-enhanced version:

 func validatePostgresSSLMode(sslMode string) bool {
 	validModes := map[string]bool{
-		"":            true,
 		"disable":     true,
 		"allow":       true,
 		"prefer":      true,
 		"require":     true,
 		"verify-ca":   true,
 		"verify-full": true,
 	}
-	return validModes[strings.ToLower(strings.TrimSpace(sslMode))]
+	mode := strings.ToLower(strings.TrimSpace(sslMode))
+	if mode == "" {
+		mode = "prefer"  // Secure default
+	}
+	log.Info().Str("postgres_ssl_mode", mode).Msg("PostgreSQL SSL mode configured")
+	return validModes[mode]
 }

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🧹 Nitpick comments (2)
docs/en/configure-homebox.md (2)

29-34: Enhance PostgreSQL configuration documentation

Please add validation rules and examples for PostgreSQL configuration:

  • HBOX_DATABASE_PORT: Valid range (typically 5432)
  • HBOX_DATABASE_HOST: Valid formats (IP, hostname)
  • HBOX_DATABASE_SSL_MODE: Valid options (disable, require, verify-ca, verify-full)

37-50: Add comprehensive security monitoring recommendations

Please add a new section on security monitoring and maintenance:

  • Regular vulnerability scanning
  • Database activity monitoring
  • Failed login attempt monitoring
  • Regular security audits
  • Incident response procedures
  • Backup verification procedures

Would you like me to provide a detailed section on security monitoring best practices?

🛑 Comments failed to post (3)
docs/en/configure-homebox.md (3)

38-44: 🛠️ Refactor suggestion

Enhance PostgreSQL security recommendations

The PostgreSQL security section should include additional critical security measures:

  • Network security (firewall rules, VPC/private subnet deployment)
  • Regular security updates for PostgreSQL
  • Audit logging configuration
  • Connection pooling configuration examples
  • Role-based access control (RBAC)
  • Database encryption at rest

45-50: 🛠️ Refactor suggestion

Enhance SQLite security recommendations

Add these critical security measures for SQLite:

  • Encryption recommendations for database files
  • Backup encryption requirements
  • Access control through filesystem ACLs
  • Regular integrity checks
  • WAL file security considerations

76-83: ⚠️ Potential issue

Add security warning for CLI password argument

Please add a warning about security implications of using --database-password in CLI:

  • Password visible in process list (ps aux)
  • Shell history exposure
  • Recommend using environment variables or configuration files instead

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 4

🔭 Outside diff range comments (2)
docs/en/installation.md (2)

Line range hint 13-25: Enhance security guidance for Docker deployment

The Docker installation section should include security best practices.

Consider adding these security recommendations:

### Docker Security Best Practices

1. Always use specific version tags instead of `latest` in production
2. Enable Docker's security features:
   - Add `--security-opt no-new-privileges:true`
   - Consider using `--read-only` for container filesystem
3. Implement resource limits:
   - Add memory limits: `--memory="512m"`
   - Add CPU limits: `--cpus="1.0"`
4. Avoid running containers with `--privileged` flag

Line range hint 38-61: Add security hardening to Docker Compose configuration

The Docker Compose example should demonstrate secure configuration practices.

Consider enhancing the example with security configurations:

 services:
   homebox:
     image: ghcr.io/sysadminsmedia/homebox:latest
     container_name: homebox
     restart: always
+    security_opt:
+      - no-new-privileges:true
+    read_only: true
+    tmpfs:
+      - /tmp
+    deploy:
+      resources:
+        limits:
+          memory: 512M
+          cpus: '1.0'
     environment:
     - HBOX_LOG_LEVEL=info
     - HBOX_LOG_FORMAT=text
     - HBOX_WEB_MAX_UPLOAD_SIZE=10
+    # Add comment about securing sensitive environment variables
     volumes:
       - homebox-data:/data/
     ports:
       - 127.0.0.1:3100:7745  # Bind to localhost only
🧹 Nitpick comments (8)
docs/en/index.md (2)

43-43: Document security considerations for PostgreSQL backend

While adding PostgreSQL as a backend option is great for larger installations, it's important to document security best practices. Consider adding a security section or link to configuration documentation covering:

  • SSL/TLS configuration
  • Authentication methods
  • Network security
  • Backup procedures

Would you like me to help draft a security considerations section for the PostgreSQL backend?


56-56: Consider rephrasing for better readability

The repeated use of "We" at the start of consecutive sentences could be improved for better flow.

Consider this revision:

-We've found spreadsheets get pretty unwieldy when you have a lot of data, and it's hard to keep track of what's where. We also wanted to be able to search and filter my data in a more robust way than a spreadsheet can provide. We also wanted to leave the door open for more advanced features
+We've found spreadsheets get pretty unwieldy when you have a lot of data, making it difficult to track what's where. Additionally, we wanted better search and filtering capabilities than what spreadsheets provide. Furthermore, we aimed to leave the door open for more advanced features
🧰 Tools
🪛 LanguageTool

[style] ~56-~56: To elevate your writing, try using a synonym here.
Context: ...y when you have a lot of data, and it's hard to keep track of what's where. We also ...

(HARD_TO)


[style] ~56-~56: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ust way than a spreadsheet can provide. We also wanted to leave the door open for ...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

docs/en/installation.md (2)

8-10: Consider adding security recommendations for environment variables

While the new configuration section is helpful, it should include security best practices for handling environment variables, especially in production environments.

Consider adding a security note like:

::: warning Security Note
Protect your environment variables and never commit them to version control. Consider using environment variable management tools or secrets management systems in production.
:::

Line range hint 95-115: Add security considerations for native installations

The native installation instructions for Windows, Linux, and macOS should include security best practices.

Consider adding a security section:

### Security Considerations for Native Installation

1. Run the application with a dedicated service account with minimal privileges
2. Configure your system's firewall to restrict access to port 7745
3. Consider setting up a reverse proxy with HTTPS for production use
4. Regularly update to the latest version for security patches
docs/.vitepress/menus/en.mts (1)

7-8: LGTM! Menu structure changes look good.

The reorganization of configuration and upgrade documentation into separate items improves clarity and makes these important sections more discoverable.

Security Recommendation: Consider adding a Security Best Practices section

Given that this PR introduces PostgreSQL support, it would be valuable to add a dedicated security section in the documentation menu covering:

  • Database security configurations
  • Authentication best practices
  • Network security considerations
docs/en/configure.md (3)

42-55: Enhance security recommendations section

Consider adding these additional security recommendations:

  1. For PostgreSQL:

    • Document recommended pg_hba.conf settings
    • Add note about using connection timeouts
    • Recommend periodic password rotation
  2. For SQLite:

    • Add specific chmod and chown commands
    • Recommend using separate mount points for database files
    • Add backup encryption recommendations

Would you like me to provide detailed examples for these security recommendations?


57-94: Improve CLI arguments documentation structure and security notes

Consider these improvements:

  1. Add a security warning about command-line arguments being visible in process listings
  2. Group arguments by category (Web, Database, Security, etc.)
  3. Add examples for secure usage in production

Would you like me to provide an example of the reorganized CLI arguments section?


12-12: Fix typographical issues in documentation

The following lines contain incorrect colon usage:

  • Line 12: "...can be one of: development..." should be "...can be either development..."
  • Line 24: "...can be one of: text..." should be "...can be either text..."
  • Line 31: "...can be one of: http..." should be "...can be either http..."

Also applies to: 24-24, 31-31

🧰 Tools
🪛 LanguageTool

[typographical] ~12-~12: Do not use a colon (:) before a series that is introduced by a preposition (‘of’). Remove the colon or add a noun or a noun phrase after the preposition.
Context: ...e used for runtime behavior can be one of: development, production | | HBOX_WE...

(RP_COLON)

🛑 Comments failed to post (4)
.github/workflows/docker-publish-rootless.yaml (2)

13-15: ⚠️ Potential issue

Fix invalid workflow trigger syntax

The ignore key is not valid in GitHub Actions workflow triggers. Use paths-ignore instead for excluding paths.

Apply this change to fix the syntax and maintain the intended behavior:

    paths:
      - 'backend/**'
      - 'frontend/**'
      - 'Dockerfile'
      - '.dockerignore'
      - '.github/workflows/docker-publish-rootless.yaml'
-    ignore:
-      - 'docs/**'
+    paths-ignore:
+      - 'docs/**'

Additionally, from a security perspective, consider adding these paths to ensure no sensitive files trigger builds:

    paths-ignore:
      - 'docs/**'
+     - '**/*.md'
+     - '**/*.env.example'
+     - '.github/ISSUE_TEMPLATE/**'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - '.github/workflows/docker-publish-rootless.yaml'
    paths-ignore:
      - 'docs/**'
      - '**/*.md'
      - '**/*.env.example'
      - '.github/ISSUE_TEMPLATE/**'
🧰 Tools
🪛 actionlint (1.7.4)

14-14: unexpected key "ignore" for "push" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows"

(syntax-check)


24-26: ⚠️ Potential issue

Apply the same syntax fix to pull_request trigger

The same syntax issue exists in the pull_request trigger section.

Apply the same fix here:

    paths:
      - 'backend/**'
      - 'frontend/**'
      - 'Dockerfile'
      - '.dockerignore'
      - '.github/workflows/docker-publish-rootless.yaml'
-    ignore:
-      - 'docs/**'
+    paths-ignore:
+      - 'docs/**'
+     - '**/*.md'
+     - '**/*.env.example'
+     - '.github/ISSUE_TEMPLATE/**'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - '.github/workflows/docker-publish-rootless.yaml'
    paths-ignore:
      - 'docs/**'
      - '**/*.md'
      - '**/*.env.example'
      - '.github/ISSUE_TEMPLATE/**'
🧰 Tools
🪛 actionlint (1.7.4)

25-25: unexpected key "ignore" for "pull_request" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows"

(syntax-check)

.github/workflows/docker-publish.yaml (1)

13-15: ⚠️ Potential issue

Apply consistent syntax fixes and enhance security measures

The same syntax issues exist in this file. Additionally, since this is a Docker publishing workflow, let's enhance security measures.

  1. Fix the syntax issues as in the rootless workflow.
  2. Consider these additional security enhancements:
permissions:
  # Restrict permissions to minimum required
  contents: read
  packages: write
  id-token: write
  security-events: write  # For vulnerability scanning

# Add Vulnerability Scanning
steps:
  - name: Run Trivy vulnerability scanner
    uses: aquasecurity/trivy-action@master
    with:
      image-ref: ${{ env.DOCKERHUB_REPO }}:${{ steps.meta.outputs.version }}
      format: 'sarif'
      output: 'trivy-results.sarif'

Would you like me to create a GitHub issue to track the implementation of these security enhancements?

Also applies to: 24-26

🧰 Tools
🪛 actionlint (1.7.4)

14-14: unexpected key "ignore" for "push" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows"

(syntax-check)

docs/en/configure.md (1)

32-39: 💡 Codebase verification

Document supported SSL mode values for PostgreSQL configuration

The documentation already includes strong security recommendations for SSL modes. However, it would be helpful to list all supported values for HBOX_DATABASE_SSL_MODE:

  • disable
  • allow
  • prefer
  • require (recommended for production)
  • verify-ca
  • verify-full (recommended for production)
🔗 Analysis chain

Consider security-first defaults for database configuration

For enhanced security, consider the following recommendations:

  1. Set HBOX_DATABASE_SSL_MODE default to require for PostgreSQL
  2. Add a note about using environment variables or secrets management for sensitive values like HBOX_DATABASE_PASSWORD
  3. Document the supported values for HBOX_DATABASE_SSL_MODE

Let's verify the supported SSL modes in the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for SSL mode validation or supported values
rg -A 5 "SSL[_ ]?MODE|ssl[_ ]?mode" 

Length of output: 4918


Script:

#!/bin/bash
# Search for SSL mode validation code
ast-grep --pattern 'if $_ := $_.SslMode; $_ {
  $$$
}'

Length of output: 56


Script:

#!/bin/bash
# Search for SSL mode validation or error handling
rg -B 2 -A 2 'invalid.+sslmode|sslmode.+invalid'

Length of output: 708


Script:

#!/bin/bash
# Search for validatePostgresSSLMode function implementation
ast-grep --pattern 'func validatePostgresSSLMode($_) $_ {
  $$$
}'

Length of output: 1509

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🔭 Outside diff range comments (2)
backend/internal/data/repo/repo_group_test.go (1)

36-48: Investigate and fix the commented-out test instead of leaving it disabled.

The output confirms that the Test_Group_GroupStatistics function in backend/internal/data/repo/repo_group_test.go (lines 36-48) remains commented out. Leaving such tests disabled not only masks functionality issues—as evidenced by the noted discrepancy between test and production environments—but can also hide vulnerabilities related to data handling and integrity. It is recommended to re-enable the test after thorough investigation to ensure both functional consistency and robust security checks.

  • backend/internal/data/repo/repo_group_test.go (lines 36-48): The test for group statistics is currently commented out. Please revisit the failure scenario, resolve the underlying issue, and re-enable the test to ensure consistent behavior and to avoid potential security risks.

Additionally, ensure that any fixes in this area come with added security validations, so you can confidently verify that vulnerabilities are not inadvertently introduced.

🔗 Analysis chain

Investigate and fix the commented-out test instead of disabling it.

Commenting out tests without proper investigation could mask potential issues that might surface in production. The discrepancy between test and production behavior needs thorough investigation.

Let's verify if there are any similar patterns of commented-out tests:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for commented-out test functions
rg -U "(?s)/\*\s*func\s+Test.*?\*/" --type go

Length of output: 947

backend/app/api/main.go (1)

135-172: Secure temporary directory creation and cleanup.

The temporary directory creation and cleanup need additional security measures:

  1. Set proper permissions on the temporary directory
  2. Ensure cleanup runs even if the program panics

Apply this diff to enhance security:

 	tempUUID, err := uuid.NewUUID()
 	if err != nil {
 		return err
 	}
 	temp := filepath.Join(os.TempDir(), fmt.Sprintf("homebox-%s", tempUUID.String()))
+	if err := os.MkdirAll(temp, 0700); err != nil {
+		return fmt.Errorf("failed to create temporary directory: %w", err)
+	}
+	defer func() {
+		if err := os.RemoveAll(temp); err != nil {
+			log.Error().Err(err).Msg("failed to remove temporary directory")
+		}
+	}()
♻️ Duplicate comments (1)
.github/workflows/docker-publish-rootless.yaml (1)

14-16: ⚠️ Potential issue

Fix invalid workflow syntax and enhance security.

  1. Replace ignore with paths-ignore as per GitHub Actions syntax
  2. Consider adding SLSA provenance generation for better supply chain security

Also applies to: 25-27

🧰 Tools
🪛 actionlint (1.7.4)

14-14: unexpected key "ignore" for "push" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows"

(syntax-check)

🛑 Comments failed to post (3)
backend/app/api/main.go (2)

119-125: ⚠️ Potential issue

Remove sensitive information from error logs.

The error logging includes database credentials which could be exposed in log files. This is a security risk.

Apply this diff to remove sensitive information:

-			Str("driver", strings.ToLower(cfg.Database.Driver)).
-			Str("host", cfg.Database.Host).
-			Str("port", cfg.Database.Port).
-			Str("database", cfg.Database.Database).
-			Msg("failed opening connection to {driver} database at {host}:{port}/{database}")
+			Str("driver", strings.ToLower(cfg.Database.Driver)).
+			Msg("failed opening connection to database")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

		log.Fatal().
			Err(err).
			Str("driver", strings.ToLower(cfg.Database.Driver)).
			Msg("failed opening connection to database")

107-115: ⚠️ Potential issue

Validate database driver input to prevent injection.

The database driver input should be validated against a whitelist to prevent potential injection attacks.

Apply this diff to add validation:

+var validDrivers = map[string]bool{
+    "sqlite3":  true,
+    "postgres": true,
+}
+
 switch strings.ToLower(cfg.Database.Driver) {
+    if !validDrivers[strings.ToLower(cfg.Database.Driver)] {
+        log.Fatal().Str("driver", cfg.Database.Driver).Msg("unsupported database driver")
+    }

Committable suggestion skipped: line range outside the PR's diff.

.github/workflows/docker-publish.yaml (1)

14-16: ⚠️ Potential issue

Fix invalid workflow syntax and enhance security.

  1. Replace ignore with paths-ignore as per GitHub Actions syntax
  2. Consider adding SLSA provenance generation for better supply chain security

Apply this diff to both workflow files:

-    ignore:
-      - 'docs/**'
+    paths-ignore:
+      - 'docs/**'
+      - '**/*.md'

Also applies to: 25-27

🧰 Tools
🪛 actionlint (1.7.4)

14-14: unexpected key "ignore" for "push" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows"

(syntax-check)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants