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

feat(GPX-698): Refactor and cleanup #71

Merged
merged 113 commits into from
Oct 4, 2023
Merged

feat(GPX-698): Refactor and cleanup #71

merged 113 commits into from
Oct 4, 2023

Conversation

Lucostus
Copy link
Collaborator

@Lucostus Lucostus commented Aug 11, 2023

  • Logger Changes: Replaces zap logging with zerolog.
  • Router Change: Now using gorilla/mux to distinguish between Prometheus/Loki URLs
  • File: .github/workflows/release.yml
    • Name Change: Publish new release to CI
    • Job Renames: golangci to lint, scan-code to scan, build-and-test split into test and build
    • Go Version: Updated from 1.20 to 1.21
    • Action Versions: actions/checkout and actions/setup-go upgraded
    • Scheduling: Removed cron scheduling
    • Tagging: switched autotag to anothrNick/github-tag-action
    • Docker meta: Tagging rules updated
    • Release Process: Changes in how releases are created
  • File: auth.go
    • OAuth Token: Changed from KeycloakToken to OAuthToken
    • Token Retrieval: Functions getToken and trimBearerToken for token parsing
    • JWT Parsing: Function parseJwtToken to handle JWT tokens
    • Label Validation: validateLabels validates user labels
    • Admin Check: isAdmin checks if user is an admin
  • File: build/Containerfile
    • Base Image: Switch from ubi9/ubi-minimal to scratch.
    • CA Image: alpine:latest for CA certificates.
  • File: config.go
    • Struct: Updated names and added fields: logging, web, admin, dev, DB, Thanos, Loki.
    • WithConfig Method: Reads YAML, sets logging, watches config changes
    • WithSAT Method: K8s service account token, dev mode option
    • WithTLSConfig Method: TLS setup for HTTP client, CA and mTLS
    • WithJWKS Method: JWKS for JWT auth, refresh options
  • File: configs/config.yaml
    • log.level: DEBUG -> 1
    • tenant_provider: Removed
    • web:
      • insecure_skip_verify -> tls_verify_skip
      • Added label_store_kind, service_account_token, oauth_group_name
      • Updated jwks_cert_url
    • admin: No change
    • db: Added token_key
    • thanos: Added Header
    • loki: Added Header
    • Purpose: Tweaks in logging, web, dev, db, loki settings; Adds/removes keys
  • File: configs/labels.yaml
    • Removed:
      • groups
      • users
    • Added:
      • group1: #cluster-wide flag
      • user1: hogarama namespace
      • user3: grafana, opernshift-logging, opernshift-monitoring namespaces
    • Purpose: Redefined user and group label configs, added new settings for cluster-wide and specific namespaces.
  • File: enforce.go
    • EnforceQL Interface: Method Enforce for query enforcement
    • enforceRequest Function: Delegates HTTP request based on method
    • enforceGet Function: Enforces GET request, modifies URL query
    • enforcePost Function: Enforces POST request, modifies form data
    • Purpose: HTTP request enforcement based on tenant labels, query matching. Handles both GET and POST methods.
  • File: enforcer_logql.go
    • LogQLEnforcer Struct: New struct for EnforceQL interface.
    • Enforce Method: Modified, returns tenant-isolated query
    • matchNamespaceMatchers Function: Ensures query matchers adhere to tenant labels.
  • File: enforcer_promql.go
    • Struct Added: PromQLEnforcer for enforcing PromQL queries via EnforceQL interface.
    • Method Changes:
      • promqlEnforcer -> PromQLEnforcer.Enforce
      • enforceLabels, checkLabels and createEnforcer take an additional labelMatch parameter.
    • Purpose: Improves structure, logging, and modularity. Adds flexibility for label matching.
  • File: go.mod
    • Dependencies Added:
      • github.com/gorilla/mux v1.8.0
      • github.com/rs/zerolog v1.30.0
      • github.com/mattn/go-colorable v0.1.13
      • github.com/mattn/go-isatty v0.0.19
    • Dependencies Updated:
      • Multiple github.com/go-openapi/* packages
      • github.com/prometheus/alertmanager to v0.26.0
      • go.mongodb.org/mongo-driver to v1.12.0
    • Dependencies Removed:
      • go.uber.org/zap v1.24.0
    • Replace Directive:
      • github.com/prometheus/prometheus to v0.46.0
    • Purpose: Adds new libraries, updates existing ones for feature enhancements or bug fixes.
  • File: init.go
    • Note: File deleted
  • File: labeler.go
    • Note: File deleted
  • File: labelstore.go
    • New File: Manages label storage
    • Interfaces:
      • Labelstore: Defines Connect, GetLabels
    • Functions:
      • WithLabelStore(): Connects LabelStore to App
      • ConfigMapHandler.Connect(): Reads labels from YAML
      • ConfigMapHandler.GetLabels(): Merges labels
      • MySQLHandler.Connect(): Connects to MySQL
      • MySQLHandler.Close(): Closes DB connection
      • MySQLHandler.GetLabels(): Queries DB for labels
    • Error Handling: Logs fatal errors
    • Note: Supports multiple label store kinds (ConfigMap, MySQL)
  • File: labelstore_test.go (Renamed from labeler_test.go)
    • Test Updates: Tests for ConfigMapHandler.GetLabels
    • Config Changes:
      • Removed setupTestLabeler() and teardown()
      • Moved hard-coded labels into ConfigMapHandler instance
    • Test Cases:
      • Tests for different user-group combinations
      • Introduced "admin_group" test with skip flag
    • Assertions:
      • Checks expected labels and skip flag
    • Tests:
      • User and groups,
      • User only,
      • User with one group,
      • User with non-matching group,
      • Admin group with skip flag.
  • File: log.go
    • New File: Introduces logging functionalities.
    • Data Struct: requestData for HTTP request details.
    • Middleware: loggingMiddleware for HTTP request logging.
      • LogTokens: Configurable to log/redact request body.
    • Helper Functions:
      • readBody: Reads HTTP request body.
      • logRequestData: Logs HTTP request details.
      • cleanSensitiveHeaders: Removes sensitive headers.
      • logAndWriteError: Logs and writes errors.
    • Logging Libraries: Uses github.com/rs/zerolog/log.
    • Security: Conditional redaction of sensitive info.
    • Error Handling: In readBody and logRequestData.
  • File: main.go
    • Structural Change: Introduced App struct, removed global Logger
    • Logging: Switched from zap to zerolog
    • Initialization: New approach using App methods (WithConfig, WithSAT, etc.)
    • Server: Removed old main(), healthz, reverseProxy. Introduced StartServer in App struct.
    • Metrics: Re-configured using slok/go-http-metrics
  • File: main_test.go
    • Changes:
      • setupTestMain() returns App and tokens
      • App and ConfigMapHandler introduced
      • Token-related test cases updated
      • Additional test cases for Loki
    • Tests:
      • Headers, tokens, authorization
      • Tenant access
      • Loki query support
    • Cleanup:
      • Removed commented-out defer
      • Formatting and naming consistency
  • File: routes.go
    • Plugin header: Removed x-pluging-id routing.
    • Struct: Route struct with Url and MatchWord.
    • WithHealthz: Adds health check and metrics routes (/healthz, /metrics, /debug/pprof/).
    • WithRoutes: Initializes new router, uses logging middleware, adds Loki and Thanos routes.
    • WithLoki: Adds Loki API routes, warns if Loki URL not set (skips).
    • WithThanos: Adds Thanos API routes, warns if Thanos URL not set (skips).
    • handler: Orchestrates proxy behavior, performs OAuth token validation, conditional enforcement, and forwards requests.
    • streamUp: Forwards request to upstream server using a reverse proxy.
    • setHeader: Sets HTTP headers, optionally includes authorization.
    • Logging: Uses zerolog for logging activities and errors.
    • Configurations: Reads settings like URLs, headers, and TLS flags from a.Cfg.
    • Error Handling: Various functions handle errors by logging and responding with appropriate HTTP statuses.
  • File: structs.go
    • Deleted: File removed
  • File: util.go
    • Removed Functions: ContainsIgnoreCase, MapKeysToArray, teardown
    • Functionality: String comparison, map key extraction, teardown initConfig removed
    • Changes: Code simplification, possibly moved functions
  • File: README.md
    • Updated: Updated with new instructions for building and running the proxy.

added file with configuration for different routes
tenant field will be used to apply the X-Scope-OrgID in query frontend mode
Test cases in `main_test.go` were updated to better reflect the expected error messages when incorrect or missing authorization headers are found. The expected body of the response is now more precise, covering a variety of error scenarios like missing headers, invalid or malformed headers, and errors parsing Keycloak tokens. This brings more accuracy to the test cases.

In addition, redundant authorization functions `TestHasAuthorizationHeader` and `TestGetBearerToken` were removed as they were not properly encapsulating the logic of the main app. The `TestIsAdminSkip` function was also refactored for better naming, as it is checking if a user is an admin, not if an admin should be skipped.
This refactor changes how `request.go` handles requests, authentication, and logging. Instead of individually parsing authorization headers for each route, we've added authentication middleware that parses the bearer token, verifies if it is valid, and adds the parsed Keycloak token to the request context for easy access in the route handlers.

The refactor also simplifies route definitions by replacing the dedicated enforcer function and upstream URL fields in the Route struct with a generic datasource field. We determine the proper function and upstream URL based on the provided datasource at the beginning of the `handleRoute` function.

Finally, a logging middleware was introduced before the route handlers to log the incoming HTTP request, its header, method, URL, and body. The logging output is redacted when a configuration flag is set.

These changes will make the codebase easier to maintain and enhance debugging by improving logging.
Modified the initialization code to improve logger and configuration error-handling, providing more informative panic logs. Enhanced flexibility by enabling the choice of tenant providers - either "configmap" or "mysql". The logging system now responds to configuration changes by updating the logging level dynamically for better log control.
Adjusted 'GetLabelsCM' and 'GetLabelsDB' functions in labeler.go to take value of type KeycloakToken instead of distinct username and email parameters.
The request.go file was deleted as part of a code restructuring effort to separate concerns. All route handlers were moved to a separate file for better code readability and simplify future development.
Removed unused package imports and handlers including promhttp handler, pprof Index handler, and HealthCheckHandler because they were not needed anymore. Also re-arranged the http server initialization process.
Refactor the `handleRoute` function in the handler.go file to remove the `thanosUrl` and `lokiUrl` parameters and to retrieve the datasource and Keycloak token from the request context instead.
This commit modifies the 'routes.go' file to substantially improve how routes are assigned and configured by creating separate handlers for Loki and Thanos API endpoints. Alongside this, the Datasource struct has been introduced to encapsulate all necessary information per data source allowing us to handle route via EnforeceFunc. The changes also consist of the implementation of 'UseMutualTLS' in the struct to increase security measures when communicating with upstream servers.
…arious files

Updated comment blocks and function signatures across several files to improve clarity and readability. This includes more detailed descriptions for each function, giving a clearer explanation of their purpose and behavior. Changes were made in the following files:
- enforcer_promql.go
- routes.go
- init.go
- handler.go
- main.go
- enforcer_logql.go
- log.go
- labeler.go
- authorization.go
- enforce.go
…ibility

This patch updates the proxy routing and authorization logic to clarify its purpose and make it more extensible. The "KeycloakToken" has been renamed to "OAuthToken" to make its use for general OAuth strategy clear. URL parsing error handling has been moved nearer to its invocation site for better error clarity and has been standardized across functions. Unnecessarily re-parsed URLs for Loki and Thanos have been replaced by earlier parsed URL, simplifying the logic and eliminating redundancy. Also, the imported useless library "golang.org/x/exp/maps" has been removed to clean up the dependencies. In authorization logic, more specific error messages are now returned for better diagnostics during debugging. Additionally, header assignment has been modified to depend on the request method, making it more dynamic.
Code refactoring was carried out to improve clarity and good practices. KeycloakToken was renamed to OAuthToken making it generic. Unnecessary URL parsing was reduced by reusing earlier parsed URL, which simplifies the logic and reduces redundancy. Error messages were made more specific for better debug information. Additional changes include: removing an unused library for cleaner dependencies, moving error handling to the site of the error triggering for clearer code flow, and updating header assignment to be dynamic based on the request method.
Refactored the multena-proxy code to improve its readability and maintainability. A large chunk of App and Config structs, previously part of types.go and main.go, were moved into a new file named config.go. The aim of the refactoring is to have a cleaner separation of the configuration handling from the main business logic. This further allows easier debuggability and can enhance the productivity of the developers, by providing a clear understanding and better navigation of the codebase.
Refactoring of the application included elaborating comment blocks for better understanding the functionality of methods and types, rearranging import statements according to best practices, and division of code in files based on functionality. This change makes the code more readable, maintainable and debuggable while ensuring better code standards. Further, unnecessary / redundant code pieces were removed from a few test files.
The key name 'preferredUsername' in tokenMap has been renamed to 'username' for consistent naming throughout the codebase. In addition to this, 'email' has been set up as the 'token_key' in the MySQL query string, enabling more targeted user searches.
…nd architecture diagrams

Made several modifications to Multena Proxy's README.md, "config.yaml" and "labels.yaml" files to improve the clarity of existing instructions and provide more detailed explanation of the system. Changes include adjustments to the architecture diagram in the 'How does it work?' section, modifications to the 'request processing flow', and updates to the example 'labels.yaml' and 'config.yaml' files. These changes were necessary to improve the readability of the documentation, and keep them in line with the latest version of the software after recent updates to its functionality.
…nstructions

Updated the installation and configuration instructions in README.MD of Multena Proxy to provide more detailed and organized steps for the user. This revision includes new sections on how to install and upgrade Multena using Helm, how to choose a Labelstore provider between ConfigMap and MySQL, and explains each section in the `config.yaml` file. This is to help users understand and navigate through the proxy setup process more efficiently.
build/Containerfile Fixed Show fixed Hide fixed
build/Containerfile Fixed Show fixed Hide fixed
build/Containerfile Fixed Show fixed Hide fixed
@Lucostus Lucostus self-assigned this Oct 3, 2023
Copy link
Contributor

@fhochleitner fhochleitner left a comment

Choose a reason for hiding this comment

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

Hab ein paar Kleinigkeiten angefügt. 100% hab ich es jetzt nicht nachverfolgt, vor allem, weil mir auch ein bisschen der deep-dive fehlt, wie das Enforcing und Matching tatsächlich abläuft.

Aber grundsätzlich schauts ganz gut aus.

build/Containerfile Show resolved Hide resolved
configs/config.yaml Outdated Show resolved Hide resolved
main.go Show resolved Hide resolved
build/Containerfile Dismissed Show dismissed Hide dismissed
build/Containerfile Dismissed Show dismissed Hide dismissed
@Lucostus Lucostus merged commit b7cab8b into main Oct 4, 2023
7 checks passed
@Lucostus Lucostus deleted the feature/GPX-698-rewrite branch October 4, 2023 09:35
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