|
| 1 | +package browsersafe |
| 2 | + |
| 3 | +import ( |
| 4 | + "k8s.io/apimachinery/pkg/util/sets" |
| 5 | + "k8s.io/apiserver/pkg/authorization/authorizer" |
| 6 | +) |
| 7 | + |
| 8 | +const ( |
| 9 | + proxyAction = "proxy" |
| 10 | + unsafeProxy = "unsafeproxy" |
| 11 | +) |
| 12 | + |
| 13 | +type browserSafeAuthorizer struct { |
| 14 | + delegate authorizer.Authorizer |
| 15 | + |
| 16 | + // list of groups, any of which indicate the request is authenticated |
| 17 | + authenticatedGroups sets.String |
| 18 | +} |
| 19 | + |
| 20 | +func NewBrowserSafeAuthorizer(delegate authorizer.Authorizer, authenticatedGroups ...string) authorizer.Authorizer { |
| 21 | + return &browserSafeAuthorizer{ |
| 22 | + delegate: delegate, |
| 23 | + authenticatedGroups: sets.NewString(authenticatedGroups...), |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +func (a *browserSafeAuthorizer) Authorize(attributes authorizer.Attributes) (bool, string, error) { |
| 28 | + browserSafeAttributes := a.getBrowserSafeAttributes(attributes) |
| 29 | + return a.delegate.Authorize(browserSafeAttributes) |
| 30 | +} |
| 31 | + |
| 32 | +func (a *browserSafeAuthorizer) getBrowserSafeAttributes(attributes authorizer.Attributes) authorizer.Attributes { |
| 33 | + if !attributes.IsResourceRequest() { |
| 34 | + return attributes |
| 35 | + } |
| 36 | + |
| 37 | + isProxyVerb := attributes.GetVerb() == proxyAction |
| 38 | + isProxySubresource := attributes.GetSubresource() == proxyAction |
| 39 | + |
| 40 | + if !isProxyVerb && !isProxySubresource { |
| 41 | + // Requests to non-proxy resources don't expose HTML or HTTP-handling user content to browsers |
| 42 | + return attributes |
| 43 | + } |
| 44 | + |
| 45 | + if user := attributes.GetUser(); user != nil { |
| 46 | + if a.authenticatedGroups.HasAny(user.GetGroups()...) { |
| 47 | + // An authenticated request indicates this isn't a browser page load. |
| 48 | + // Browsers cannot make direct authenticated requests. |
| 49 | + // This depends on the API not enabling basic or cookie-based auth. |
| 50 | + return attributes |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return &browserSafeAttributes{ |
| 55 | + Attributes: attributes, |
| 56 | + isProxyVerb: isProxyVerb, |
| 57 | + isProxySubresource: isProxySubresource, |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +type browserSafeAttributes struct { |
| 62 | + authorizer.Attributes |
| 63 | + |
| 64 | + isProxyVerb, isProxySubresource bool |
| 65 | +} |
| 66 | + |
| 67 | +func (b *browserSafeAttributes) GetVerb() string { |
| 68 | + if b.isProxyVerb { |
| 69 | + return unsafeProxy |
| 70 | + } |
| 71 | + return b.Attributes.GetVerb() |
| 72 | +} |
| 73 | + |
| 74 | +func (b *browserSafeAttributes) GetSubresource() string { |
| 75 | + if b.isProxySubresource { |
| 76 | + return unsafeProxy |
| 77 | + } |
| 78 | + return b.Attributes.GetSubresource() |
| 79 | +} |
0 commit comments