-
Notifications
You must be signed in to change notification settings - Fork 913
Authz for gateway and otlp_http inputs #3927
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
mmatczuk
wants to merge
5
commits into
main
Choose a base branch
from
mmt/authz
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
5 commits
Select commit
Hold shift + click to select a range
8705620
gateway(authz): extract FileWatchingAutzResourcePolicy from mcp
mmatczuk 828fb5e
gateway(authz): add http middleware
mmatczuk 1a3ec5f
gateway(authz): get and set AuthzConfig in service.Resources
mmatczuk 0134301
gateway: add authz authorization policy integration
mmatczuk e605fab
otlp: add authz authorization policy integration for http input
mmatczuk 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,126 @@ | ||
| // Copyright 2026 Redpanda Data, Inc. | ||
| // | ||
| // Licensed as a Redpanda Enterprise file under the Redpanda Community | ||
| // License (the "License"); you may not use this file except in compliance with | ||
| // the License. You may obtain a copy of the License at | ||
| // | ||
| // https://github.com/redpanda-data/connect/blob/main/licenses/rcl.md | ||
|
|
||
| package gateway | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "net/http" | ||
| "sync/atomic" | ||
|
|
||
| "github.com/redpanda-data/benthos/v4/public/service" | ||
| "github.com/redpanda-data/common-go/authz" | ||
| "github.com/redpanda-data/common-go/authz/loader" | ||
| ) | ||
|
|
||
| // AuthzConfig holds the configuration for authorization policy. | ||
| type AuthzConfig struct { | ||
| ResourceName authz.ResourceName | ||
| PolicyFile string | ||
| } | ||
|
|
||
| const authzConfigKey = "rp_gateway_authz_config" | ||
|
|
||
| // SetManagerAuthzConfig stores the authorization configuration in the resource | ||
| // manager. | ||
| func SetManagerAuthzConfig(mgr *service.Resources, conf AuthzConfig) { | ||
| mgr.SetGeneric(authzConfigKey, conf) | ||
| } | ||
|
|
||
| // ManagerAuthzConfig retrieves the authorization configuration from the | ||
| // resource manager. | ||
| func ManagerAuthzConfig(mgr *service.Resources) (AuthzConfig, bool) { | ||
| if c, ok := mgr.GetGeneric(authzConfigKey); ok { | ||
| return c.(AuthzConfig), true | ||
| } | ||
| return AuthzConfig{}, false | ||
| } | ||
|
|
||
| // FileWatchingAuthzResourcePolicy wraps an authorization policy that | ||
| // automatically reloads when the underlying policy file changes. | ||
| // Thread-safe for concurrent use. | ||
| type FileWatchingAuthzResourcePolicy struct { | ||
| unwatch loader.PolicyUnwatch | ||
| value atomic.Pointer[authz.ResourcePolicy] | ||
| } | ||
|
|
||
| // NewFileWatchingAuthzResourcePolicy loads an authorization policy from file and | ||
| // watches it for changes. The notifyError callback is called on reload errors. | ||
| func NewFileWatchingAuthzResourcePolicy( | ||
| name authz.ResourceName, | ||
| file string, | ||
| permissions []authz.PermissionName, | ||
| notifyError func(error), | ||
| ) (*FileWatchingAuthzResourcePolicy, error) { | ||
| a := new(FileWatchingAuthzResourcePolicy) | ||
|
|
||
| policy, unwatch, err := loader.WatchPolicyFile(file, func(policy authz.Policy, err error) { | ||
| if err != nil { | ||
| notifyError(fmt.Errorf("watching authorization policy file: %w", err)) | ||
| return | ||
| } | ||
| rp, err := authz.NewResourcePolicy(policy, name, permissions) | ||
| if err != nil { | ||
| notifyError(fmt.Errorf("loading authorization policy: %w", err)) | ||
| return | ||
| } | ||
| a.value.Store(rp) | ||
| }) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("load authorization policy file: %w", err) | ||
| } | ||
| a.unwatch = unwatch | ||
|
|
||
| rp, err := authz.NewResourcePolicy(policy, name, permissions) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("compile authorization policy: %w", err) | ||
| } | ||
| a.value.Store(rp) | ||
|
|
||
| return a, nil | ||
| } | ||
|
|
||
| // Close closes the resource policy and stops watching the policy file. | ||
| func (r *FileWatchingAuthzResourcePolicy) Close() error { | ||
| if r == nil { | ||
| return nil | ||
| } | ||
| return r.unwatch() | ||
| } | ||
|
|
||
| // Authorizer returns an [Authorizer] for this resource and the given permission. | ||
| // The permission must have been provided to [NewFileWatchingAuthzResourcePolicy]. | ||
| func (r *FileWatchingAuthzResourcePolicy) Authorizer(perm authz.PermissionName) authz.Authorizer { | ||
| return r.value.Load().Authorizer(perm) | ||
| } | ||
|
|
||
| // SubResourceAuthorizer returns an [Authorizer] for a child resource and | ||
| // the given permission. The permission must have been provided to | ||
| // [NewFileWatchingAuthzResourcePolicy]. | ||
| func (r *FileWatchingAuthzResourcePolicy) SubResourceAuthorizer(t authz.ResourceType, id authz.ResourceID, perm authz.PermissionName) authz.Authorizer { | ||
| return r.value.Load().SubResourceAuthorizer(t, id, perm) | ||
| } | ||
|
|
||
| // AuthzMiddleware returns an HTTP middleware handler that enforces | ||
| // authorization checks for the given permission before invoking the next | ||
| // handler. If the principal is missing or unauthorized, it responds with | ||
| // 403 Forbidden. | ||
| func AuthzMiddleware( | ||
| policy *FileWatchingAuthzResourcePolicy, | ||
| perm authz.PermissionName, | ||
| next http.Handler, | ||
| ) http.Handler { | ||
| return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { | ||
| principal, ok := ValidatedPrincipalIDFromContext(req.Context()) | ||
| if !ok || !policy.Authorizer(perm).Check(principal) { | ||
| http.Error(w, "Forbidden", http.StatusForbidden) | ||
| return | ||
| } | ||
| next.ServeHTTP(w, req) | ||
| }) | ||
| } | ||
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,215 @@ | ||
| // Copyright 2026 Redpanda Data, Inc. | ||
| // | ||
| // Licensed as a Redpanda Enterprise file under the Redpanda Community | ||
| // License (the "License"); you may not use this file except in compliance with | ||
| // the License. You may obtain a copy of the License at | ||
| // | ||
| // https://github.com/redpanda-data/connect/blob/main/licenses/rcl.md | ||
|
|
||
| package gateway_test | ||
|
|
||
| import ( | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
|
|
||
| "github.com/redpanda-data/common-go/authz" | ||
| "github.com/redpanda-data/connect/v4/internal/gateway" | ||
| ) | ||
|
|
||
| const ( | ||
| authzTestResourceName authz.ResourceName = "organization/test-org/resourcegroup/default/dataplane/test-service" | ||
| authzTestPermRead authz.PermissionName = "test_service_read" | ||
| authzTestPermWrite authz.PermissionName = "test_service_write" | ||
| authzTestPrincipal authz.PrincipalID = "test@example.com" | ||
| authzOtherPrincipal authz.PrincipalID = "other@example.com" | ||
| ) | ||
|
|
||
| // testHandler is a simple HTTP handler that writes "OK" on success | ||
| var testHandler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | ||
| w.WriteHeader(http.StatusOK) | ||
| _, _ = w.Write([]byte("OK")) | ||
| }) | ||
|
|
||
| func TestAuthzMiddlewareAllowAll(t *testing.T) { | ||
| t.Log("Given: Policy file granting all permissions") | ||
| policy := setupPolicy(t, "testdata/policies/allow_all.yaml") | ||
| defer policy.Close() | ||
|
|
||
| t.Log("And: Middleware protecting a handler with read permission") | ||
| middleware := gateway.AuthzMiddleware(policy, authzTestPermRead, testHandler) | ||
|
|
||
| t.Log("When: Request with valid principal in context") | ||
| req := httptest.NewRequest(http.MethodGet, "/test", http.NoBody) | ||
| req = req.WithContext(gateway.ContextWithValidatedPrincipalID(req.Context(), authzTestPrincipal)) | ||
| rec := httptest.NewRecorder() | ||
| middleware.ServeHTTP(rec, req) | ||
|
|
||
| t.Log("Then: Request succeeds") | ||
| assert.Equal(t, http.StatusOK, rec.Code) | ||
| } | ||
|
|
||
| func TestAuthzMiddlewareDenyAll(t *testing.T) { | ||
| t.Log("Given: Policy file denying all permissions") | ||
| policy := setupPolicy(t, "testdata/policies/deny_all.yaml") | ||
| defer policy.Close() | ||
|
|
||
| t.Log("And: Middleware protecting a handler with read permission") | ||
| middleware := gateway.AuthzMiddleware(policy, authzTestPermRead, testHandler) | ||
|
|
||
| t.Log("When: Request with valid principal but no permissions") | ||
| req := httptest.NewRequest(http.MethodGet, "/test", http.NoBody) | ||
| req = req.WithContext(gateway.ContextWithValidatedPrincipalID(req.Context(), authzTestPrincipal)) | ||
| rec := httptest.NewRecorder() | ||
| middleware.ServeHTTP(rec, req) | ||
|
|
||
| t.Log("Then: Request is forbidden") | ||
| assert.Equal(t, http.StatusForbidden, rec.Code) | ||
| assert.Contains(t, rec.Body.String(), "Forbidden") | ||
| } | ||
|
|
||
| func TestAuthzMiddlewareNoPrincipal(t *testing.T) { | ||
| t.Log("Given: Policy file granting all permissions") | ||
| policy := setupPolicy(t, "testdata/policies/allow_all.yaml") | ||
| defer policy.Close() | ||
|
|
||
| t.Log("And: Middleware protecting a handler with read permission") | ||
| middleware := gateway.AuthzMiddleware(policy, authzTestPermRead, testHandler) | ||
|
|
||
| t.Log("When: Request without principal in context") | ||
| req := httptest.NewRequest(http.MethodGet, "/test", nil) | ||
| rec := httptest.NewRecorder() | ||
| middleware.ServeHTTP(rec, req) | ||
|
|
||
| t.Log("Then: Request is forbidden") | ||
| assert.Equal(t, http.StatusForbidden, rec.Code) | ||
| assert.Contains(t, rec.Body.String(), "Forbidden") | ||
| } | ||
|
|
||
| func TestAuthzMiddlewareSelective(t *testing.T) { | ||
| t.Log("Given: Policy file granting only read permission") | ||
| policy := setupPolicy(t, "testdata/policies/selective.yaml") | ||
| defer policy.Close() | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| permission authz.PermissionName | ||
| wantCode int | ||
| wantBody string | ||
| }{ | ||
| { | ||
| name: "allowed_read", | ||
| permission: authzTestPermRead, | ||
| wantCode: http.StatusOK, | ||
| wantBody: "OK", | ||
| }, | ||
| { | ||
| name: "denied_write", | ||
| permission: authzTestPermWrite, | ||
| wantCode: http.StatusForbidden, | ||
| wantBody: "Forbidden", | ||
| }, | ||
| } | ||
|
|
||
| for _, tc := range tests { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| t.Logf("When: Request requires %s permission", tc.permission) | ||
| middleware := gateway.AuthzMiddleware(policy, tc.permission, testHandler) | ||
| req := httptest.NewRequest(http.MethodGet, "/test", nil) | ||
| req = req.WithContext(gateway.ContextWithValidatedPrincipalID(req.Context(), authzTestPrincipal)) | ||
| rec := httptest.NewRecorder() | ||
| middleware.ServeHTTP(rec, req) | ||
|
|
||
| t.Logf("Then: Request %s", tc.wantBody) | ||
| assert.Equal(t, tc.wantCode, rec.Code) | ||
| assert.Contains(t, rec.Body.String(), tc.wantBody) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestAuthzMiddlewareWrongPrincipal(t *testing.T) { | ||
| t.Log("Given: Policy file granting permissions to specific principal") | ||
| policy := setupPolicy(t, "testdata/policies/allow_all.yaml") | ||
| defer policy.Close() | ||
|
|
||
| t.Log("And: Middleware protecting a handler with read permission") | ||
| middleware := gateway.AuthzMiddleware(policy, authzTestPermRead, testHandler) | ||
|
|
||
| t.Log("When: Request with different principal not in policy") | ||
| req := httptest.NewRequest(http.MethodGet, "/test", nil) | ||
| req = req.WithContext(gateway.ContextWithValidatedPrincipalID(req.Context(), authzOtherPrincipal)) | ||
| rec := httptest.NewRecorder() | ||
| middleware.ServeHTTP(rec, req) | ||
|
|
||
| t.Log("Then: Request is forbidden") | ||
| assert.Equal(t, http.StatusForbidden, rec.Code) | ||
| assert.Contains(t, rec.Body.String(), "Forbidden") | ||
| } | ||
|
|
||
| func TestAuthzMiddlewarePolicyReload(t *testing.T) { | ||
| t.Log("Given: Policy file with allow_all") | ||
| dir := t.TempDir() | ||
| policyFile := filepath.Join(dir, "policy.yaml") | ||
|
|
||
| copyPolicyFile := func(src string) { | ||
| data, err := os.ReadFile(src) | ||
| require.NoError(t, err) | ||
| require.NoError(t, os.WriteFile(policyFile, data, 0o644)) | ||
| } | ||
|
|
||
| copyPolicyFile("testdata/policies/allow_all.yaml") | ||
| policy := setupPolicy(t, policyFile) | ||
| defer policy.Close() | ||
|
|
||
| t.Log("And: Middleware protecting a handler with read permission") | ||
| middleware := gateway.AuthzMiddleware(policy, authzTestPermRead, testHandler) | ||
|
|
||
| t.Run("allow_all", func(t *testing.T) { | ||
| t.Log("When: Request with valid principal") | ||
| req := httptest.NewRequest(http.MethodGet, "/test", nil) | ||
| req = req.WithContext(gateway.ContextWithValidatedPrincipalID(req.Context(), authzTestPrincipal)) | ||
| rec := httptest.NewRecorder() | ||
| middleware.ServeHTTP(rec, req) | ||
|
|
||
| t.Log("Then: Request succeeds") | ||
| assert.Equal(t, http.StatusOK, rec.Code) | ||
| }) | ||
|
|
||
| t.Log("Given: Policy file updated to deny_all") | ||
| copyPolicyFile("testdata/policies/deny_all.yaml") | ||
| time.Sleep(100 * time.Millisecond) | ||
|
|
||
| t.Run("deny_all", func(t *testing.T) { | ||
| t.Log("When: Request with valid principal") | ||
| req := httptest.NewRequest(http.MethodGet, "/test", nil) | ||
| req = req.WithContext(gateway.ContextWithValidatedPrincipalID(req.Context(), authzTestPrincipal)) | ||
| rec := httptest.NewRecorder() | ||
| middleware.ServeHTTP(rec, req) | ||
|
|
||
| t.Log("Then: Request fails") | ||
| assert.Equal(t, http.StatusForbidden, rec.Code) | ||
| assert.Contains(t, rec.Body.String(), "Forbidden") | ||
| }) | ||
| } | ||
|
|
||
| // setupPolicy creates a FileWatchingAuthzResourcePolicy for testing | ||
| func setupPolicy(t *testing.T, policyFile string) *gateway.FileWatchingAuthzResourcePolicy { | ||
| t.Helper() | ||
| policy, err := gateway.NewFileWatchingAuthzResourcePolicy( | ||
| authzTestResourceName, | ||
| policyFile, | ||
| []authz.PermissionName{authzTestPermRead, authzTestPermWrite}, | ||
| func(err error) { | ||
| t.Fatalf("Policy watch error: %v", err) | ||
| }, | ||
| ) | ||
| require.NoError(t, err) | ||
|
|
||
| return policy | ||
| } |
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,10 @@ | ||
| roles: | ||
| - id: test.admin | ||
| permissions: | ||
| - test_service_read | ||
| - test_service_write | ||
|
|
||
| bindings: | ||
| - role: test.admin | ||
| principal: test@example.com | ||
| scope: organization/test-org/resourcegroup/default/dataplane/test-service |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we use a custom type here so it's impossible to get conflicts?