/
authorization.go
72 lines (62 loc) · 2.59 KB
/
authorization.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package handlers
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
restful "github.com/emicklei/go-restful"
"k8s.io/kubernetes/pkg/api/legacyscheme"
kapierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
kauthorizer "k8s.io/apiserver/pkg/authorization/authorizer"
coreapi "k8s.io/kubernetes/pkg/apis/core"
)
type bypassAuthorizer struct {
paths sets.String
authorizer kauthorizer.Authorizer
}
// NewBypassAuthorizer creates an Authorizer that always allows the exact paths described, and delegates to the nested
// authorizer for everything else.
func NewBypassAuthorizer(auth kauthorizer.Authorizer, paths ...string) kauthorizer.Authorizer {
return bypassAuthorizer{paths: sets.NewString(paths...), authorizer: auth}
}
func (a bypassAuthorizer) Authorize(attributes kauthorizer.Attributes) (allowed kauthorizer.Decision, reason string, err error) {
if !attributes.IsResourceRequest() && a.paths.Has(attributes.GetPath()) {
return kauthorizer.DecisionAllow, "always allowed", nil
}
return a.authorizer.Authorize(attributes)
}
// Forbidden renders a simple forbidden error to the response
func Forbidden(reason string, attributes kauthorizer.Attributes, w http.ResponseWriter, req *http.Request) {
resource := ""
group := ""
name := ""
// the attributes can be empty for two basic reasons:
// 1. malformed API request
// 2. not an API request at all
// In these cases, just assume default that will work better than nothing
if attributes != nil {
group = attributes.GetAPIGroup()
resource = attributes.GetResource()
name = attributes.GetName()
}
// Reason is an opaque string that describes why access is allowed or forbidden (forbidden by the time we reach here).
// We don't have direct access to kind or name (not that those apply either in the general case)
// We create a NewForbidden to stay close the API, but then we override the message to get a serialization
// that makes sense when a human reads it.
forbiddenError := kapierrors.NewForbidden(schema.GroupResource{Group: group, Resource: resource}, name, errors.New("") /*discarded*/)
forbiddenError.ErrStatus.Message = reason
formatted := &bytes.Buffer{}
output, err := runtime.Encode(legacyscheme.Codecs.LegacyCodec(coreapi.SchemeGroupVersion), &forbiddenError.ErrStatus)
if err != nil {
fmt.Fprintf(formatted, "%s", forbiddenError.Error())
} else {
json.Indent(formatted, output, "", " ")
}
w.Header().Set("Content-Type", restful.MIME_JSON)
w.WriteHeader(http.StatusForbidden)
w.Write(formatted.Bytes())
}