// ValidateOIDCAuthCallback is called by the proxy to check OIDC query parameters
// returned by OIDC Provider, if everything checks out, auth server
// will respond with OIDCAuthResponse, otherwise it will return error
511778
func (a *AuthServer) ValidateOIDCAuthCallback(q url.Values) (*OIDCAuthResponse, error) {
	re, err := a.validateOIDCAuthCallback(q)
	if err != nil {
		a.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{
			events.LoginMethod:        events.LoginMethodOIDC,
			events.AuthAttemptSuccess: false,
			// log the original internal error in audit log
			events.AuthAttemptErr: trace.Unwrap(err).Error(),
		})
	} else {
		a.EmitAuditEvent(events.UserSSOLogin, events.EventFields{
			events.EventUser:          re.Username,
			events.AuthAttemptSuccess: true,
			events.LoginMethod:        events.LoginMethodOIDC,
		})
	}
	return re, err
}
1205337
func (c *Client) CreateOIDCAuthRequest(req services.OIDCAuthRequest) (*services.OIDCAuthRequest, error) {
	out, err := c.PostJSON(c.Endpoint("oidc", "requests", "create"), createOIDCAuthRequestReq{
		Req: req,
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var response *services.OIDCAuthRequest
	if err := json.Unmarshal(out.Bytes(), &response); err != nil {
		return nil, trace.Wrap(err)
	}
	return response, nil
}
1338201
func (s *IdentityService) CreateOIDCAuthRequest(req services.OIDCAuthRequest, ttl time.Duration) error {
	if err := req.Check(); err != nil {
		return trace.Wrap(err)
	}
	value, err := json.Marshal(req)
	if err != nil {
		return trace.Wrap(err)
	}
	item := backend.Item{
		Key:     backend.Key(webPrefix, connectorsPrefix, oidcPrefix, requestsPrefix, req.StateToken),
		Value:   value,
		Expires: backend.Expiry(s.Clock(), ttl),
	}
	_, err = s.Create(context.TODO(), item)
	if err != nil {
		return trace.Wrap(err)
	}
	return nil
}
43742
func requiresAuthentication(callName string) bool {
	for _, name := range NonAuthenticatingCalls {
		if name == callName {
			return false
		}
	}
	return true
}
1096345
func (i *Identity) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error {
	cert, ok := key.(*ssh.Certificate)
	if !ok {
		return trace.BadParameter("only host certificates supported")
	}

	// Loop over all CAs and see if any of them signed the certificate.
	for _, k := range i.SSHCACertBytes {
		pubkey, _, _, _, err := ssh.ParseAuthorizedKey(k)
		if err != nil {
			return trace.Wrap(err)
		}
		if sshutils.KeysEqual(cert.SignatureKey, pubkey) {
			return nil
		}
	}

	return trace.BadParameter("no matching keys found")
}
141088
func validateStateToken(c context.Context, stateTok string) (map[string]string, error) {
	return openIDStateToken.Validate(c, stateTok, nil)
}
1107292
func (c *Client) ValidateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error) {
	out, err := c.PostJSON(c.Endpoint("github", "requests", "validate"),
		validateGithubAuthCallbackReq{Query: q})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var rawResponse githubAuthRawResponse
	if err := json.Unmarshal(out.Bytes(), &rawResponse); err != nil {
		return nil, trace.Wrap(err)
	}
	response := GithubAuthResponse{
		Username: rawResponse.Username,
		Identity: rawResponse.Identity,
		Cert:     rawResponse.Cert,
		Req:      rawResponse.Req,
		TLSCert:  rawResponse.TLSCert,
	}
	if len(rawResponse.Session) != 0 {
		session, err := services.GetWebSessionMarshaler().UnmarshalWebSession(
			rawResponse.Session)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		response.Session = session
	}
	response.HostSigners = make([]services.CertAuthority, len(rawResponse.HostSigners))
	for i, raw := range rawResponse.HostSigners {
		ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(raw)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		response.HostSigners[i] = ca
	}
	return &response, nil
}
321448
func (jolokiaClient *JolokiaClient) executePostRequestCallback(pattern string, wrapper func() ([]byte, error)) (string, error) {
	jsonReq, wrapError := wrapper()
	if wrapError != nil {
		return "", fmt.Errorf("JSON Wrap Failed: %v", wrapError)
	}
	requestUrl := jolokiaClient.url
	if pattern != "" {
		requestUrl = requestUrl + "/?" + pattern
	}
	request := &httpRequest{Url: requestUrl, Body: jsonReq}
	response, httpErr := performPostRequest(request, jolokiaClient.user, jolokiaClient.pass)
	if httpErr != nil {
		return "", fmt.Errorf("HTTP Request Failed: %v", httpErr)
	}
	if response.StatusCode != 200 {
		return "", fmt.Errorf("HTTP Request Error Code: %v", response.Status)
	}
	jolokiaResponse := string(response.Body)
	return jolokiaResponse, nil
}
712895
func domainEventReasonCallback(c C.virConnectPtr, d C.virDomainPtr,
	reason int, opaque int) {

	domain := VirDomain{ptr: d}
	connection := VirConnection{ptr: c}

	eventDetails := DomainReasonEvent{
		Reason: reason,
	}

	callDomainCallbackId(opaque, &connection, &domain, eventDetails)
}
1245161
func (r User_Customer_OpenIdConnect) ValidateAuthenticationToken(authenticationToken *datatypes.Container_User_Authentication_Token) (resp datatypes.Container_User_Customer_Portal_Token, err error) {
	params := []interface{}{
		authenticationToken,
	}
	err = r.Session.DoRequest("SoftLayer_User_Customer_OpenIdConnect", "validateAuthenticationToken", params, &r.Options, &resp)
	return
}
704687
func (m *GrpcService_GoogleGrpc_CallCredentials) Validate() error {
	if m == nil {
		return nil
	}

	switch m.CredentialSpecifier.(type) {

	case *GrpcService_GoogleGrpc_CallCredentials_AccessToken:
		// no validation rules for AccessToken

	case *GrpcService_GoogleGrpc_CallCredentials_GoogleComputeEngine:

		{
			tmp := m.GetGoogleComputeEngine()

			if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return GrpcService_GoogleGrpc_CallCredentialsValidationError{
						field:  "GoogleComputeEngine",
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	case *GrpcService_GoogleGrpc_CallCredentials_GoogleRefreshToken:
		// no validation rules for GoogleRefreshToken

	case *GrpcService_GoogleGrpc_CallCredentials_ServiceAccountJwtAccess:

		{
			tmp := m.GetServiceAccountJwtAccess()

			if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return GrpcService_GoogleGrpc_CallCredentialsValidationError{
						field:  "ServiceAccountJwtAccess",
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	case *GrpcService_GoogleGrpc_CallCredentials_GoogleIam:

		{
			tmp := m.GetGoogleIam()

			if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return GrpcService_GoogleGrpc_CallCredentialsValidationError{
						field:  "GoogleIam",
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	case *GrpcService_GoogleGrpc_CallCredentials_FromPlugin:

		{
			tmp := m.GetFromPlugin()

			if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return GrpcService_GoogleGrpc_CallCredentialsValidationError{
						field:  "FromPlugin",
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	default:
		return GrpcService_GoogleGrpc_CallCredentialsValidationError{
			field:  "CredentialSpecifier",
			reason: "value is required",
		}

	}

	return nil
}
448159
func (c *Client) ValidateCredentials(user user.User) (bool, error) {
	result := false
	err := c.call("ValidateCredentials", user, &result)
	return result, err
}
443038
func (rd *Redirector) wrapCallback(fn func(http.ResponseWriter, *http.Request) (*auth.SSHLoginResponse, error)) http.Handler {
	clone := *rd.proxyURL
	clone.Path = "/web/msg/error/login_failed"
	errorURL := clone.String()
	clone.Path = "/web/msg/info/login_success"
	successURL := clone.String()

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		response, err := fn(w, r)
		if err != nil {
			if trace.IsNotFound(err) {
				http.NotFound(w, r)
				return
			}
			select {
			case rd.errorC <- err:
			case <-rd.context.Done():
				http.Redirect(w, r, errorURL, http.StatusFound)
				return
			}
			http.Redirect(w, r, errorURL, http.StatusFound)
			return
		}
		select {
		case rd.responseC <- response:
		case <-rd.context.Done():
			http.Redirect(w, r, errorURL, http.StatusFound)
			return
		}
		http.Redirect(w, r, successURL, http.StatusFound)
	})
}
489667
func (j *PKIJWTVerifier) Callback(r *http.Request) (string, string, int, error) {
	return "", "", 0, nil
}
882408
func ValidateAuthTokenWithCtxOrReq(
	ctx types.Context,
	config *types.AuthConfig,
	req *http.Request) (*types.AuthToken, error) {

	tok, err := ValidateAuthTokenWithCtx(ctx, config)
	if err != nil {
		return nil, err
	}
	if tok != nil {
		return tok, nil
	}
	return ValidateAuthTokenWithReq(ctx, config, req)
}
510743
func (p *Provider) handleCallback(rw http.ResponseWriter, req *http.Request, _ router.Params) error {
	// oauth handshake
	code := req.FormValue("code")
	accessToken, err := p.Config.Exchange(oauth2.NoContext, code)
	if err != nil {
		return errors.Wrap(err)
	}
	var state string
	encState := req.FormValue("state")
	if encState != "" {
		stateByte, err := base64.StdEncoding.DecodeString(encState)
		if err != nil {
			return errors.New("error decoding state: %s", err)
		}
		state = string(stateByte)
	}
	err = p.PostCallback(req, rw, accessToken, state)
	if err != nil {
		return errors.Wrap(err)
	}
	return nil
}
379653
func (v *TokenVerifier) Callback(r *http.Request) (string, string, int, error) {

	// We first validate that the callback state matches the original redirect
	// state. We clean up the cache once it is validated. During this process
	// we recover the original URL that initiated the protocol. This allows
	// us to redirect the client to their original request.
	receivedState := r.URL.Query().Get("state")
	originURL, err := stateCache.Get(receivedState)
	if err != nil {
		return "", "", http.StatusBadRequest, fmt.Errorf("bad state")
	}
	stateCache.Remove(receivedState)

	// We exchange the authorization code with an OAUTH token. This is the main
	// step where the OAUTH provider will match the code to the token.
	oauth2Token, err := v.clientConfig.Exchange(r.Context(), r.URL.Query().Get("code"), oauth2.AccessTypeOffline)
	if err != nil {
		return "", "", http.StatusInternalServerError, fmt.Errorf("bad code: %s", err)
	}

	// We extract the rawID token.
	rawIDToken, ok := oauth2Token.Extra("id_token").(string)
	if !ok {
		return "", "", http.StatusInternalServerError, fmt.Errorf("bad ID")
	}

	if err := tokenCache.SetWithExpire(
		rawIDToken,
		&clientData{
			tokenSource: v.clientConfig.TokenSource(context.Background(), oauth2Token),
			expiry:      oauth2Token.Expiry,
		},
		time.Until(oauth2Token.Expiry.Add(3600*time.Second)),
	); err != nil {
		return "", "", http.StatusInternalServerError, fmt.Errorf("failed to insert token in the cache: %s", err)
	}

	return rawIDToken, originURL.(string), http.StatusTemporaryRedirect, nil
}