// validSelfAuthenticatedPOST checks that a given POST request has a valid JWS
// using `validSelfAuthenticatedJWS`.
430156
func (wfe *WebFrontEndImpl) validSelfAuthenticatedPOST(
	request *http.Request,
	logEvent *web.RequestEvent) ([]byte, *jose.JSONWebKey, *probs.ProblemDetails) {
	// Parse the JWS from the POST request
	jws, prob := wfe.parseJWSRequest(request)
	if prob != nil {
		return nil, nil, prob
	}
	// Extract and validate the embedded JWK from the parsed JWS
	return wfe.validSelfAuthenticatedJWS(jws, request, logEvent)
}
440711
func (r Account_ProofOfConcept) GetSubmittedRequest(requestId *int) (resp datatypes.Container_Account_ProofOfConcept_Review, err error) {
	params := []interface{}{
		requestId,
	}
	err = r.Session.DoRequest("SoftLayer_Account_ProofOfConcept", "getSubmittedRequest", params, &r.Options, &resp)
	return
}
371438
func builtinJWTVerify(a ast.Value, b ast.Value, verify func(publicKey interface{}, digest []byte, signature []byte) error) (ast.Value, error) {
	// Decode the JSON Web Token
	token, err := decodeJWT(a)
	if err != nil {
		return nil, err
	}

	// Process PEM encoded certificate input
	astCertificate, err := builtins.StringOperand(b, 2)
	if err != nil {
		return nil, err
	}
	key, err := getKeyFromCert(string(astCertificate))
	if err != nil {
		return nil, err
	}

	signature, err := token.decodeSignature()
	if err != nil {
		return nil, err
	}

	// Validate the JWT signature
	err = verify(key,
		getInputSHA([]byte(token.header+"."+token.payload)),
		[]byte(signature))

	if err != nil {
		return ast.Boolean(false), nil
	}
	return ast.Boolean(true), nil
}
794963
func (wfe *WebFrontEndImpl) parseJWSRequest(request *http.Request) (*jose.JSONWebSignature, *probs.ProblemDetails) {
	// Verify that the POST request has the expected headers
	if prob := wfe.validPOSTRequest(request); prob != nil {
		return nil, prob
	}

	// Read the POST request body's bytes. validPOSTRequest has already checked
	// that the body is non-nil
	bodyBytes, err := ioutil.ReadAll(request.Body)
	if err != nil {
		wfe.stats.httpErrorCount.With(prometheus.Labels{"type": "UnableToReadReqBody"}).Inc()
		return nil, probs.ServerInternal("unable to read request body")
	}

	return wfe.parseJWS(bodyBytes)
}
1200874
func (c *ContivClient) AciGwPost(obj *AciGw) error {
	// build key and URL
	keyStr := obj.Name
	url := c.baseURL + "/api/v1/aciGws/" + keyStr + "/"

	// http post the object
	err := c.httpPost(url, obj)
	if err != nil {
		log.Debugf("Error creating aciGw %+v. Err: %v", obj, err)
		return err
	}

	return nil
}
1234458
func (s *TestInvokeAuthorizerOutput) SetIsAuthenticated(v bool) *TestInvokeAuthorizerOutput {
	s.IsAuthenticated = &v
	return s
}
972806
func (id *idemixmsp) IsWellFormed(identity *m.SerializedIdentity) error {
	sId := new(m.SerializedIdemixIdentity)
	err := proto.Unmarshal(identity.IdBytes, sId)
	if err != nil {
		return errors.Wrap(err, "not an idemix identity")
	}
	return nil
}
812702
func (wfe *WebFrontEndImpl) RevokeCertificate(
	ctx context.Context,
	logEvent *web.RequestEvent,
	response http.ResponseWriter,
	request *http.Request) {

	// The ACME specification handles the verification of revocation requests
	// differently from other endpoints. For this reason we do *not* immediately
	// call `wfe.validPOSTForAccount` like all of the other endpoints.
	// For this endpoint we need to accept a JWS with an embedded JWK, or a JWS
	// with an embedded key ID, handling each case differently in terms of which
	// certificates are authorized to be revoked by the requester

	// Parse the JWS from the HTTP Request
	jws, prob := wfe.parseJWSRequest(request)
	if prob != nil {
		wfe.sendError(response, logEvent, prob, nil)
		return
	}

	// Figure out which type of authentication this JWS uses
	authType, prob := checkJWSAuthType(jws)
	if prob != nil {
		wfe.sendError(response, logEvent, prob, nil)
		return
	}

	// Handle the revocation request according to how it is authenticated, or if
	// the authentication type is unknown, error immediately
	if authType == embeddedKeyID {
		prob = wfe.revokeCertByKeyID(ctx, jws, request, logEvent)
		addRequesterHeader(response, logEvent.Requester)
	} else if authType == embeddedJWK {
		prob = wfe.revokeCertByJWK(ctx, jws, request, logEvent)
	} else {
		prob = probs.Malformed("Malformed JWS, no KeyID or embedded JWK")
	}
	if prob != nil {
		wfe.sendError(response, logEvent, prob, nil)
		return
	}
	response.WriteHeader(http.StatusOK)
}
165004
func (a *oauth) VerifyOAuth(next http.Handler) httprouter.Handle {

	return func(rw http.ResponseWriter, r *http.Request, ps httprouter.Params) {

		/* Parse the JWT from the input request */
		jwt, err := jws.ParseJWTFromRequest(r)
		if err != nil {
			WriteErrorResponse(http.StatusBadRequest, err.Error(), rw)
			return
		}

		/* Get the pulic key from cache */
		pk := a.getPkSafe()
		if pk == nil {
			WriteErrorResponse(http.StatusBadRequest, "Public key not configured. Validation failed.", rw)
			return
		}

		/* Validate the token */
		err = jwt.Validate(pk, crypto.SigningMethodRS256)
		if err != nil {
			WriteErrorResponse(http.StatusBadRequest, err.Error(), rw)
			return
		}

		/* Set the input params in the request */
		r = SetParamsInRequest(r, ps)
		next.ServeHTTP(rw, r)
	}

}
1285111
func checkJWT(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	addCommonJwtRespHeaders(w, r)
	// Look for JWT in both headers and request value "access_token".
	token, err := request.ParseFromRequest(r, TokenExtractor{}, func(token *jwt.Token) (interface{}, error) {
		// Token was signed with RSA method when it was initially granted
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return publicKey, nil
	})
	if err != nil || !token.Valid {
		http.Error(w, fmt.Sprintf("{\"error\": \"%s %s\"}", "JWT not valid,", err), http.StatusUnauthorized)
	} else {
		w.WriteHeader(http.StatusOK)
	}
}
621177
func HTTPPost(path string, data *[]byte, headers [][]string, username, password string) ([]byte, error) {
	var (
		req *http.Request
		err error
	)

	client := &http.Client{Transport: &transport}
	if data == nil {
		req, err = http.NewRequest("POST", path, nil)
	} else {
		req, err = http.NewRequest("POST", path, bytes.NewReader(*data))
	}

	if err != nil {
		return nil, err
	}

	if username != "" && password != "" {
		req.SetBasicAuth(username, password)
	}

	if len(headers) > 0 {
		for i := range headers {
			req.Header.Add(headers[i][0], headers[i][1])
		}
	}
	return makeRequest(client, req)
}
77417
func IsInvalidCredentialsError(err error) bool {
	isInvalidCredentialsError := false
	if soap.IsSoapFault(err) {
		_, isInvalidCredentialsError = soap.ToSoapFault(err).VimFault().(types.InvalidLogin)
	}
	return isInvalidCredentialsError
}
532047
func (j *JWT) ValidPrincipal(ctx context.Context, jwtToken Token, lifespan time.Duration) (Principal, error) {
	gojwt.TimeFunc = j.Now

	// Check for expected signing method.
	alg := j.KeyFunc

	return j.ValidClaims(jwtToken, lifespan, alg)
}
987973
func (sub *subscription) IsValid() bool {
	sub.Lock()
	defer sub.Unlock()
	if sub.inboxSub == nil {
		return false
	}
	return sub.inboxSub.IsValid()
}
934014
func (s *GenericAPIServer) isPostStartHookRegistered(name string) bool {
	s.postStartHookLock.Lock()
	defer s.postStartHookLock.Unlock()
	_, exists := s.postStartHooks[name]
	return exists
}
1341599
func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) {
	hasher := sha1.New()
	_, err := hasher.Write(secret.Certificate.Raw)
	if err != nil {
		return "", err
	}

	thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil))

	// The jti (JWT ID) claim provides a unique identifier for the JWT.
	jti := make([]byte, 20)
	_, err = rand.Read(jti)
	if err != nil {
		return "", err
	}

	token := jwt.New(jwt.SigningMethodRS256)
	token.Header["x5t"] = thumbprint
	x5c := []string{base64.StdEncoding.EncodeToString(secret.Certificate.Raw)}
	token.Header["x5c"] = x5c
	token.Claims = jwt.MapClaims{
		"aud": spt.inner.OauthConfig.TokenEndpoint.String(),
		"iss": spt.inner.ClientID,
		"sub": spt.inner.ClientID,
		"jti": base64.URLEncoding.EncodeToString(jti),
		"nbf": time.Now().Unix(),
		"exp": time.Now().Add(time.Hour * 24).Unix(),
	}

	signedString, err := token.SignedString(secret.PrivateKey)
	return signedString, err
}
1113949
func ValidatePostInit() error {
	if option.Config.EnableIPv4 || option.Config.Tunnel != option.TunnelDisabled {
		if ipv4ExternalAddress == nil {
			return fmt.Errorf("External IPv4 node address could not be derived, please configure via --ipv4-node")
		}
	}

	if option.Config.EnableIPv4 {
		if ipv4InternalAddress == nil {
			return fmt.Errorf("BUG: Internal IPv4 node address was not configured")
		}

		if !ipv4AllocRange.Contains(ipv4InternalAddress) {
			return fmt.Errorf("BUG: Internal IPv4 (%s) must be part of cluster prefix (%s)",
				ipv4InternalAddress, ipv4AllocRange)
		}

		ones, _ := ipv4AllocRange.Mask.Size()
		if ipv4ClusterCidrMaskSize > ones {
			return fmt.Errorf("IPv4 per node allocation prefix (%s) must be inside cluster prefix (%s)",
				ipv4AllocRange, GetIPv4ClusterRange())
		}
	}

	return nil
}