feat!: Go rewrite (#9)

* Go rewrite

* chore(cr): apply suggestions

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>

* 📝 CodeRabbit Chat: Add NoOpClient to fail2ban and initialize when skip flag is true

* 📝 CodeRabbit Chat: Fix malformed if-else structure and add no-op client for skip-only commands

* 📝 CodeRabbit Chat: Fix malformed if-else structure and add no-op client for skip-only commands

* fix(main): correct no-op branch syntax (#10)

* chore(gitignore): ignore env and binary files (#11)

* chore(config): remove indent_size for go files (#12)

* feat(cli): inject version via ldflags (#13)

* fix(security): validate filter parameter to prevent path traversal (#15)

* chore(repo): anchor ignore for build artifacts (#16)

* chore(ci): use golangci-lint action (#17)

* feat(fail2ban): expose GetLogDir (#19)

* test(cmd): improve IP mock validation (#20)

* chore(ci): update golanglint

* fix(ci): golanglint

* fix(ci): correct args indentation in pr-lint workflow (#21)

* fix(ci): avoid duplicate releases (#22)

* refactor(fail2ban): remove test check from OSRunner (#23)

* refactor(fail2ban): make log and filter dirs configurable (#24)

* fix(ci): create single release per tag (#14)

Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>

* chore(dev): add codex setup script (#27)

* chore(lint): enable staticcheck (#26)

* chore(ci): verify golangci config (#28)

* refactor(cmd): centralize env config (#29)

* chore(dev): add pre-commit config (#30)

* fix(ci): disable cgo in cross compile (#31)

* fix(ci): fail on formatting issues (#32)

* feat(cmd): add context to logs watch (#33)

* chore: fixes, roadmap, claude.md, linting

* chore: fixes, linting

* fix(ci): gh actions update, fixes and tweaks

* chore: use reviewdog actionlint

* chore: use wow-rp-addons/actions-editorconfig-check

* chore: combine agent instructions, add comments, fixes

* chore: linting, fixes, go revive

* chore(deps): update pre-commit hooks

* chore: bump go to 1.21, pin workflows

* fix: install tools in lint.yml

* fix: sudo timeout

* fix: service command injection

* fix: memory exhaustion with large logs

* fix: enhanced path traversal and file security vulns

* fix: race conditions

* fix: context support

* chore: simplify fail2ban/ code

* feat: major refactoring with GoReleaser integration and code consolidation

- Add GoReleaser configuration for automated multi-platform releases
  - Support for Linux, macOS, Windows, and BSD builds
  - Docker images, Homebrew tap, and Linux packages (.deb, .rpm, .apk)
  - GitHub Actions workflow for release automation

- Consolidate duplicate code and improve architecture
  - Extract common command helpers to cmd/helpers.go (~230 lines)
  - Remove duplicate MockClient implementation from tests (~250 lines)
  - Create context wrapper helpers in fail2ban/context_helpers.go
  - Standardize error messages in fail2ban/errors.go

- Enhance validation and security
  - Add proper IP address validation with fail2ban.ValidateIP
  - Fix path traversal and command injection vulnerabilities
  - Improve thread-safety in MockClient with consistent ordering

- Optimize documentation
  - Reduce CLAUDE.md from 190 to 81 lines (57% reduction)
  - Reduce TODO.md from 633 to 93 lines (85% reduction)
  - Move README.md to root directory with installation instructions

- Improve test reliability
  - Fix race conditions and test flakiness
  - Add sorting to ensure deterministic test output
  - Enhance MockClient with configurable behavior

* feat: comprehensive code quality improvements and documentation reorganization

This commit represents a major overhaul of code quality, documentation
structure, and development tooling:

**Documentation & Structure:**

- Move CODE_OF_CONDUCT.md from .github to root directory
- Reorganize documentation with dedicated docs/ directory
- Create comprehensive architecture, security, and testing documentation
- Update all references and cross-links for new documentation structure

**Code Quality & Linting:**

- Add 120-character line length limit across all files via EditorConfig
- Enable comprehensive linting with golines, lll, usetesting, gosec, and revive
- Fix all 86 revive linter issues (unused parameters, missing export comments)
- Resolve security issues (file permissions 0644 → 0600, gosec warnings)
- Replace deprecated os.Setenv with t.Setenv in all tests
- Configure golangci-lint with auto-fix capabilities and formatter integration

**Development Tooling:**

- Enhance pre-commit configuration with additional hooks and formatters
- Update GoReleaser configuration with improved YAML formatting
- Improve GitHub workflows and issue templates for CLI-specific context
- Add comprehensive Makefile with proper dependency checking

**Testing & Security:**

- Standardize mock patterns and context wrapper implementations
- Enhance error handling with centralized error constants
- Improve concurrent access testing for thread safety

* perf: implement major performance optimizations with comprehensive test coverage

This commit introduces three significant performance improvements along with
complete linting compliance and robust test coverage:

**Performance Optimizations:**
1. **Time Parsing Cache (8.6x improvement)**
    - Add TimeParsingCache with sync.Map for caching parsed times
    - Implement object pooling for string builders to reduce allocations
    - Create optimized BanRecordParser with pooled string slices

2. **Gzip Detection Consolidation (55x improvement)**
    - Consolidate ~100 lines of duplicate gzip detection logic
    - Fast-path extension checking before magic byte detection
    - Unified GzipDetector with comprehensive file handling utilities

3. **Parallel Processing (2.5-5.0x improvement)**
    - Generic WorkerPool implementation for concurrent operations
    - Smart fallback to sequential processing for single operations
    - Context-aware cancellation support for long-running tasks
    - Applied to ban/unban operations across multiple jails

**New Files Added:**
- fail2ban/time_parser.go: Cached time parsing with global instances
- fail2ban/ban_record_parser.go: Optimized ban record parsing
- fail2ban/gzip_detection.go: Unified gzip handling utilities
- fail2ban/parallel_processing.go: Generic parallel processing framework
- cmd/parallel_operations.go: Command-level parallel operation support

**Code Quality & Linting:**
- Resolve all golangci-lint issues (0 remaining)
- Add proper #nosec annotations for legitimate file operations
- Implement sentinel errors replacing nil/nil anti-pattern
- Fix context parameter handling and error checking

**Comprehensive Test Coverage:**
- 500+ lines of new tests with benchmarks validating all improvements
- Concurrent access testing for thread safety
- Edge case handling and error condition testing
- Performance benchmarks demonstrating measured improvements

**Modified Files:**
- fail2ban/fail2ban.go: Integration with new optimized parsers
- fail2ban/logs.go: Use consolidated gzip detection (-91 lines)
- cmd/ban.go & cmd/unban.go: Add conditional parallel processing

* test: comprehensive test infrastructure overhaul with real test data

Major improvements to test code quality and organization:

• Added comprehensive test data infrastructure with 6 anonymized log files
• Extracted common test helpers reducing ~200 lines to ~50 reusable functions
• Enhanced ban record parser tests with real production log patterns
• Improved gzip detection tests with actual compressed test data
• Added integration tests for full log processing and concurrent operations
• Updated .gitignore to allow testdata log files while excluding others
• Updated TODO.md to reflect completed test infrastructure improvements

* fix: comprehensive security hardening and critical bug fixes

Security Enhancements:
- Add command injection protection with allowlist validation for all external
  commands
- Add security documentation to gzip functions warning about path traversal risks
- Complete TODO.md security audit - all critical vulnerabilities addressed

Bug Fixes:
- Fix negative index access vulnerability in parallel operations (prevent panic)
- Fix parsing inconsistency between BannedIn and BannedInWithContext functions
- Fix nil error handling in concurrent log reading tests
- Fix benchmark error simulation to measure actual performance vs error paths

Implementation Details:
- Add ValidateCommand() with allowlist for fail2ban-client, fail2ban-regex,
  service, systemctl, sudo
- Integrate command validation into all OSRunner methods before execution
- Replace manual string parsing with ParseBracketedList() for consistency
- Add bounds checking (index >= 0) to prevent negative array access
- Replace nil error with descriptive error message in concurrent error channels
- Update banFunc in benchmark to return success instead of permanent errors

Test Coverage:
- Add comprehensive security validation tests with injection attempt patterns
- Add parallel operations safety tests with index validation
- Add parsing consistency tests between context/non-context functions
- Add error handling demonstration tests for concurrent operations
- Add gzip function security requirement documentation tests

* perf: implement ultra-optimized log and ban record parsing with significant performance gains

Major performance improvements to core fail2ban processing with
 comprehensive benchmarking:

Performance Achievements:
• Ban record parsing: 15% faster, 39% less memory, 45% fewer allocations
• Log processing: 27% faster, 64% less memory, 32% fewer allocations
• Cache performance: 624x faster cache hits with zero allocations
• String pooling: 4.7x improvement with zero memory allocations

Core Optimizations:
• Object pooling (sync.Pool) for string slices, scanner buffers, and line buffers
• Comprehensive caching (sync.Map) for gzip detection, file info, and path patterns
• Fast path optimizations with extension-based gzip detection
• Byte-level operations to reduce string allocations in filtering
• Ultra-optimized parsers with smart field parsing and efficient time handling

New Files:
• fail2ban/ban_record_parser_optimized.go - High-performance ban record parser
• fail2ban/log_performance_optimized.go - Ultra-optimized log processor with caching
• fail2ban/ban_record_parser_benchmark_test.go - Ban record parsing benchmarks
• fail2ban/log_performance_benchmark_test.go - Log performance benchmarks
• fail2ban/ban_record_parser_compatibility_test.go - Compatibility verification tests

Updated:
• fail2ban/fail2ban.go - Integration with ultra-optimized parsers
• TODO.md - Marked performance optimization tasks as completed

* fix(ci): install dev dependencies for pre-commit

* refactor: streamline pre-commit config and extract test helpers

- Replace local hooks with upstream pre-commit repositories for better maintainability
- Add new hooks: shellcheck, shfmt, checkov for enhanced code quality
- Extract common test helpers into dedicated test_helpers.go to reduce duplication
- Add warning logs for unreadable log files in fail2ban and logs packages
- Remove hard-coded GID checks in sudo.go for better cross-platform portability
- Update golangci-lint installation method in Makefile

* fix(security): path traversal, log file validation

* feat: complete pre-release modernization with comprehensive testing

- Remove all deprecated legacy functions and dead code paths
- Add security hardening with sanitized error messages
- Implement comprehensive performance benchmarks and security audit tests
- Mark all pre-release modernization tasks as completed (10/10)
- Update project documentation to reflect full completion status

* fix(ci): linting, and update gosec install source

* feat: implement comprehensive test framework with 60-70% code reduction

Major test infrastructure modernization:

- Create fluent CommandTestBuilder framework for streamlined test creation
- Add MockClientBuilder pattern for advanced mock configuration
- Standardize table test field naming (expectedOut→wantOutput, expectError→wantError)
- Consolidate test code: 3,796 insertions, 3,104 deletions (net +692 lines with enhanced functionality)

Framework achievements:
- 168+ tests passing with zero regressions
- 5 cmd test files fully migrated to new framework
- 63 field name standardizations applied
- Advanced mock patterns with fluent interface

File organization improvements:
- Rename all test files with consistent prefixes (cmd_*, fail2ban_*, main_*)
- Split monolithic test files into focused, maintainable modules
- Eliminate cmd_test.go (622 lines) and main_test.go (825 lines)
- Create specialized test files for better organization

Documentation enhancements:
- Update docs/testing.md with complete framework documentation
- Optimize TODO.md from 231→72 lines (69% token reduction)
- Add comprehensive migration guides and best practices

Test framework components:
- command_test_framework.go: Core fluent interface implementation
- MockClientBuilder: Advanced mock configuration with builder pattern
- table_test_standards.go: Standardized field naming conventions
- Enhanced test helpers with error checking consolidation

* chore: fixes, .go-version, linting

* fix(ci) editorconfig in .pre-commit-config.yaml

* fix: too broad gitignore

* chore: update fail2ban/fail2ban_path_security_test.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>

* chore: code review fixes

* chore: code review fixes

* fix: more code review fixes

* fix: more code review fixes

* feat: cleanup, fixes, testing

* chore: minor config file updates

- Add quotes to F2B_TIMEOUT value in .env.example for clarity
- Remove testdata log exception from .gitignore (simplified)

* feat: implement comprehensive monitoring with structured logging and metrics

- Add structured logging with context propagation throughout codebase
  - Implement ContextualLogger with request tracking and operation timing
  - Add context values for operation, IP, jail, command, and request ID
  - Integrate with existing logrus logging infrastructure

- Add request/response timing metrics collection
  - Create comprehensive Metrics system with atomic counters
  - Track command executions, ban/unban operations, and client operations
  - Implement latency distribution buckets for performance analysis
  - Add validation cache hit/miss tracking

- Enhance ban/unban commands with structured logging
  - Add LogOperation wrapper for automatic timing and context
  - Log individual jail operations with success/failure status
  - Integrate metrics recording with ban/unban operations

- Add new 'metrics' command to expose collected metrics
  - Support both plain text and JSON output formats
  - Display system metrics (uptime, memory, goroutines)
  - Show operation counts, failures, and average latencies
  - Include latency distribution histograms

- Update test infrastructure
  - Add tests for metrics command
  - Fix test helper to support persistent flags
  - Ensure all tests pass with new logging

This completes the high-priority performance monitoring and structured
logging requirements from TODO.md, providing comprehensive operational
visibility into the f2b application.

* docs: update TODO.md to reflect completed monitoring work

- Mark structured logging and timing metrics as completed
- Update test coverage stats (cmd/ improved from 66.4% to 76.8%)
- Add completed infrastructure section for today's work
- Update current status date and add monitoring to health indicators

* feat: complete TODO.md technical debt cleanup

Complete all remaining TODO.md tasks with comprehensive implementation:

## 🎯 Validation Caching Implementation
- Thread-safe validation cache with sync.RWMutex protection
- MetricsRecorder interface to avoid circular dependencies
- Cached validation for IP, jail, filter, and command validation
- Integration with existing metrics system for cache hit/miss tracking
- 100% test coverage for caching functionality

## 🔧 Constants Extraction
- Fail2Ban status codes: Fail2BanStatusSuccess, Fail2BanStatusAlreadyProcessed
- Command constants: Fail2BanClientCommand, Fail2BanRegexCommand, Fail2BanServerCommand
- File permissions: DefaultFilePermissions (0600), DefaultDirectoryPermissions (0750)
- Timeout limits: MaxCommandTimeout, MaxFileTimeout, MaxParallelTimeout
- Updated all references throughout codebase to use named constants

## 📊 Test Coverage Improvement
- Increased fail2ban package coverage from 62.0% to 70.3% (target: 70%+)
- Added 6 new comprehensive test files with 200+ additional test cases
- Coverage improvements across all major components:
  - Context helpers, validation cache, mock clients, OS runner methods
  - Error constructors, timing operations, cache statistics
  - Thread safety and concurrency testing

## 🛠️ Code Quality & Fixes
- Fixed all linting issues (golangci-lint, revive, errcheck)
- Resolved unused parameter warnings and error handling
- Fixed timing-dependent test failures in worker pool cancellation
- Enhanced thread safety in validation caching

## 📈 Final Metrics
- Overall test coverage: 72.4% (up from ~65%)
- fail2ban package: 70.3% (exceeds 70% target)
- cmd package: 76.9%
- Zero TODO/FIXME/HACK comments in production code
- 100% linting compliance

* fix: resolve test framework issues and update documentation

- Remove unnecessary defer/recover block in comprehensive_framework_test.go
- Fix compilation error in command_test_framework.go variable redeclaration
- Update TODO.md to reflect all 12 completed code quality fixes
- Clean up dead code and improve test maintainability
- Fix linting issues: error handling, code complexity, security warnings
- Break down complex test function to reduce cyclomatic complexity

* fix: replace dangerous test commands with safe placeholders

Replaces actual dangerous commands in test cases with safe placeholder patterns to prevent accidental execution while maintaining comprehensive security testing.

- Replace 'rm -rf /', 'cat /etc/passwd' with 'DANGEROUS_RM_COMMAND', 'DANGEROUS_SYSTEM_CALL'
- Update GetDangerousCommandPatterns() to recognize both old and new patterns
- Enhance filter validation with command injection protection (semicolons, pipes, backticks, dollar signs)
- Add package documentation comments for all packages (main, cmd, fail2ban)
- Fix GoReleaser static linking configuration for cross-platform builds
- Remove Docker platform restriction to enable multi-arch support
- Apply code formatting and linting fixes

All security validation tests continue to pass with the safe placeholders.

* fix: resolve TestMixedConcurrentOperations race condition and command key mismatches

The concurrency test was failing due to several issues:

1. **Command Key Mismatch**: Test setup used "sudo test arg" key but MockRunner
   looked for "test arg" because "test" command doesn't require sudo
2. **Invalid Commands**: Using "test" and "echo" commands that aren't in the
   fail2ban command allowlist, causing validation failures
3. **Race Conditions**: Multiple goroutines setting different MockRunners
   simultaneously, overwriting responses

**Solution:**
- Replace invalid test commands ("test", "echo") with valid fail2ban commands
  ("fail2ban-client status", "fail2ban-client -V")
- Pre-configure shared MockRunner with all required response keys for both
  sudo and non-sudo execution paths
- Improve test structure to reduce race conditions between setup and execution

All tests now pass reliably, resolving the CI failure.

* fix: address code quality issues and improve test coverage

- Replace unsafe type assertion with comma-ok idiom in logging
- Fix TestTestFilter to use created filter instead of nonexistent
- Add warning logs for invalid log level configurations
- Update TestVersionCommand to use consistent test framework pattern
- Remove unused LoggerContextKey constant
- Add version command support to test framework
- Fix trailing whitespace in test files

* feat: add timeout handling and multi-architecture Docker support

* test: enhance path traversal security test coverage

* chore: comprehensive documentation update and linting fixes

Updated all documentation to reflect current capabilities including context-aware operations, multi-architecture Docker support, advanced security features, and performance monitoring. Removed unused functions and fixed all linting issues.

* fix(lint): .goreleaser.yaml

* feat: add markdown link checker and fix all linting issues

- Add markdown-link-check to pre-commit hooks with comprehensive configuration
- Fix GitHub workflow structure (sync-labels.yml) with proper job setup
- Add JSON schemas to all configuration files for better IDE support
- Update tool installation in Makefile for markdown-link-check dependency
- Fix all revive linting issues (Boolean literals, defer in loop, if-else simplification, method naming)
- Resolve broken relative link in CONTRIBUTING.md
- Configure rate limiting and ignore patterns for GitHub URLs
- Enhance CLAUDE.md with link checking documentation

* fix(ci): sync-labels permissions

* docs: comprehensive documentation update reflecting current project status

- Updated TODO.md to show production-ready status with 21 commands
- Enhanced README.md with enterprise-grade features and capabilities
- Added performance monitoring and timeout configuration to FAQ
- Updated CLAUDE.md with accurate project architecture overview
- Fixed all line length issues to meet EditorConfig requirements
- Added .mega-linter.yml configuration for enhanced linting

* fix: address CodeRabbitAI review feedback

- Split .goreleaser.yaml builds for static/dynamic linking by architecture
- Update docs to accurately reflect 7 path traversal patterns (not 17)
- Fix containsPathTraversal to allow valid absolute paths
- Replace runnerCombinedRunWithSudoContext with RunnerCombinedOutputWithSudoContext
- Fix ldflags to use uppercase Version variable name
- Remove duplicate test coverage metrics in TODO.md
- Fix .markdown-link-check.json schema violations
- Add v8r JSON validator to pre-commit hooks

* chore(ci): update workflows, switch v8r to check-jsonschema

* fix: restrict static linking to amd64 only in .goreleaser.yaml

- Move arm64 from static to dynamic build configuration
- Static linking now only applies to linux/amd64
- Prevents build failures due to missing static libc on ARM64
- All architectures remain supported with appropriate linking

* fix(ci): caching

* fix(ci): python caching with pip, node with npm

* fix(ci): no caching for node then

* fix(ci): no requirements.txt, no cache

* refactor: address code review feedback

- Pin Alpine base image to v3.20 for reproducible builds
- Remove redundant --platform flags in GoReleaser Docker configs
- Fix unused parameters in concurrency test goroutines
- Simplify string search helper using strings.Contains()
- Remove redundant error checking logic in security tests

---------

Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
2025-08-07 01:49:45 +03:00
committed by GitHub
parent f98e049eee
commit 70d1cb70fd
140 changed files with 29940 additions and 1262 deletions

View File

@@ -1,93 +0,0 @@
# Citizen Code of Conduct
## 1. Purpose
A primary goal of @ivuorinen's repositories is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof).
This code of conduct outlines our expectations for all those who participate in our community, as well as the consequences for unacceptable behavior.
We invite all those who participate in @ivuorinen's repositories to help us create safe and positive experiences for everyone.
## 2. Open [Source/Culture/Tech] Citizenship
A supplemental goal of this Code of Conduct is to increase open [source/culture/tech] citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community.
Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society.
If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, we want to know.
## 3. Expected Behavior
The following behaviors are expected and requested of all community members:
* Participate in an authentic and active way. In doing so, you contribute to the health and longevity of this community.
* Exercise consideration and respect in your speech and actions.
* Attempt collaboration before conflict.
* Refrain from demeaning, discriminatory, or harassing behavior and speech.
* Be mindful of your surroundings and of your fellow participants. Alert community leaders if you notice a dangerous situation, someone in distress, or violations of this Code of Conduct, even if they seem inconsequential.
* Remember that community event venues may be shared with members of the public; please be respectful to all patrons of these locations.
## 4. Unacceptable Behavior
The following behaviors are considered harassment and are unacceptable within our community:
* Violence, threats of violence or violent language directed against another person.
* Sexist, racist, homophobic, transphobic, ableist or otherwise discriminatory jokes and language.
* Posting or displaying sexually explicit or violent material.
* Posting or threatening to post other people's personally identifying information ("doxing").
* Personal insults, particularly those related to gender, sexual orientation, race, religion, or disability.
* Inappropriate photography or recording.
* Inappropriate physical contact. You should have someone's consent before touching them.
* Unwelcome sexual attention. This includes, sexualized comments or jokes; inappropriate touching, groping, and unwelcomed sexual advances.
* Deliberate intimidation, stalking or following (online or in person).
* Advocating for, or encouraging, any of the above behavior.
* Sustained disruption of community events, including talks and presentations.
## 5. Weapons Policy
No weapons will be allowed at @ivuorinen's repositories events, community spaces, or in other spaces covered by the scope of this Code of Conduct. Weapons include but are not limited to guns, explosives (including fireworks), and large knives such as those used for hunting or display, as well as any other item used for the purpose of causing injury or harm to others. Anyone seen in possession of one of these items will be asked to leave immediately, and will only be allowed to return without the weapon. Community members are further expected to comply with all state and local laws on this matter.
## 6. Consequences of Unacceptable Behavior
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.
Anyone asked to stop unacceptable behavior is expected to comply immediately.
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).
## 7. Reporting Guidelines
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify a community organizer as soon as possible. ismo@ivuorinen.net.
Additionally, community organizers are available to help community members engage with local law enforcement or to otherwise help those experiencing unacceptable behavior feel safe. In the context of in-person events, organizers will also provide escorts as desired by the person experiencing distress.
## 8. Addressing Grievances
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify @ivuorinen with a concise description of your grievance. Your grievance will be handled in accordance with our existing governing policies.
## 9. Scope
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues--online and in-person--as well as in all one-on-one communications pertaining to community business.
This code of conduct and its related procedures also applies to unacceptable behavior occurring outside the scope of community activities when such behavior has the potential to adversely affect the safety and well-being of community members.
## 10. Contact info
@ivuorinen
ismo@ivuorinen.net
## 11. License and attribution
The Citizen Code of Conduct is distributed by [Stumptown Syndicate](http://stumptownsyndicate.org) under a [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/3.0/).
Portions of text derived from the [Django Code of Conduct](https://www.djangoproject.com/conduct/) and the [Geek Feminism Anti-Harassment Policy](http://geekfeminism.wikia.com/wiki/Conference_anti-harassment/Policy).
_Revision 2.3. Posted 6 March 2017._
_Revision 2.2. Posted 4 February 2016._
_Revision 2.1. Posted 23 June 2014._
_Revision 2.0, adopted by the [Stumptown Syndicate](http://stumptownsyndicate.org) board on 10 January 2013. Posted 17 March 2013._

View File

@@ -12,27 +12,42 @@ A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
1. Run command: `f2b [command]`
2. With arguments: `[arguments]`
3. Expected behavior: `[what should happen]`
4. Actual result: `[what actually happened]`
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Command Output**
Please include the full command output:
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
```bash
$ f2b [your command here]
[paste the complete output here]
```
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Environment (please complete the following information):**
- OS: [e.g. Ubuntu 20.04, macOS 12.6, Windows 11]
- Architecture: [e.g. amd64, arm64]
- Go version: [e.g. 1.20.5] (if building from source)
- f2b version: [e.g. 1.2.3] (run `f2b version`)
- Fail2Ban version: [e.g. 0.11.2] (run `fail2ban-client version`)
- User privileges: [e.g. root, sudo user, regular user]
**Logs**
If available, include relevant logs:
```text
# f2b debug logs (run with --log-level=debug)
[paste debug output here]
# Fail2Ban logs (if relevant)
[paste relevant fail2ban logs here]
```
**Additional context**
Add any other context about the problem here.

66
.github/README.md vendored
View File

@@ -1,66 +0,0 @@
# ivuorinen/f2b
A fail2ban wrapper for easier management and listing of banned IP's in your jails.
Requires fail2ban to be installed and running. Should work on most Linux distributions.
Developed against `fail2ban` version 0.11.2 on Ubuntu 22.04.4 LTS using nvim.
[![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit/) ![GitHub file size in bytes](https://img.shields.io/github/size/ivuorinen/f2b/f2b)
## Installation
```bash
curl https://raw.githubusercontent.com/ivuorinen/f2b/main/f2b > f2b
chmod +x f2b
./f2b version
```
Requiements: `fail2ban` (duh), and few other default tools.
`awk`, `cat`, `date`, `grep`, `ls`, `sed`, `sort`, `tail`, `tr`, `wc`, and `zcat` should be installed.
Those are usually installed by default on most Linux distributions. The script will tell you if something is missing.
If running commands straight from the internet scares you (as it should) you can
open the f2b script in your favourite editor (or here in GitHub) and view the source.
I promise I'm not doing anything weird in the script.
## Usage
It uses several fail2ban commands to get the information it needs, so it needs to be run as root.
```bash
Usage: f2b [command] [options]
list-jails List all jails
status all Show status of all jails
status [jail] Show status of a specific jail
banned Show all banned IP addresses with ban time left
banned [jail] Show all banned IP addresses with ban time left in a jail
ban [ip] Ban IP address in all jails
ban [ip] [jail] Ban IP address in a specific jail
unban [ip] Unban IP address in all jails
unban [ip] [jail] Unban IP address in a specific jail
test [ip] Test if IP address is banned
logs Show fail2ban logs
logs all [ip] Show logs for a specific IP address in all jails
logs [jail] Show logs for a specific jail
logs [jail] [ip] Show logs for a specific jail and IP address
logs-watch Watch fail2ban logs
logs-watch all [ip] Watch logs for a specific IP address
logs-watch [jail] Watch logs for a specific jail
logs-watch [jail] [ip] Watch logs for a specific jail and IP address
test-filter [filter] Test a fail2ban filter
service start Start fail2ban
service stop Stop fail2ban
service restart Restart fail2ban
help Show help
version Show version
```
## Authors
- [@ivuorinen](https://github.com/ivuorinen)
## License
[MIT](https://choosealicense.com/licenses/mit/)

27
.github/copilot-instructions.md vendored Normal file
View File

@@ -0,0 +1,27 @@
# GitHub Copilot Instructions
## Primary Guidelines
**Follow all rules and guidelines in [AGENTS.md](../AGENTS.md)** - this is the authoritative source for all AI agents
working on this project.
## Quick Reference
- **Security**: Never execute real sudo commands in tests, always use MockRunner
- **Testing**: Use `F2B_TEST_SUDO=true` and mock all system interactions
- **Format**: Run `go fmt ./...` and `golangci-lint run` before suggesting changes
- **Commits**: Use semantic commit format: `type(scope): message`
- **Validation**: Validate all input before privilege escalation
- **Testing**: Include both privileged and unprivileged test scenarios
## Project Context
f2b is a security-focused Go CLI for managing Fail2Ban. All code suggestions must prioritize security, testability,
and maintainability.
## Documentation References
- [AGENTS.md](../AGENTS.md) - Complete AI/LLM contributor guidelines
- [docs/security.md](../docs/security.md) - Security practices and threat model
- [docs/testing.md](../docs/testing.md) - Testing strategies and mock patterns
- [docs/architecture.md](../docs/architecture.md) - System architecture and design

View File

@@ -1,3 +1,4 @@
---
name: Claude Code
on:
@@ -45,7 +46,7 @@ jobs:
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 1

49
.github/workflows/lint.yml vendored Normal file
View File

@@ -0,0 +1,49 @@
---
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Lint
on:
push:
branches: [master, main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions: read-all
jobs:
lint:
name: Lint Code
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24.x
- name: Set up Go
uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
with:
go-version-file: go.mod
cache: true
cache-dependency-path: go.sum
- name: Set up Python
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with:
python-version: "3.x"
- name: Install tools required by pre-commit
shell: bash
run: make dev-setup
- name: Run pre-commit
uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
with:
extra_args: --all-files

View File

@@ -21,11 +21,58 @@ jobs:
statuses: write
contents: read
packages: read
issues: write # Used by ivuorinen/actions/pr-lint
pull-requests: write # Used by ivuorinen/actions/pr-lint
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24.x
- name: Set up Go
uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
with:
go-version-file: go.mod
cache: true
cache-dependency-path: go.sum
- name: Set up Python
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with:
python-version: "3.x"
- name: Cache pre-commit
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
with:
path: ~/.cache/pre-commit
key: ${{ runner.os }}-precommit-${{ hashFiles('.pre-commit-config.yaml') }}
- name: Install pre-commit tooling
shell: bash
run: |
make dev-deps
- name: Run pre-commit
uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
with:
extra_args: --all-files
- name: Run integration tests and collect coverage
run: |
# Run all tests with coverage collection for PR analysis
go test -race -covermode=atomic -coverprofile=coverage.out ./...
- name: Upload coverage report
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: coverage-report
path: coverage.out
- name: Run PR Lint
# Custom PR linting action that performs additional PR-specific checks
# https://github.com/ivuorinen/actions
uses: ivuorinen/actions/pr-lint@86387d514e628a6b8b2c8c4f559ba3e0147204a8 # 25.8.4

View File

@@ -1,14 +0,0 @@
---
name: Release Drafter
# yamllint disable-line rule:truthy
on:
workflow_call:
permissions:
contents: write
statuses: write
jobs:
Draft:
uses: ivuorinen/ivuorinen/.github/workflows/sync-labels.yml@main

59
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,59 @@
---
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Release with GoReleaser
on:
push:
tags:
- "v*.*.*"
permissions:
contents: write
packages: write
attestations: write
id-token: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 0 # Required for changelog generation
- name: Set up Go
uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
with:
go-version-file: go.mod
cache: true
- name: Install GoReleaser
uses: goreleaser/goreleaser-action@9c156ee8a17a598857849441385a2041ef570552 # v6.3.0
with:
install-only: true
version: "~> v2"
- name: Login to GitHub Container Registry
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@9c156ee8a17a598857849441385a2041ef570552 # v6.3.0
with:
version: "~> v2"
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Optional: Token for homebrew tap if you have a separate repo
# HOMEBREW_TAP_GITHUB_TOKEN: ${{ secrets.HOMEBREW_TAP_GITHUB_TOKEN }}
- name: Upload Release Assets
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: release-artifacts
path: dist/
retention-days: 7

View File

@@ -4,7 +4,7 @@ name: Stale
on:
schedule:
- cron: '0 8 * * *' # Every day at 08:00
- cron: "0 8 * * *" # Every day at 08:00
workflow_call:
workflow_dispatch:

View File

@@ -1,7 +1,7 @@
---
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Sync labels
# yamllint disable-line rule:truthy
on:
push:
branches:
@@ -13,9 +13,12 @@ on:
workflow_call:
workflow_dispatch:
permissions:
issues: write
permissions: read-all
jobs:
SyncLabels:
uses: ivuorinen/ivuorinen/.github/workflows/sync-labels.yml@main
sync-labels:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- uses: ivuorinen/actions/sync-labels@1018ccd7fe3d4520222a558d7d5f701515c45af0 # 25.7.28