Skip to content

Conversation

cnlangzi
Copy link
Member

@cnlangzi cnlangzi commented Feb 14, 2025

Changed

Fixed

  • fix(reqlog): escap values from client

Added

  • feat(acl): added ext/acl to implement Access Control List with hosts/ipnets/countries

Tests

Tasks to complete before merging PR:

  • Ensure unit tests are passing. If not run make unit-test to check for any regressions 📋
  • Ensure lint tests are passing. if not run make lint to check for any issues
  • Ensure codecov/patch is passing for changes.

Summary by Sourcery

Implement ACL middleware to filter requests based on host, IP, or country. Add a new log format VCombined and support loading rules from a config file. Escape values from the client in request logs.

New Features:

  • Implement Access Control List (ACL) middleware with filtering by hosts, IP networks, and countries

Bug Fixes:

  • Escape values from client in request logs

Enhancements:

  • Add VCombined log format which includes virtual host
  • Add host redirection for disallowed hosts in ACL middleware
  • Load ACL rules from config files
  • Watch config files and reload ACL options automatically

Documentation:

  • Document Access Control List (ACL) middleware

Tests:

  • Add tests for the ACL middleware
  • Add tests for escaping values in request logs

Copy link

sourcery-ai bot commented Feb 14, 2025

Reviewer's Guide by Sourcery

This pull request introduces an Access Control List (ACL) middleware, enhances request logging, refactors text viewer and template initialization, updates context to use App instead of app, removes index.html suffix from static file paths, and updates CSRF middleware documentation and example code. The ACL middleware allows restricting access based on hosts, IP networks, and countries. Request logging is enhanced to include virtual host information and escape values from client logs. The text viewer and template initialization are refactored for better code organization. The context is updated to use App instead of app for consistency. The index.html suffix is removed from static file paths to improve usability. The CSRF middleware documentation and example code are updated for clarity.

Updated class diagram for TextTemplate and TextViewer

classDiagram
  class TextTemplate {
    -template *template.Template
  }
  class TextViewer {
    -template *TextTemplate
  }
  TextViewer -- TextTemplate : has
  note for TextTemplate "Represents a text template that can be loaded from a file system and executed with data."
  note for TextViewer "Holds an TextTemplate and is used to render text content."
Loading

File-Level Changes

Change Details Files
Implemented Access Control List (ACL) middleware to restrict access based on hosts, IP networks, and countries.
  • Added ext/acl directory with implementation for ACL middleware.
  • Created acl.go with the core logic for ACL middleware.
  • Implemented options for allowing/denying hosts, IP networks, and countries.
  • Added functionality to redirect requests based on host validation.
  • Implemented a lookup function to determine the country of an IP address.
  • Added configuration options for loading rules from a file.
  • Added tests for the new ACL middleware.
ext/acl/acl.go
ext/acl/acl_test.go
ext/acl/config.go
ext/acl/config_test.go
ext/acl/helper.go
ext/acl/option.go
ext/acl/watcher.go
ext/acl/acl.ini
Updated request logging to include virtual host and escape values from client logs.
  • Added support for virtual host logging in the combined log format.
  • Added Escape function to handle strings with double quotes in log output.
  • Modified the Combined and VCombined log formats to include virtual host and escaped values.
  • Updated tests to verify the new logging format.
ext/reqlog/log_test.go
ext/reqlog/format.go
Refactored text viewer and template initialization.
  • Created NewTextTemplate function to initialize TextTemplate.
  • Created NewTextViewer function to initialize TextViewer.
  • Refactored TextViewEngine to use NewTextViewer.
  • Updated tests to use NewTextTemplate.
viewengine_text.go
template_text.go
viewer_text.go
viewer_text_test.go
Updated context to use App instead of app.
  • Updated all instances of c.app to c.App in context.go.
  • Updated all instances of app.app to app.App in app.go.
  • Updated all instances of ctx.app to ctx.App in context_test.go.
