// IssuerFromAPIRootCA returns the desired issuer given an API root CA object
437368
func IssuerFromAPIRootCA(rootCA *api.RootCA) (*IssuerInfo, error) {
	wantedIssuer := rootCA.CACert
	if rootCA.RootRotation != nil {
		wantedIssuer = rootCA.RootRotation.CACert
	}
	issuerCerts, err := helpers.ParseCertificatesPEM(wantedIssuer)
	if err != nil {
		return nil, errors.Wrap(err, "invalid certificate in cluster root CA object")
	}
	if len(issuerCerts) == 0 {
		return nil, errors.New("invalid certificate in cluster root CA object")
	}
	return &IssuerInfo{
		Subject:   issuerCerts[0].RawSubject,
		PublicKey: issuerCerts[0].RawSubjectPublicKeyInfo,
	}, nil
}
52487
func (component *Component) AttachPublicAPI(group *gin.RouterGroup) {
	group.GET("/authorize", component.rest.AppAuthorize)
	group.POST("/authorize", component.rest.AppAuthorize)
	group.POST("/token", component.rest.AppToken)
	group.POST("/info", component.rest.AppInfo)
	group.GET("/oauth2/code", component.rest.AppAuthCode)
	group.GET("/oauth2/token", component.rest.AppAuthToken)
	group.POST("/oauth2/password", component.rest.AppAuthPassword)
	group.GET("/oauth2/client_credentials", component.rest.AppAuthClientCredentials)
	group.GET("/oauth2/assertion", component.rest.AppAuthAssertion)
	group.GET("/oauth2/refresh", component.rest.AppAuthRefresh)
	group.GET("/oauth2/info", component.rest.AppAuthInfo)
}
251848
func CreateRootCA(rootCN string) (RootCA, error) {
	// Create a simple CSR for the CA using the default CA validator and policy
	req := cfcsr.CertificateRequest{
		CN:         rootCN,
		KeyRequest: &cfcsr.BasicKeyRequest{A: RootKeyAlgo, S: RootKeySize},
		CA:         &cfcsr.CAConfig{Expiry: RootCAExpiration},
	}

	// Generate the CA and get the certificate and private key
	cert, _, key, err := initca.New(&req)
	if err != nil {
		return RootCA{}, err
	}

	rootCA, err := NewRootCA(cert, cert, key, DefaultNodeCertExpiration, nil)
	if err != nil {
		return RootCA{}, err
	}

	return rootCA, nil
}
564659
func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
	if len(rids) == 0 {
		return []*IssueUser{}, nil
	}

	ius := make([]*IssueUser, 0, 10)
	sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed).In("repo_id", rids)
	err := sess.Find(&ius)
	return ius, err
}
1205162
func newAPIRoot(st *state.State, shared *sharedServerContext, facades *facade.Registry, resources *common.Resources, authorizer facade.Authorizer) *apiRoot {
	r := &apiRoot{
		state:       st,
		shared:      shared,
		facades:     facades,
		resources:   resources,
		authorizer:  authorizer,
		objectCache: make(map[objectKey]reflect.Value),
	}
	return r
}
188668
func (c *Component) ExchangeAppKeyForToken(appID, key string) (string, error) {
	issuerID := keys.KeyIssuer(key)
	if issuerID == "" {
		// Take the first configured auth server
		for k := range c.Config.AuthServers {
			issuerID = k
			break
		}
		key = fmt.Sprintf("%s.%s", issuerID, key)
	}
	issuer, ok := c.Config.AuthServers[issuerID]
	if !ok {
		return "", fmt.Errorf("Auth server \"%s\" not registered", issuerID)
	}

	token, err := getTokenFromCache(oauthCache, appID, key)
	if err != nil {
		return "", err
	}

	if token != nil {
		return token.AccessToken, nil
	}

	srv, _ := parseAuthServer(issuer)
	acc := account.New(srv.url)

	if srv.username != "" {
		acc = acc.WithAuth(auth.BasicAuth(srv.username, srv.password))
	} else {
		acc = acc.WithAuth(auth.AccessToken(c.AccessToken))
	}

	token, err = acc.ExchangeAppKeyForToken(appID, key)
	if err != nil {
		return "", err
	}

	saveTokenToCache(oauthCache, appID, key, token)

	return token.AccessToken, nil
}
453343
func (rca *RootCA) IssueAndSaveNewCertificates(kw KeyWriter, cn, ou, org string) (*tls.Certificate, *IssuerInfo, error) {
	csr, key, err := GenerateNewCSR()
	if err != nil {
		return nil, nil, errors.Wrap(err, "error when generating new node certs")
	}

	// Obtain a signed Certificate
	certChain, err := rca.ParseValidateAndSignCSR(csr, cn, ou, org)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to sign node certificate")
	}
	signer, err := rca.Signer()
	if err != nil { // should never happen, since if ParseValidateAndSignCSR did not fail this root CA must have a signer
		return nil, nil, err
	}

	// Create a valid TLSKeyPair out of the PEM encoded private key and certificate
	tlsKeyPair, err := tls.X509KeyPair(certChain, key)
	if err != nil {
		return nil, nil, err
	}

	if err := kw.Write(NormalizePEMs(certChain), key, nil); err != nil {
		return nil, nil, err
	}

	return &tlsKeyPair, &IssuerInfo{
		PublicKey: signer.parsedCert.RawSubjectPublicKeyInfo,
		Subject:   signer.parsedCert.RawSubject,
	}, nil
}
1283106
func rpcAuthorityKind(a backend.Authority) auth.RPCAuthorityKind {
	switch a {
	case backend.AsAnonymous:
		return auth.NoAuth
	case backend.AsService:
		return auth.AsSelf
	case backend.AsUser:
		return auth.AsUser
	default:
		panic(fmt.Errorf("unknown config Authority (%d)", a))
	}
}
488475
func (s *SecurityConfig) UpdateRootCA(rootCA *RootCA) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	// refuse to update the root CA if the current TLS credentials do not validate against it
	if err := validateRootCAAndTLSCert(rootCA, s.certificate); err != nil {
		return err
	}

	s.rootCA = rootCA
	return s.updateTLSCredentials(s.certificate, s.issuerInfo)
}
553250
func (r *rootRotationReconciler) UpdateRootCA(newRootCA *api.RootCA) {
	issuerInfo, err := IssuerFromAPIRootCA(newRootCA)
	if err != nil {
		log.G(r.ctx).WithError(err).Error("unable to update process the current root CA")
		return
	}

	var (
		shouldStartNewLoop, waitForPrevLoop bool
		loopCtx                             context.Context
	)
	r.mu.Lock()
	defer func() {
		r.mu.Unlock()
		if shouldStartNewLoop {
			if waitForPrevLoop {
				r.wg.Wait()
			}
			r.wg.Add(1)
			go r.runReconcilerLoop(loopCtx, newRootCA)
		}
	}()

	// check if the issuer has changed, first
	if reflect.DeepEqual(&r.currentIssuer, issuerInfo) {
		r.currentRootCA = newRootCA
		return
	}
	// If the issuer has changed, iterate through all the nodes to figure out which ones need rotation
	if newRootCA.RootRotation != nil {
		var nodes []*api.Node
		r.store.View(func(tx store.ReadTx) {
			nodes, err = store.FindNodes(tx, store.All)
		})
		if err != nil {
			log.G(r.ctx).WithError(err).Error("unable to list nodes, so unable to process the current root CA")
			return
		}

		// from here on out, there will be no more errors that cause us to have to abandon updating the Root CA,
		// so we can start making changes to r's fields
		r.unconvergedNodes = make(map[string]*api.Node)
		for _, n := range nodes {
			if !hasIssuer(n, issuerInfo) {
				r.unconvergedNodes[n.ID] = n
			}
		}
		shouldStartNewLoop = true
		if r.cancel != nil { // there's already a loop going, so cancel it
			r.cancel()
			waitForPrevLoop = true
		}
		loopCtx, r.cancel = context.WithCancel(r.ctx)
	} else {
		r.unconvergedNodes = nil
	}
	r.currentRootCA = newRootCA
	r.currentIssuer = *issuerInfo
}
23616
func IsReseller(token string) (*models.Principal, error) {
	claims, err := parseAndCheckToken(token)
	if err == nil {
		if claims.Issuer == issuerName && claims.Id != "" {
			isReseller := false
			for _, role := range claims.Roles {
				if role == "reseller" {
					isReseller = true
					break
				}
			}
			if isReseller {
				return &models.Principal{
					Name: claims.Id,
				}, nil
			}
			return nil, errors.New(403, "Forbidden: insufficient API key privileges")
		}
	}
	return nil, errors.New(401, "Unauthorized: invalid API key token: %v", err)
}
172073
func (d *dualListener) openAPIPort(topic string, conn apiserver.APIConnection, err error) {
	if err != nil {
		logger.Errorf("programming error: %v", err)
		return
	}
	// We are wanting to make sure that the api-caller has connected before we
	// open the api port. Each api connection is published with the origin tag.
	// Any origin that matches our agent name means that someone has connected
	// to us. We need to also check which agent connected as it is possible that
	// one of the other HA controller could connect before we connect to
	// ourselves.
	if conn.Origin != d.agentName || conn.AgentTag != d.agentName {
		return
	}

	d.unsub()
	if d.delay > 0 {
		d.mu.Lock()
		d.status = "waiting prior to opening agent port"
		d.mu.Unlock()
		logger.Infof("waiting for %s before allowing api connections", d.delay)
		<-d.clock.After(d.delay)
	}

	d.mu.Lock()
	defer d.mu.Unlock()
	// Make sure we haven't been closed already.
	select {
	case <-d.done:
		return
	default:
		// We are all good.
	}

	listenAddr := net.JoinHostPort("", strconv.Itoa(d.apiPort))
	listener, err := net.Listen("tcp", listenAddr)
	if err != nil {
		select {
		case d.errors <- err:
		case <-d.done:
			logger.Errorf("can't open api port: %v, but worker exiting already", err)
		}
		return
	}

	logger.Infof("listening for api connections on %q", listener.Addr())
	d.apiListener = listener
	go d.accept(listener)
	d.status = ""
}
1110264
func (k *Key) Issuer() string {
	q := k.url.Query()

	issuer := q.Get("issuer")

	if issuer != "" {
		return issuer
	}

	p := strings.TrimPrefix(k.url.Path, "/")
	i := strings.Index(p, ":")

	if i == -1 {
		return ""
	}

	return p[:i]
}
1130791
func NewStateCAASOperatorUpgraderAPI(ctx facade.Context) (*API, error) {
	authorizer := ctx.Auth()
	broker, err := stateenvirons.GetNewCAASBrokerFunc(caas.New)(ctx.State())
	if err != nil {
		return nil, errors.Annotate(err, "getting caas client")
	}
	return NewCAASOperatorUpgraderAPI(authorizer, broker)
}
833910
func (s *VPCRouterSetting) FindRemoteAccessUser(userName string, password string) (int, *VPCRouterRemoteAccessUsersConfig) {
	for i, c := range s.RemoteAccessUsers.Config {
		if c.UserName == userName && c.Password == password {
			return i, c
		}
	}
	return -1, nil
}
720165
func (client *Client) GrantAccountPrivilege(args *GrantAccountPrivilegeArgs) (resp *GrantAccountPrivilegeResponse, err error) {
	response := GrantAccountPrivilegeResponse{}
	err = client.Invoke("GrantAccountPrivilege", args, &response)

	if err != nil {
		return nil, err
	}
	return &response, nil
}
926413
func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
	wellKnown := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
	req, err := http.NewRequest("GET", wellKnown, nil)
	if err != nil {
		return nil, err
	}
	resp, err := doRequest(ctx, req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("unable to read response body: %v", err)
	}

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("%s: %s", resp.Status, body)
	}

	var p providerJSON
	err = unmarshalResp(resp, body, &p)
	if err != nil {
		return nil, fmt.Errorf("oidc: failed to decode provider discovery object: %v", err)
	}

	if p.Issuer != issuer {
		return nil, fmt.Errorf("oidc: issuer did not match the issuer returned by provider, expected %q got %q", issuer, p.Issuer)
	}
	return &Provider{
		issuer:       p.Issuer,
		authURL:      p.AuthURL,
		tokenURL:     p.TokenURL,
		userInfoURL:  p.UserInfoURL,
		rawClaims:    body,
		remoteKeySet: NewRemoteKeySet(ctx, p.JWKSURL),
	}, nil
}