Conversation
WalkthroughIntroduces a new v3 migration (MigrateKeyAuthConfig) that converts keyauth configurations from KeyLookup/AuthScheme to Extractor expressions, registers it in the migrations list for 2.0.0 to <4.0.0-0, and adds tests covering header, cookie, chained sources, and unknown source handling. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant CLI
participant MigrationRunner
participant Filesystem
User->>CLI: run migrate (target v3 range)
CLI->>MigrationRunner: DoMigration(curr, target)
loop For each migration in v3 list
MigrationRunner->>MigrationRunner: Check From/To constraints
alt Session extractor migration
MigrationRunner->>Filesystem: Apply MigrateSessionExtractor
else Key auth config migration
MigrationRunner->>Filesystem: Apply MigrateKeyAuthConfig
Note right of Filesystem: Replace KeyLookup/AuthScheme with Extractor
end
end
MigrationRunner-->>CLI: Done
CLI-->>User: Migration complete
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~15–25 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Summary of Changes
Hello @ReneWerner87, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request introduces a new migration step to update keyauth middleware configurations. It transitions existing keyauth.Config structures from using the deprecated KeyLookup and AuthScheme fields to the new Extractor API, ensuring compatibility with updated authentication mechanisms.
Highlights
- Keyauth Configuration Update: Implemented MigrateKeyAuthConfig to automatically refactor keyauth.Config instances, replacing KeyLookup and AuthScheme with the Extractor field.
- Migration Pipeline Integration: The new keyauth migrator has been added to the main list of v3 migrations, ensuring it runs as part of the overall migration process.
- Robust Test Coverage: Comprehensive unit tests have been added to validate the keyauth migration logic across various scenarios, including different key lookup sources and chained extractors.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Code Review
This pull request introduces a migration script for keyauth configurations to adapt to the new Extractor API. The implementation correctly handles various KeyLookup and AuthScheme combinations and is accompanied by a good set of unit tests for common scenarios.
However, I've identified a potential issue with the regular expression used to locate keyauth.Config blocks. It may fail for configurations that include nested code blocks (like a Validator function), potentially leading to an incorrect migration. I've left a detailed comment on this. Addressing this would make the migration script more robust.
Overall, a good addition that will help users migrate their projects. Just this one point on robustness to consider.
| // MigrateKeyAuthConfig updates keyauth middleware configuration to use Extractor | ||
| // instead of KeyLookup/AuthScheme and removes the deprecated fields. | ||
| func MigrateKeyAuthConfig(cmd *cobra.Command, cwd string, _, _ *semver.Version) error { | ||
| reConfig := regexp.MustCompile(`keyauth\.Config{[^}]*}`) |
There was a problem hiding this comment.
The regex keyauth\.Config{[^}]*} is not robust enough to handle struct literals that contain nested blocks with braces, such as function literals (e.g., for a Validator field). The [^}]* pattern will stop at the first closing brace } it encounters, which can lead to an incomplete match and broken code after migration.
For example, this valid configuration would be migrated incorrectly:
keyauth.New(keyauth.Config{
KeyLookup: "header:X-API-Key",
Validator: func(c fiber.Ctx, key string) (bool, error) {
if key == "secret" { // This '}' would break the regex
return true, nil
}
return false, nil
},
})To fix this, you should use a more robust method to find the entire keyauth.Config struct literal. Instead of a single regex, you could find the start keyauth.Config{ and then programmatically scan for the matching closing brace, taking into account nested braces and strings, similar to the logic in the removeConfigField function.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
cmd/internal/migrations/v3/common.go (2)
1012-1014: Broaden KeyLookup matching to support raw and backtick-quoted strings (optional hardening)
reKeyLookuponly matches double-quoted literals, missing backtick-quoted values and any non-literal forms. Consider extending the pattern to support backticks for robustness. If you want to keep the current simplicity, at minimum document that only double-quoted KeyLookup values are migrated.Example pattern accommodating backticks:
- reKeyLookup := regexp.MustCompile(`(?m)(\s*)KeyLookup:\s*("[^"]+")(,?)(\n?)`) + // Supports "..." and `...` forms + reKeyLookup := regexp.MustCompile("(?m)(\\s*)KeyLookup:\\s*((?:\"(?:[^\"\\\\]|\\\\.)+\"|`[^`]+`))\\s*(,?)(\\n?)")Note: using a double-quoted Go string for the regex avoids embedding backticks inside a raw string.
1060-1064: Unknown KeyLookup source drops all sources; consider partial migration (optional)On encountering an unrecognized source, the implementation removes both AuthScheme and KeyLookup entirely, discarding any recognized sources in the list. If feasibility allows, consider skipping only the unknown entry and migrating the known ones instead to maximize safe auto-fix coverage.
cmd/internal/migrations/v3/common_test.go (3)
1303-1328: Add a test for variable-based AuthScheme to prevent regressionsCoverage is solid for literals. Add a case where AuthScheme is an identifier (e.g., const or var) to ensure it’s preserved without being turned into a string literal.
Example test to add:
func Test_MigrateKeyAuthConfig_HeaderAuth_VarScheme(t *testing.T) { t.Parallel() dir, err := os.MkdirTemp("", "mkeyauth_header_var") require.NoError(t, err) defer func() { require.NoError(t, os.RemoveAll(dir)) }() file := writeTempFile(t, dir, `package main import "github.com/gofiber/fiber/v2/middleware/keyauth" const myScheme = "Bearer" var _ = keyauth.New(keyauth.Config{ KeyLookup: "header:Authorization", AuthScheme: myScheme, })`) var buf bytes.Buffer cmd := newCmd(&buf) require.NoError(t, v3.MigrateKeyAuthConfig(cmd, dir, nil, nil)) content := readFile(t, file) assert.NotContains(t, content, "KeyLookup") assert.NotContains(t, content, "AuthScheme") assert.Contains(t, content, `Extractor: keyauth.FromAuthHeader("Authorization", myScheme)`) assert.Contains(t, buf.String(), "Migrating keyauth middleware configs") }
1352-1373: Consider adding tests for param and form sourcesYou already cover header, cookie, and chained sources. Include param: and form: to fully exercise all supported extractors.
Example:
func Test_MigrateKeyAuthConfig_ParamAndForm(t *testing.T) { t.Parallel() dir, err := os.MkdirTemp("", "mkeyauth_param_form") require.NoError(t, err) defer func() { require.NoError(t, os.RemoveAll(dir)) }() file := writeTempFile(t, dir, `package main import "github.com/gofiber/fiber/v2/middleware/keyauth" var _ = keyauth.New(keyauth.Config{ KeyLookup: "param:id,form:token", })`) var buf bytes.Buffer cmd := newCmd(&buf) require.NoError(t, v3.MigrateKeyAuthConfig(cmd, dir, nil, nil)) content := readFile(t, file) assert.NotContains(t, content, "KeyLookup") assert.Contains(t, content, `Extractor: keyauth.Chain(keyauth.FromParam("id"), keyauth.FromForm("token"))`) assert.Contains(t, buf.String(), "Migrating keyauth middleware configs") }
1330-1350: Optional: add a default-scheme test (no AuthScheme provided)To lock in the "Bearer" default behavior, add a case where AuthScheme is omitted and header:Authorization is used.
Example:
func Test_MigrateKeyAuthConfig_HeaderAuth_DefaultScheme(t *testing.T) { t.Parallel() dir, err := os.MkdirTemp("", "mkeyauth_header_default") require.NoError(t, err) defer func() { require.NoError(t, os.RemoveAll(dir)) }() file := writeTempFile(t, dir, `package main import "github.com/gofiber/fiber/v2/middleware/keyauth" var _ = keyauth.New(keyauth.Config{ KeyLookup: "header:Authorization", })`) var buf bytes.Buffer cmd := newCmd(&buf) require.NoError(t, v3.MigrateKeyAuthConfig(cmd, dir, nil, nil)) content := readFile(t, file) assert.Contains(t, content, `Extractor: keyauth.FromAuthHeader("Authorization", "Bearer")`) assert.Contains(t, buf.String(), "Migrating keyauth middleware configs") }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these settings in your CodeRabbit configuration.
📒 Files selected for processing (3)
cmd/internal/migrations/lists.go(1 hunks)cmd/internal/migrations/v3/common.go(1 hunks)cmd/internal/migrations/v3/common_test.go(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
cmd/internal/migrations/lists.go (1)
cmd/internal/migrations/v3/common.go (1)
MigrateKeyAuthConfig(1010-1090)
cmd/internal/migrations/v3/common.go (1)
cmd/internal/helpers.go (1)
ChangeFileContent(36-68)
cmd/internal/migrations/v3/common_test.go (1)
cmd/internal/migrations/v3/common.go (1)
MigrateKeyAuthConfig(1010-1090)
🔇 Additional comments (2)
cmd/internal/migrations/v3/common.go (1)
1011-1011: Config block matcher may break with nested braces; verify against complex configs
reConfig := regexp.MustCompile('keyauth.Config{[^}]*}')is a simple, non-nested matcher. If configs embed values containing braces (e.g., function literals, maps), this could under/over-match. This pattern is used elsewhere in the file too; if you’ve validated against real-world configs, fine. Otherwise, consider a brace-depth scan for resilience.cmd/internal/migrations/lists.go (1)
60-61: LGTM: keyauth migration correctly wired after session extractorPlacement after MigrateSessionExtractor is coherent and preserves the existing migration flow.
| scheme := "Bearer" | ||
| if am := reAuthScheme.FindStringSubmatch(cfg); len(am) > 1 { | ||
| scheme = strings.TrimSpace(am[1]) | ||
| if uq, err := strconv.Unquote(scheme); err == nil { | ||
| scheme = uq | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
Do not force-quote AuthScheme; preserve raw expressions to avoid breaking variable-based schemes
If AuthScheme is provided as a variable or const (not a string literal), unquoting then re-quoting with %q will turn the identifier into a literal string of its name. This changes behavior. Instead, keep the raw matched expression (quoted or not) and only default to a quoted "Bearer" when missing.
Apply this diff to preserve AuthScheme expressions and fix the FromAuthHeader call:
- scheme := "Bearer"
- if am := reAuthScheme.FindStringSubmatch(cfg); len(am) > 1 {
- scheme = strings.TrimSpace(am[1])
- if uq, err := strconv.Unquote(scheme); err == nil {
- scheme = uq
- }
- }
+ // Preserve raw AuthScheme expression if present (supports literals and identifiers).
+ // Default to a quoted "Bearer" when not provided.
+ schemeArg := strconv.Quote("Bearer")
+ if am := reAuthScheme.FindStringSubmatch(cfg); len(am) > 1 {
+ schemeArg = strings.TrimSpace(am[1])
+ }
@@
- if strings.EqualFold(header, "Authorization") {
- extractors = append(extractors, fmt.Sprintf("keyauth.FromAuthHeader(%q, %q)", header, scheme))
+ if strings.EqualFold(header, "Authorization") {
+ extractors = append(extractors, fmt.Sprintf("keyauth.FromAuthHeader(%q, %s)", header, schemeArg))Also applies to: 1045-1052
Summary
Testing
go test ./...https://chatgpt.com/codex/tasks/task_e_689db679dc9c8326bc2e1c1e88c84090
Summary by CodeRabbit
New Features
Tests