Repository navigation
feat: add plugin install command #332
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
Open
fzipi
wants to merge
3
commits into
main
Choose a base branch
from
feat/plugin-install
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| // Copyright 2026 OWASP Core Rule Set Project | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package install | ||
|
|
||
| import ( | ||
| "fmt" | ||
|
|
||
| "github.com/rs/zerolog/log" | ||
| "github.com/spf13/cobra" | ||
|
|
||
| "github.com/coreruleset/crs-toolchain/v2/cmd/internal" | ||
| "github.com/coreruleset/crs-toolchain/v2/plugin" | ||
| ) | ||
|
|
||
| var logger = log.With().Str("component", "cmd.plugin.install").Logger() | ||
|
|
||
| var ( | ||
| pluginsDir string | ||
| version string | ||
| force bool | ||
| requireSignature bool | ||
| ) | ||
|
|
||
| func New(cmdContext *internal.CommandContext) *cobra.Command { | ||
| cmd := &cobra.Command{ | ||
| Use: "install NAME", | ||
| Short: "Install a CRS plugin from the plugin registry", | ||
| Long: `Resolve NAME against the published plugin registry, resolve a release tag, | ||
| download that release, and copy the plugin's files into the plugins directory. | ||
|
|
||
| Existing files are never overwritten unless --force is given.`, | ||
| Args: cobra.ExactArgs(1), | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| targetDir := pluginsDir | ||
| if targetDir == "" { | ||
| targetDir = cmdContext.RootContext().PluginsDir() | ||
| } | ||
|
|
||
| result, err := plugin.Install(cmd.Context(), plugin.Options{ | ||
| Name: args[0], | ||
| Version: version, | ||
| PluginsDir: targetDir, | ||
| Force: force, | ||
| RequireSignature: requireSignature, | ||
| }) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| report(cmd, cmdContext, targetDir, result) | ||
| return nil | ||
| }, | ||
| } | ||
|
|
||
| buildFlags(cmd) | ||
| return cmd | ||
| } | ||
|
|
||
| func buildFlags(cmd *cobra.Command) { | ||
| cmd.Flags().StringVar(&pluginsDir, "plugins-dir", "", | ||
| "Target directory to install into. Defaults to '<CRS_ROOT>/plugins'.") | ||
| cmd.Flags().StringVar(&version, "version", "", | ||
| "Release tag to install. Defaults to the newest release.") | ||
| cmd.Flags().BoolVar(&force, "force", false, | ||
| "Overwrite files already present in the target directory.") | ||
| cmd.Flags().BoolVar(&requireSignature, "require-signature", false, | ||
| "Fail unless the release is signed. No registered plugin publishes signed releases yet, "+ | ||
| "so this always fails today.") | ||
| } | ||
|
|
||
| func report(cmd *cobra.Command, cmdContext *internal.CommandContext, targetDir string, result *plugin.Result) { | ||
| out := cmd.OutOrStdout() | ||
| fmt.Fprintf(out, "Installed %s %s (%s) into %s\n", result.Name, result.Tag, result.Repository, targetDir) | ||
| fmt.Fprintf(out, " type: %s, status: %s, rule IDs: %d-%d\n", | ||
| result.Type, result.Status, result.RuleIDRange.Start, result.RuleIDRange.End) | ||
| fmt.Fprintf(out, " digest: %s\n", result.Digest) | ||
|
|
||
| if result.LuaWarning { | ||
| warn(cmd, cmdContext, fmt.Sprintf("%s ships Lua scripts; it requires a Lua-enabled ModSecurity", result.Name)) | ||
| } | ||
| for _, file := range result.OverlapWarnings { | ||
| warn(cmd, cmdContext, fmt.Sprintf("%s's rule ID range overlaps existing file %s", result.Name, file)) | ||
| } | ||
| } | ||
|
|
||
| func warn(cmd *cobra.Command, cmdContext *internal.CommandContext, message string) { | ||
| if cmdContext.Output == internal.GitHub { | ||
| fmt.Fprintf(cmd.OutOrStdout(), "::warning ::%s\n", message) | ||
| return | ||
| } | ||
| logger.Warn().Msg(message) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| // Copyright 2026 OWASP Core Rule Set Project | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package plugin | ||
|
|
||
| import ( | ||
| "github.com/spf13/cobra" | ||
|
|
||
| "github.com/coreruleset/crs-toolchain/v2/cmd/internal" | ||
| "github.com/coreruleset/crs-toolchain/v2/cmd/plugin/install" | ||
| ) | ||
|
|
||
| func New(cmdContext *internal.CommandContext) *cobra.Command { | ||
| cmd := &cobra.Command{ | ||
| Use: "plugin", | ||
| Short: "Manage CRS plugins", | ||
| Args: cobra.ExactArgs(1), | ||
| } | ||
|
|
||
| cmd.AddCommand(install.New(cmdContext)) | ||
|
|
||
| return cmd | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| // Copyright 2026 OWASP Core Rule Set Project | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package plugin | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "os" | ||
| "regexp" | ||
| "time" | ||
|
|
||
| "github.com/cli/go-gh/v2/pkg/api" | ||
| ) | ||
|
|
||
| // githubAPIBaseURL is a var so tests can point it at an httptest server. It | ||
| // is passed as an absolute URL to the go-gh REST client, which uses it | ||
| // as-is instead of resolving it against the client's configured host. | ||
| var githubAPIBaseURL = "https://api.github.com" | ||
|
|
||
| // githubTimeout bounds a single GitHub API or download request. | ||
| var githubTimeout = 60 * time.Second | ||
|
|
||
| // maxTarballBytes bounds the size of a downloaded plugin source tarball. | ||
| // Plugin repositories are a handful of rule/config/lua files; anything | ||
| // approaching this size indicates a misbehaving or malicious release rather | ||
| // than a legitimate plugin. | ||
| const maxTarballBytes = 100 << 20 // 100 MiB | ||
|
|
||
| var repositoryURLPattern = regexp.MustCompile(`^https://github\.com/([^/]+)/([^/]+?)/?$`) | ||
|
|
||
| // parseRepository extracts the owner and repo name from a GitHub repository | ||
| // URL, as published in the registry's `repository` field. | ||
| func parseRepository(repositoryURL string) (owner, repo string, err error) { | ||
| matches := repositoryURLPattern.FindStringSubmatch(repositoryURL) | ||
| if matches == nil { | ||
| return "", "", fmt.Errorf("%q is not a GitHub repository URL", repositoryURL) | ||
| } | ||
| return matches[1], matches[2], nil | ||
| } | ||
|
|
||
| // newGitHubClient builds a go-gh REST client. If a GH_TOKEN or GITHUB_TOKEN | ||
| // is set, or the gh CLI is configured, requests are authenticated, which is | ||
| // what allows installing from a private plugin repository. | ||
| func newGitHubClient() (*api.RESTClient, error) { | ||
| client, err := api.NewRESTClient(api.ClientOptions{ | ||
| Headers: map[string]string{ | ||
| "Accept": "application/vnd.github+json", | ||
| "X-GitHub-Api-Version": "2022-11-28", | ||
| }, | ||
| Timeout: githubTimeout, | ||
| }) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("creating GitHub client: %w", err) | ||
| } | ||
| return client, nil | ||
| } | ||
|
|
||
| // resolveTag resolves version to a concrete GitHub release tag. An empty | ||
| // version resolves to the newest release. A repository with no releases, or | ||
| // a pinned version that isn't a published release, is a clear error rather | ||
| // than falling back to a branch. | ||
| func resolveTag(ctx context.Context, client *api.RESTClient, owner, repo, version string) (string, error) { | ||
| path := fmt.Sprintf("%s/repos/%s/%s/releases/latest", githubAPIBaseURL, owner, repo) | ||
| if version != "" { | ||
| path = fmt.Sprintf("%s/repos/%s/%s/releases/tags/%s", githubAPIBaseURL, owner, repo, version) | ||
| } | ||
|
|
||
| var release struct { | ||
| TagName string `json:"tag_name"` | ||
| } | ||
| if err := client.DoWithContext(ctx, http.MethodGet, path, nil, &release); err != nil { | ||
| var httpErr *api.HTTPError | ||
| if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound { | ||
| if version != "" { | ||
| return "", fmt.Errorf("no release tagged %q found for %s/%s", version, owner, repo) | ||
| } | ||
| return "", fmt.Errorf("no releases found for %s/%s (repository may be private or have no releases)", owner, repo) | ||
| } | ||
| return "", fmt.Errorf("resolving release for %s/%s: %w", owner, repo, err) | ||
| } | ||
| return release.TagName, nil | ||
| } | ||
|
|
||
| // downloadTarball downloads the source archive for owner/repo at tag into | ||
| // destFile. GitHub plugin releases publish no release assets, so the source | ||
| // tarball is the only artifact that can be fetched at a given tag. | ||
| func downloadTarball(ctx context.Context, client *api.RESTClient, owner, repo, tag, destFile string) error { | ||
| ctx, cancel := context.WithTimeout(ctx, githubTimeout) | ||
| defer cancel() | ||
|
|
||
| path := fmt.Sprintf("%s/repos/%s/%s/tarball/%s", githubAPIBaseURL, owner, repo, tag) | ||
| resp, err := client.RequestWithContext(ctx, http.MethodGet, path, nil) | ||
| if err != nil { | ||
| return fmt.Errorf("downloading %s/%s@%s: %w", owner, repo, tag, err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| out, err := os.Create(destFile) | ||
| if err != nil { | ||
| return fmt.Errorf("creating %s for %s/%s@%s: %w", destFile, owner, repo, tag, err) | ||
| } | ||
|
|
||
| written, copyErr := io.Copy(out, io.LimitReader(resp.Body, maxTarballBytes+1)) | ||
| closeErr := out.Close() | ||
| if err := errors.Join(copyErr, closeErr); err != nil { | ||
| return fmt.Errorf("writing %s/%s@%s: %w", owner, repo, tag, err) | ||
| } | ||
| if written > maxTarballBytes { | ||
| return fmt.Errorf("downloading %s/%s@%s: archive exceeds maximum size of %d bytes", owner, repo, tag, maxTarballBytes) | ||
| } | ||
| return nil | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.