context.go
app.go
context_test.go
Removed index.html suffix from static file paths.
  • Modified StaticViewEngine to remove the /index.html suffix from static file paths.
viewengine_static.go
Updated CSRF middleware documentation and example code.
  • Removed unnecessary blank lines from the CSRF middleware documentation.
  • Simplified the example code for CSRF middleware.
README.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding some unit tests for the new ext/acl package to ensure its functionality and correctness.
  • The WithConfig function in ext/acl/option.go could benefit from error handling when parsing the config file.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟡 Testing: 1 issue found
  • 🟡 Complexity: 2 issues found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

deepsource-io bot commented Feb 14, 2025

Here's the code health analysis summary for commits 4665572..a8f4f51. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource Go LogoGo✅ SuccessView Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

Copy link

codecov bot commented Feb 14, 2025

Codecov Report

Attention: Patch coverage is 98.42271% with 5 lines in your changes missing coverage. Please review.

Project coverage is 93.98%. Comparing base (4665572) to head (a8f4f51).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
context.go 20.00% 2 Missing and 2 partials ⚠️
ext/acl/watcher.go 96.96% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #48      +/-   ##
==========================================
+ Coverage   93.10%   93.98%   +0.88%     
==========================================
  Files          49       54       +5     
  Lines        1899     2196     +297     
==========================================
+ Hits         1768     2064     +296     
- Misses         97       98       +1     
  Partials       34       34              
Flag Coverage Δ
Unit-Tests 93.98% <98.42%> (+0.88%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@cnlangzi
Copy link
Member Author

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding comments to the acl package to explain the purpose and usage of its functions and types.
  • The acl package introduces a config file, so it would be helpful to provide an example config file in the documentation.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟡 Testing: 2 issues found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@cnlangzi
Copy link
Member Author

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding more comprehensive error handling, especially around IP parsing and country code lookups.
  • The ACL middleware could benefit from a mechanism to disable it entirely via a configuration option.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟡 Testing: 2 issues found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

})
}

func TestIPNets(t *testing.T) {
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Edge case tests for IPNets with invalid formats.

Add tests to handle scenarios with invalid IP network formats to ensure proper error handling.

Comment on lines +70 to +71
})
}
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Test case for countries with empty lookup function.

It would be beneficial to add a test case where the lookup function is nil or returns an empty string to ensure the middleware handles such scenarios gracefully.

Suggested change
})
}
})
t.Run("empty_lookup", func(t *testing.T) {
emptyLookup := func(ip string) string {
return ""
}
m := New(WithLookupFunc(emptyLookup), AllowCountries("cn"))
ctx := createContext(nil)
ctx.Request.RemoteAddr = "172.0.0.2:2222"
err := m(nop)(ctx)
require.Error(t, err)
require.Equal(t, http.StatusForbidden, ctx.Response.StatusCode())
})
t.Run("nil_lookup", func(t *testing.T) {
// Passing a nil lookup function to ensure the middleware handles it gracefully.
m := New(WithLookupFunc(nil), AllowCountries("cn"))
ctx := createContext(nil)
ctx.Request.RemoteAddr = "172.0.0.2:2222"
err := m(nop)(ctx)
require.Error(t, err)
require.Equal(t, http.StatusForbidden, ctx.Response.StatusCode())
})
}

README.md Outdated
@@ -698,7 +695,95 @@ func main(){
```


#### Access Control List(ACL )
Copy link

Choose a reason for hiding this comment

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

issue (typo): Typo: Remove space before parenthesis in "Access Control List(ACL )"

It should be "Access Control List (ACL)".

Suggested change
#### Access Control List(ACL )
#### Access Control List (ACL)

@cnlangzi cnlangzi merged commit f7e5bca into main Feb 15, 2025
7 checks passed
@cnlangzi cnlangzi deleted the feat/acl branch February 15, 2025 06:34
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.

1 participant