本文整理汇总了Golang中github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors.IsUnauthorized函数的典型用法代码示例。如果您正苦于以下问题:Golang IsUnauthorized函数的具体用法?Golang IsUnauthorized怎么用?Golang IsUnauthorized使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了IsUnauthorized函数的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: doServiceAccountAPIRequests
func doServiceAccountAPIRequests(t *testing.T, c *client.Client, ns string, authenticated bool, canRead bool, canWrite bool) {
testSecret := &api.Secret{
ObjectMeta: api.ObjectMeta{Name: "testSecret"},
Data: map[string][]byte{"test": []byte("data")},
}
readOps := []testOperation{
func() error { _, err := c.Secrets(ns).List(labels.Everything(), fields.Everything()); return err },
func() error { _, err := c.Pods(ns).List(labels.Everything(), fields.Everything()); return err },
}
writeOps := []testOperation{
func() error { _, err := c.Secrets(ns).Create(testSecret); return err },
func() error { return c.Secrets(ns).Delete(testSecret.Name) },
}
for _, op := range readOps {
err := op()
unauthorizedError := errors.IsUnauthorized(err)
forbiddenError := errors.IsForbidden(err)
switch {
case !authenticated && !unauthorizedError:
t.Fatalf("expected unauthorized error, got %v", err)
case authenticated && unauthorizedError:
t.Fatalf("unexpected unauthorized error: %v", err)
case authenticated && canRead && forbiddenError:
t.Fatalf("unexpected forbidden error: %v", err)
case authenticated && !canRead && !forbiddenError:
t.Fatalf("expected forbidden error, got: %v", err)
}
}
for _, op := range writeOps {
err := op()
unauthorizedError := errors.IsUnauthorized(err)
forbiddenError := errors.IsForbidden(err)
switch {
case !authenticated && !unauthorizedError:
t.Fatalf("expected unauthorized error, got %v", err)
case authenticated && unauthorizedError:
t.Fatalf("unexpected unauthorized error: %v", err)
case authenticated && canWrite && forbiddenError:
t.Fatalf("unexpected forbidden error: %v", err)
case authenticated && !canWrite && !forbiddenError:
t.Fatalf("expected forbidden error, got: %v", err)
}
}
}
示例2: verifyOpenShiftUser
func verifyOpenShiftUser(client *client.Client) error {
if _, err := client.Users().Get("~"); err != nil {
log.Errorf("Get user failed with error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
return nil
}
示例3: NewCmdLogin
// NewCmdLogin implements the OpenShift cli login command
func NewCmdLogin(fullName string, f *osclientcmd.Factory, reader io.Reader, out io.Writer) *cobra.Command {
options := &LoginOptions{
Reader: reader,
Out: out,
}
cmds := &cobra.Command{
Use: "login [URL]",
Short: "Log in to an OpenShift server",
Long: loginLong,
Example: fmt.Sprintf(loginExample, fullName),
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, cmd, args); err != nil {
kcmdutil.CheckErr(err)
}
if err := options.Validate(args, kcmdutil.GetFlagString(cmd, "server")); err != nil {
kcmdutil.CheckErr(err)
}
err := RunLogin(cmd, options)
if kapierrors.IsUnauthorized(err) {
fmt.Fprintln(out, "Login failed (401 Unauthorized)")
if err, isStatusErr := err.(*kapierrors.StatusError); isStatusErr {
if details := err.Status().Details; details != nil {
for _, cause := range details.Causes {
fmt.Fprintln(out, cause.Message)
}
}
}
os.Exit(1)
} else {
kcmdutil.CheckErr(err)
}
},
}
// Login is the only command that can negotiate a session token against the auth server using basic auth
cmds.Flags().StringVarP(&options.Username, "username", "u", "", "Username, will prompt if not provided")
cmds.Flags().StringVarP(&options.Password, "password", "p", "", "Password, will prompt if not provided")
return cmds
}
示例4: verifyPruneAccess
func verifyPruneAccess(client *client.Client) error {
sar := authorizationapi.SubjectAccessReview{
Verb: "delete",
Resource: "images",
}
response, err := client.ClusterSubjectAccessReviews().Create(&sar)
if err != nil {
log.Errorf("OpenShift client error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
if !response.Allowed {
log.Errorf("OpenShift access denied: %s", response.Reason)
return ErrOpenShiftAccessDenied
}
return nil
}
示例5: verifyImageStreamAccess
func verifyImageStreamAccess(namespace, imageRepo, verb string, client *client.Client) error {
sar := authorizationapi.SubjectAccessReview{
Verb: verb,
Resource: "imagestreams/layers",
ResourceName: imageRepo,
}
response, err := client.SubjectAccessReviews(namespace).Create(&sar)
if err != nil {
log.Errorf("OpenShift client error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
if !response.Allowed {
log.Errorf("OpenShift access denied: %s", response.Reason)
return ErrOpenShiftAccessDenied
}
return nil
}
示例6: TestRequestWatch
func TestRequestWatch(t *testing.T) {
testCases := []struct {
Request *Request
Err bool
ErrFn func(error) bool
Empty bool
}{
{
Request: &Request{err: errors.New("bail")},
Err: true,
},
{
Request: &Request{baseURL: &url.URL{}, path: "%"},
Err: true,
},
{
Request: &Request{
client: clientFunc(func(req *http.Request) (*http.Response, error) {
return nil, errors.New("err")
}),
baseURL: &url.URL{},
},
Err: true,
},
{
Request: &Request{
codec: testapi.Codec(),
client: clientFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusForbidden}, nil
}),
baseURL: &url.URL{},
},
Err: true,
ErrFn: func(err error) bool {
return apierrors.IsForbidden(err)
},
},
{
Request: &Request{
codec: testapi.Codec(),
client: clientFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusUnauthorized}, nil
}),
baseURL: &url.URL{},
},
Err: true,
ErrFn: func(err error) bool {
return apierrors.IsUnauthorized(err)
},
},
{
Request: &Request{
codec: testapi.Codec(),
client: clientFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusUnauthorized,
Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(testapi.Codec(), &api.Status{
Status: api.StatusFailure,
Reason: api.StatusReasonUnauthorized,
})))),
}, nil
}),
baseURL: &url.URL{},
},
Err: true,
ErrFn: func(err error) bool {
return apierrors.IsUnauthorized(err)
},
},
{
Request: &Request{
client: clientFunc(func(req *http.Request) (*http.Response, error) {
return nil, io.EOF
}),
baseURL: &url.URL{},
},
Empty: true,
},
{
Request: &Request{
client: clientFunc(func(req *http.Request) (*http.Response, error) {
return nil, &url.Error{Err: io.EOF}
}),
baseURL: &url.URL{},
},
Empty: true,
},
{
Request: &Request{
client: clientFunc(func(req *http.Request) (*http.Response, error) {
return nil, errors.New("http: can't write HTTP request on broken connection")
}),
baseURL: &url.URL{},
},
Empty: true,
},
{
Request: &Request{
client: clientFunc(func(req *http.Request) (*http.Response, error) {
return nil, errors.New("foo: connection reset by peer")
//.........这里部分代码省略.........
示例7: TestTransformResponse
func TestTransformResponse(t *testing.T) {
invalid := []byte("aaaaa")
uri, _ := url.Parse("http://localhost")
testCases := []struct {
Response *http.Response
Data []byte
Created bool
Error bool
ErrFn func(err error) bool
}{
{Response: &http.Response{StatusCode: 200}, Data: []byte{}},
{Response: &http.Response{StatusCode: 201}, Data: []byte{}, Created: true},
{Response: &http.Response{StatusCode: 199}, Error: true},
{Response: &http.Response{StatusCode: 500}, Error: true},
{Response: &http.Response{StatusCode: 422}, Error: true},
{Response: &http.Response{StatusCode: 409}, Error: true},
{Response: &http.Response{StatusCode: 404}, Error: true},
{Response: &http.Response{StatusCode: 401}, Error: true},
{
Response: &http.Response{
StatusCode: 401,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: ioutil.NopCloser(bytes.NewReader(invalid)),
},
Error: true,
ErrFn: func(err error) bool {
return err.Error() != "aaaaa" && apierrors.IsUnauthorized(err)
},
},
{
Response: &http.Response{
StatusCode: 401,
Header: http.Header{"Content-Type": []string{"text/any"}},
Body: ioutil.NopCloser(bytes.NewReader(invalid)),
},
Error: true,
ErrFn: func(err error) bool {
return strings.Contains(err.Error(), "server has asked for the client to provide") && apierrors.IsUnauthorized(err)
},
},
{Response: &http.Response{StatusCode: 403}, Error: true},
{Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid},
{Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid},
}
for i, test := range testCases {
r := NewRequest(nil, "", uri, testapi.Version(), testapi.Codec())
if test.Response.Body == nil {
test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
}
result := r.transformResponse(test.Response, &http.Request{})
response, created, err := result.body, result.statusCode == http.StatusCreated, result.err
hasErr := err != nil
if hasErr != test.Error {
t.Errorf("%d: unexpected error: %t %v", i, test.Error, err)
} else if hasErr && test.Response.StatusCode > 399 {
status, ok := err.(APIStatus)
if !ok {
t.Errorf("%d: response should have been transformable into APIStatus: %v", i, err)
continue
}
if status.Status().Code != test.Response.StatusCode {
t.Errorf("%d: status code did not match response: %#v", i, status.Status())
}
}
if test.ErrFn != nil && !test.ErrFn(err) {
t.Errorf("%d: error function did not match: %v", i, err)
}
if !(test.Data == nil && response == nil) && !api.Semantic.DeepDerivative(test.Data, response) {
t.Errorf("%d: unexpected response: %#v %#v", i, test.Data, response)
}
if test.Created != created {
t.Errorf("%d: expected created %t, got %t", i, test.Created, created)
}
}
}
示例8: gatherAuthInfo
// Negotiate a bearer token with the auth server, or try to reuse one based on the
// information already present. In case of any missing information, ask for user input
// (usually username and password, interactive depending on the Reader).
func (o *LoginOptions) gatherAuthInfo() error {
directClientConfig, err := o.getClientConfig()
if err != nil {
return err
}
// make a copy and use it to avoid mutating the original
t := *directClientConfig
clientConfig := &t
// if a token were explicitly provided, try to use it
if o.tokenProvided() {
clientConfig.BearerToken = o.Token
if osClient, err := client.New(clientConfig); err == nil {
me, err := whoAmI(osClient)
if err == nil {
o.Username = me.Name
o.Config = clientConfig
fmt.Fprintf(o.Out, "Logged into %q as %q using the token provided.\n\n", o.Config.Host, o.Username)
return nil
}
if !kerrors.IsUnauthorized(err) {
return err
}
fmt.Fprintln(o.Out, "The token provided is invalid (probably expired).\n")
}
}
// if a token was provided try to make use of it
// make sure we have a username before continuing
if !o.usernameProvided() {
if cmdutil.IsTerminal(o.Reader) {
for !o.usernameProvided() {
o.Username = cmdutil.PromptForString(o.Reader, "Username: ")
}
}
}
// search all valid contexts with matching server stanzas to see if we have a matching user stanza
kubeconfig := *o.StartingKubeConfig
matchingClusters := getMatchingClusters(*clientConfig, kubeconfig)
for key, context := range o.StartingKubeConfig.Contexts {
if matchingClusters.Has(context.Cluster) {
clientcmdConfig := kclientcmd.NewDefaultClientConfig(kubeconfig, &kclientcmd.ConfigOverrides{CurrentContext: key})
if kubeconfigClientConfig, err := clientcmdConfig.ClientConfig(); err == nil {
if osClient, err := client.New(kubeconfigClientConfig); err == nil {
if me, err := whoAmI(osClient); err == nil && (o.Username == me.Name) {
clientConfig.BearerToken = kubeconfigClientConfig.BearerToken
clientConfig.CertFile = kubeconfigClientConfig.CertFile
clientConfig.CertData = kubeconfigClientConfig.CertData
clientConfig.KeyFile = kubeconfigClientConfig.KeyFile
clientConfig.KeyData = kubeconfigClientConfig.KeyData
o.Config = clientConfig
if key == o.StartingKubeConfig.CurrentContext {
fmt.Fprintf(o.Out, "Already logged into %q as %q.\n\n", o.Config.Host, o.Username)
}
return nil
}
}
}
}
}
// if kubeconfig doesn't already have a matching user stanza...
clientConfig.BearerToken = ""
clientConfig.CertData = []byte{}
clientConfig.KeyData = []byte{}
clientConfig.CertFile = o.CertFile
clientConfig.KeyFile = o.KeyFile
token, err := tokencmd.RequestToken(o.Config, o.Reader, o.Username, o.Password)
if err != nil {
return err
}
clientConfig.BearerToken = token
osClient, err := client.New(clientConfig)
if err != nil {
return err
}
me, err := whoAmI(osClient)
if err != nil {
return err
}
o.Username = me.Name
o.Config = clientConfig
fmt.Fprintln(o.Out, "Login successful.\n")
return nil
}