// AssertCertificateHasClientAuthUsage is a utility function for kubeadm testing that asserts if a given certificate has
// the expected ExtKeyUsageClientAuth
5045
func AssertCertificateHasClientAuthUsage(t *testing.T, cert *x509.Certificate) {
	for i := range cert.ExtKeyUsage {
		if cert.ExtKeyUsage[i] == x509.ExtKeyUsageClientAuth {
			return
		}
	}
	t.Error("cert has not ClientAuth usage as expected")
}
1167174
func OAuth2AuthorizeExplicitFactory(config *Config, storage interface{}, strategy interface{}) interface{} {
	return &oauth2.AuthorizeExplicitGrantHandler{
		AccessTokenStrategy:      strategy.(oauth2.AccessTokenStrategy),
		RefreshTokenStrategy:     strategy.(oauth2.RefreshTokenStrategy),
		AuthorizeCodeStrategy:    strategy.(oauth2.AuthorizeCodeStrategy),
		CoreStorage:              storage.(oauth2.CoreStorage),
		AuthCodeLifespan:         config.GetAuthorizeCodeLifespan(),
		RefreshTokenLifespan:     config.GetRefreshTokenLifespan(),
		AccessTokenLifespan:      config.GetAccessTokenLifespan(),
		ScopeStrategy:            config.GetScopeStrategy(),
		AudienceMatchingStrategy: config.GetAudienceStrategy(),
		TokenRevocationStorage:   storage.(oauth2.TokenRevocationStorage),
		IsRedirectURISecure:      config.GetRedirectSecureChecker(),
	}
}
1158494
func (client *Client) verifyAccessToken() error {
	if len(client.AccessToken) > 0 {
		return nil
	} else {
		return fmt.Errorf("missing access token")
	}
}
63248
func (c *IdentityConfig) CAClientKey(org string) ([]byte, bool) {
	caConfigs, ok := c.caConfigsByOrg[strings.ToLower(org)]
	if ok {
		//for now, we're only loading the first Cert Authority by default.
		return caConfigs[0].TLSCAClientKey, true
	}

	return nil, false
}
1227623
func (ch Challenge) CheckConsistencyForClientOffer() error {
	if err := ch.checkConsistency(); err != nil {
		return err
	}

	// Before completion, the key authorization field should be empty
	if ch.ProvidedKeyAuthorization != "" {
		return fmt.Errorf("A response to this challenge was already submitted.")
	}
	return nil
}
79590
func (s *RestoreFromClusterSnapshotInput) SetHsmClientCertificateIdentifier(v string) *RestoreFromClusterSnapshotInput {
	s.HsmClientCertificateIdentifier = &v
	return s
}
322472
func GenerateCertificate(authServer *AuthServer, identity TestIdentity) ([]byte, []byte, error) {
	switch id := identity.I.(type) {
	case LocalUser:
		user, err := authServer.GetUser(id.Username)
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		roles, err := services.FetchRoles(user.GetRoles(), authServer, user.GetTraits())
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		if identity.TTL == 0 {
			identity.TTL = time.Hour
		}
		priv, pub, err := authServer.GenerateKeyPair("")
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		certs, err := authServer.generateUserCert(certRequest{
			publicKey: pub,
			user:      user,
			roles:     roles,
			ttl:       identity.TTL,
			usage:     identity.AcceptedUsage,
		})
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		return certs.tls, priv, nil
	case BuiltinRole:
		keys, err := authServer.GenerateServerKeys(GenerateServerKeysRequest{
			HostID:   id.Username,
			NodeName: id.Username,
			Roles:    teleport.Roles{id.Role},
		})
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		return keys.TLSCert, keys.Key, nil
	default:
		return nil, nil, trace.BadParameter("identity of unknown type %T is unsupported", identity)
	}
}
1227452
func (m MockContext) EnrollmentCertificate() []byte {
	if m.SigningIdentity == nil {
		return nil
	}
	return m.SigningIdentity.EnrollmentCertificate()
}
1011722
func (s *CA) CreateCertAuthority(ca services.CertAuthority) error {
	if err := ca.Check(); err != nil {
		return trace.Wrap(err)
	}
	value, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(ca)
	if err != nil {
		return trace.Wrap(err)
	}
	item := backend.Item{
		Key:     backend.Key(authoritiesPrefix, string(ca.GetType()), ca.GetName()),
		Value:   value,
		Expires: ca.Expiry(),
	}

	_, err = s.Create(context.TODO(), item)
	if err != nil {
		if trace.IsAlreadyExists(err) {
			return trace.AlreadyExists("cluster %q already exists", ca.GetName())
		}
		return trace.Wrap(err)
	}
	return nil
}
574436
func (*denyAuthenticator) AuthenticateAssertion(assertionType, data string) (*authenticator.Response, bool, error) {
	return nil, false, nil
}
995387
func (s *SimpleMonitor) SetHealthCheckSSLCertificate(remainingDays int) {
	// set default
	if remainingDays < 0 {
		remainingDays = 30
	}
	s.Settings.SimpleMonitor.HealthCheck = &SimpleMonitorHealthCheck{
		Protocol:      "sslcertificate",
		RemainingDays: remainingDays,
	}
}
1221045
func (a *AuthServer) activateCertAuthority(t services.TrustedCluster) error {
	err := a.ActivateCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: t.GetName()})
	if err != nil {
		return trace.Wrap(err)
	}

	return trace.Wrap(a.ActivateCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: t.GetName()}))
}
1104326
func GenerateClientCertificate() (*Certificate, error) {
	cert, key, err := shared.GenerateMemCert(true)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return NewCertificate(cert, key), nil
}
103070
func NewCertificateAuthorityImpl(
	config ca_config.CAConfig,
	sa certificateStorage,
	pa core.PolicyAuthority,
	clk clock.Clock,
	stats metrics.Scope,
	issuers []Issuer,
	keyPolicy goodkey.KeyPolicy,
	logger blog.Logger,
	orphanQueue *goque.Queue,
) (*CertificateAuthorityImpl, error) {
	var ca *CertificateAuthorityImpl
	var err error

	if config.SerialPrefix <= 0 || config.SerialPrefix >= 256 {
		err = errors.New("Must have a positive non-zero serial prefix less than 256 for CA.")
		return nil, err
	}

	// CFSSL requires processing JSON configs through its own LoadConfig, so we
	// serialize and then deserialize.
	cfsslJSON, err := json.Marshal(config.CFSSL)
	if err != nil {
		return nil, err
	}
	cfsslConfigObj, err := cfsslConfig.LoadConfig(cfsslJSON)
	if err != nil {
		return nil, err
	}

	if config.LifespanOCSP.Duration == 0 {
		return nil, errors.New("Config must specify an OCSP lifespan period.")
	}

	for _, profile := range cfsslConfigObj.Signing.Profiles {
		if len(profile.IssuerURL) > 1 {
			return nil, errors.New("only one issuer_url supported")
		}
	}

	internalIssuers, err := makeInternalIssuers(
		issuers,
		cfsslConfigObj.Signing,
		config.LifespanOCSP.Duration)
	if err != nil {
		return nil, err
	}
	defaultIssuer := internalIssuers[issuers[0].Cert.Subject.CommonName]

	rsaProfile := config.RSAProfile
	ecdsaProfile := config.ECDSAProfile

	if rsaProfile == "" || ecdsaProfile == "" {
		return nil, errors.New("must specify rsaProfile and ecdsaProfile")
	}

	csrExtensionCount := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "csrExtensions",
			Help: "Number of CSRs with extensions of the given category",
		},
		[]string{csrExtensionCategory})
	stats.MustRegister(csrExtensionCount)

	signatureCount := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "signatures",
			Help: "Number of signatures",
		},
		[]string{"purpose"})
	stats.MustRegister(signatureCount)

	ca = &CertificateAuthorityImpl{
		sa:                sa,
		pa:                pa,
		issuers:           internalIssuers,
		defaultIssuer:     defaultIssuer,
		rsaProfile:        rsaProfile,
		ecdsaProfile:      ecdsaProfile,
		prefix:            config.SerialPrefix,
		clk:               clk,
		log:               logger,
		stats:             stats,
		keyPolicy:         keyPolicy,
		forceCNFromSAN:    !config.DoNotForceCN, // Note the inversion here
		enableMustStaple:  config.EnableMustStaple,
		signatureCount:    signatureCount,
		csrExtensionCount: csrExtensionCount,
		orphanQueue:       orphanQueue,
	}

	if config.Expiry == "" {
		return nil, errors.New("Config must specify an expiry period.")
	}
	ca.validityPeriod, err = time.ParseDuration(config.Expiry)
	if err != nil {
		return nil, err
	}

	// TODO(briansmith): Make the backdate setting mandatory after the
	// production ca.json has been updated to include it. Until then, manually
	// default to 1h, which is the backdating duration we currently use.
	ca.backdate = config.Backdate.Duration
	if ca.backdate == 0 {
		ca.backdate = time.Hour
	}

	ca.maxNames = config.MaxNames

	return ca, nil
}
1225974
func (c *ACMPCA) WaitUntilCertificateIssued(input *GetCertificateInput) error {
	return c.WaitUntilCertificateIssuedWithContext(aws.BackgroundContext(), input)
}
180762
func (s *ModifyClusterInput) SetHsmClientCertificateIdentifier(v string) *ModifyClusterInput {
	s.HsmClientCertificateIdentifier = &v
	return s
}
1249828
func (c IdentityContext) GetCertificate() (*ssh.Certificate, error) {
	k, _, _, _, err := ssh.ParseAuthorizedKey(c.Certificate)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	cert, ok := k.(*ssh.Certificate)
	if !ok {
		return nil, trace.BadParameter("not a certificate")
	}

	return cert, nil
}