/* validateGithubAuthRequest validates Github auth callback redirect

   POST /:version/github/requests/validate

   Success response: githubAuthRawResponse
*/
779610
func (s *APIServer) validateGithubAuthCallback(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) {
	var req validateGithubAuthCallbackReq
	if err := httplib.ReadJSON(r, &req); err != nil {
		return nil, trace.Wrap(err)
	}
	response, err := auth.ValidateGithubAuthCallback(req.Query)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	raw := githubAuthRawResponse{
		Username: response.Username,
		Identity: response.Identity,
		Cert:     response.Cert,
		TLSCert:  response.TLSCert,
		Req:      response.Req,
	}
	if response.Session != nil {
		rawSession, err := services.GetWebSessionMarshaler().MarshalWebSession(
			response.Session, services.WithVersion(version), services.PreserveResourceID())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		raw.Session = rawSession
	}
	raw.HostSigners = make([]json.RawMessage, len(response.HostSigners))
	for i, ca := range response.HostSigners {
		data, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(
			ca, services.WithVersion(version), services.PreserveResourceID())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		raw.HostSigners[i] = data
	}
	return &raw, nil
}
1106312
func (r *LogRequest) Validate() error {
	switch {
	case r.Project == "":
		return errors.New("project is required")
	case r.PageSize < 0:
		return errors.New("page size must not be negative")
	case r.Committish == "":
		return errors.New("committish is required")
	case strings.Contains(r.Committish, ".."):
		return errors.New("committish cannot contain \"..\"; use Ancestor instead")
	default:
		return nil
	}
}
531023
func NewGitHub(ctx *context.Context) (Client, error) {
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: ctx.Token},
	)
	httpClient := oauth2.NewClient(ctx, ts)
	base := httpClient.Transport.(*oauth2.Transport).Base
	// nolint: govet
	if &base != nil {
		base = http.DefaultTransport
	}
	// nolint: gosec
	base.(*http.Transport).TLSClientConfig = &tls.Config{
		InsecureSkipVerify: ctx.Config.GitHubURLs.SkipTLSVerify,
	}
	httpClient.Transport.(*oauth2.Transport).Base = base
	client := github.NewClient(httpClient)
	if ctx.Config.GitHubURLs.API != "" {
		api, err := url.Parse(ctx.Config.GitHubURLs.API)
		if err != nil {
			return &githubClient{}, err
		}
		upload, err := url.Parse(ctx.Config.GitHubURLs.Upload)
		if err != nil {
			return &githubClient{}, err
		}
		client.BaseURL = api
		client.UploadURL = upload
	}

	return &githubClient{client: client}, nil
}
931341
func (c *Client) CreateGithubAuthRequest(req services.GithubAuthRequest) (*services.GithubAuthRequest, error) {
	out, err := c.PostJSON(c.Endpoint("github", "requests", "create"),
		createGithubAuthRequestReq{Req: req})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var response services.GithubAuthRequest
	if err := json.Unmarshal(out.Bytes(), &response); err != nil {
		return nil, trace.Wrap(err)
	}
	return &response, nil
}
702808
func (as *AuthenticationService) UsingGithubToken(githubToken string) (AccessToken, *http.Response, error) {
	if githubToken == "" {
		return "", nil, fmt.Errorf("unable to authenticate client; empty github token provided")
	}
	var u string = "/auth/github"
	var b map[string]string = map[string]string{"github_token": githubToken}

	req, err := as.client.NewRequest("POST", u, b, nil)
	if err != nil {
		return "", nil, err
	}

	atr := &accessTokenResponse{}
	resp, err := as.client.Do(req, atr)
	if err != nil {
		return "", nil, err
	}

	as.UsingTravisToken(string(atr.Token))

	return atr.Token, resp, err
}
1301735
func (a authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	aType := getRequestAuthType(r)
	if isSupportedS3AuthType(aType) {
		// Let top level caller validate for anonymous and known signed requests.
		a.handler.ServeHTTP(w, r)
		return
	} else if aType == authTypeJWT {
		// Validate Authorization header if its valid for JWT request.
		if _, _, authErr := webRequestAuthenticate(r); authErr != nil {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		a.handler.ServeHTTP(w, r)
		return
	} else if aType == authTypeSTS {
		a.handler.ServeHTTP(w, r)
		return
	}
	writeErrorResponse(context.Background(), w, errorCodes.ToAPIErr(ErrSignatureVersionNotSupported), r.URL, guessIsBrowserReq(r))
}
488280
func (o *MultiAuthExampleAPI) Validate() error {
	var unregistered []string

	if o.JSONConsumer == nil {
		unregistered = append(unregistered, "JSONConsumer")
	}

	if o.JSONProducer == nil {
		unregistered = append(unregistered, "JSONProducer")
	}

	if o.HasRoleAuth == nil {
		unregistered = append(unregistered, "HasRoleAuth")
	}

	if o.IsRegisteredAuth == nil {
		unregistered = append(unregistered, "IsRegisteredAuth")
	}

	if o.IsResellerAuth == nil {
		unregistered = append(unregistered, "XCustomKeyAuth")
	}

	if o.IsResellerQueryAuth == nil {
		unregistered = append(unregistered, "CustomKeyAsQueryAuth")
	}

	if o.AddOrderHandler == nil {
		unregistered = append(unregistered, "AddOrderHandler")
	}

	if o.GetAccountHandler == nil {
		unregistered = append(unregistered, "GetAccountHandler")
	}

	if o.GetItemsHandler == nil {
		unregistered = append(unregistered, "GetItemsHandler")
	}

	if o.GetOrderHandler == nil {
		unregistered = append(unregistered, "GetOrderHandler")
	}

	if o.GetOrdersForItemHandler == nil {
		unregistered = append(unregistered, "GetOrdersForItemHandler")
	}

	if len(unregistered) > 0 {
		return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", "))
	}

	return nil
}
324581
func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
	token := obj.(*oauthapi.OAuthClient)
	return validation.ValidateClient(token)
}
940477
func (o *AuthSampleAPI) Validate() error {
	var unregistered []string

	if o.JSONConsumer == nil {
		unregistered = append(unregistered, "JSONConsumer")
	}

	if o.JSONProducer == nil {
		unregistered = append(unregistered, "JSONProducer")
	}

	if o.KeyAuth == nil {
		unregistered = append(unregistered, "XTokenAuth")
	}

	if o.CustomersCreateHandler == nil {
		unregistered = append(unregistered, "customers.CreateHandler")
	}

	if o.CustomersGetIDHandler == nil {
		unregistered = append(unregistered, "customers.GetIDHandler")
	}

	if len(unregistered) > 0 {
		return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", "))
	}

	return nil
}
6948
func NewGitHubRepoVFS(ctx context.Context, repo, rev string) (*ArchiveFS, error) {
	if !githubRepoRx.MatchString(repo) {
		return nil, fmt.Errorf(`invalid GitHub repo %q: must be "github.com/user/repo"`, repo)
	}

	url := fmt.Sprintf("https://codeload.%s/zip/%s", repo, rev)
	return NewZipVFS(ctx, url, ghFetch.Inc, ghFetchFailed.Inc, false)
}
279036
func (authHandler *unionAuthRequestHandler) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {
	var errlist []error
	for _, currAuthRequestHandler := range authHandler.Handlers {
		resp, ok, err := currAuthRequestHandler.AuthenticateRequest(req)
		if err != nil {
			if authHandler.FailOnError {
				return resp, ok, err
			}
			errlist = append(errlist, err)
			continue
		}

		if ok {
			return resp, ok, err
		}
	}

	return nil, false, utilerrors.NewAggregate(errlist)
}
1142512
func (g *GitHub) createGitHubClient(ctx context.Context) (*github.Client, error) {
	httpClient := &http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyFromEnvironment,
		},
		Timeout: g.HTTPTimeout.Duration,
	}

	g.obfusticatedToken = "Unauthenticated"

	if g.AccessToken != "" {
		tokenSource := oauth2.StaticTokenSource(
			&oauth2.Token{AccessToken: g.AccessToken},
		)
		oauthClient := oauth2.NewClient(ctx, tokenSource)
		ctx = context.WithValue(ctx, oauth2.HTTPClient, oauthClient)

		g.obfusticatedToken = g.AccessToken[0:4] + "..." + g.AccessToken[len(g.AccessToken)-3:]

		return github.NewClient(oauthClient), nil
	}

	return github.NewClient(httpClient), nil
}
415807
func (s *AuthServer) CreateGithubAuthRequest(req services.GithubAuthRequest) (*services.GithubAuthRequest, error) {
	connector, err := s.Identity.GetGithubConnector(req.ConnectorID, true)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	client, err := s.getGithubOAuth2Client(connector)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	req.StateToken, err = utils.CryptoRandomHex(TokenLenBytes)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	req.RedirectURL = client.AuthCodeURL(req.StateToken, "", "")
	log.WithFields(logrus.Fields{trace.Component: "github"}).Debugf(
		"Redirect URL: %v.", req.RedirectURL)
	req.SetTTL(s.GetClock(), defaults.GithubAuthRequestTTL)
	err = s.Identity.CreateGithubAuthRequest(req)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &req, nil
}
611304
func Validate(req interface{}) error {
	// validate req message
	if err := v.Struct(req); err != nil {
		if v, ok := err.(validator.ValidationErrors); ok {
			err = v
		}
		return status.Errorf(codes.InvalidArgument, "Request validation failed: %s", err)
	}
	return nil
}
666741
func (s *CodeDestination) SetGitHub(v *GitHubCodeDestination) *CodeDestination {
	s.GitHub = v
	return s
}
115691
func (s *APIServer) createGithubAuthRequest(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) {
	var req createGithubAuthRequestReq
	if err := httplib.ReadJSON(r, &req); err != nil {
		return nil, trace.Wrap(err)
	}
	response, err := auth.CreateGithubAuthRequest(req.Req)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return response, nil
}
574118
func (s Signer) AuthRequest(id, key string, r *http.Request) error {
	sig, err := s.buildSignature(id, key, r)
	if err != nil {
		return err
	}

	r.Header.Add(headerAuthorization, authScheme+sig.String())

	return nil
}