Skip to content

feat: add keyauth migrator#157

Merged
ReneWerner87 merged 1 commit intomasterfrom
codex/2025-08-14-19-05-20
Aug 14, 2025
Merged

feat: add keyauth migrator#157
ReneWerner87 merged 1 commit intomasterfrom
codex/2025-08-14-19-05-20

Conversation

@ReneWerner87
Copy link
Member

@ReneWerner87 ReneWerner87 commented Aug 14, 2025

Summary

  • migrate keyauth configs to new Extractor API
  • wire keyauth migrator into migration list
  • cover keyauth migration with tests

Testing

  • go test ./...

https://chatgpt.com/codex/tasks/task_e_689db679dc9c8326bc2e1c1e88c84090

Summary by CodeRabbit

  • New Features

    • Enhances upgrade migrations to automatically convert key authentication configuration to the new extractor-based format.
    • Supports header, query, path, form, and cookie sources; chains multiple sources when present.
    • Applies a sensible default auth scheme when not specified and removes deprecated fields.
    • Provides clearer migration status logs during upgrades from 2.x to pre-4.0.
  • Tests

    • Adds comprehensive tests covering header, cookie, chained, and unknown source scenarios for the migration.

@coderabbitai
Copy link

coderabbitai bot commented Aug 14, 2025

Walkthrough

Introduces 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

Cohort / File(s) Summary of changes
Migration registration
cmd/internal/migrations/lists.go
Registers MigrateKeyAuthConfig in the v3 migration sequence (2.0.0 to <4.0.0-0), positioned after MigrateSessionExtractor.
v3 migration logic
cmd/internal/migrations/v3/common.go
Adds MigrateKeyAuthConfig to transform keyauth.Config from KeyLookup/AuthScheme to Extractor using header/query/param/form/cookie sources; handles chaining and unknown sources; removes deprecated fields.
Tests for migration
cmd/internal/migrations/v3/common_test.go
Adds tests validating header, cookie, chained, and unknown source scenarios; asserts source transformations and status log output.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–25 minutes

Possibly related PRs

Suggested labels

✏️ Feature

Suggested reviewers

  • gaby
  • efectn

Poem

I hop through configs, light on my feet,
Turning keys to extractors—so neat!
Headers and cookies now dance in a chain,
Unknowns swept clean like April rain.
Tap-tap my paws, migrations align—
Code gardens pruned, looking fine. 🐇✨

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 Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/2025-08-14-19-05-20

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.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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 or @coderabbitai title 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@github-actions github-actions bot added the ✏️ Feature New feature or request label Aug 14, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

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

  1. 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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

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{[^}]*}`)
Copy link
Contributor

Choose a reason for hiding this comment

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

high

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.

@ReneWerner87 ReneWerner87 merged commit 64374d6 into master Aug 14, 2025
12 of 13 checks passed
@ReneWerner87 ReneWerner87 deleted the codex/2025-08-14-19-05-20 branch August 14, 2025 19:07
Copy link

@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.

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)

reKeyLookup only 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 regressions

Coverage 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 sources

You 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.

📥 Commits

Reviewing files that changed from the base of the PR and between e3fbaec and 1ed3d37.

📒 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 extractor

Placement after MigrateSessionExtractor is coherent and preserves the existing migration flow.

Comment on lines +1032 to +1039
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
}
}

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex ✏️ Feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant