// AsCreateRequest creates a payload for the LXD API, suitable for posting the
// client certificate to an LXD server.
764379
func (c *Certificate) AsCreateRequest() (api.CertificatesPost, error) {
	block, _ := pem.Decode(c.CertPEM)
	if block == nil {
		return api.CertificatesPost{}, errors.New("failed to decode certificate PEM")
	}

	return api.CertificatesPost{
		Certificate: base64.StdEncoding.EncodeToString(block.Bytes),
		CertificatePut: api.CertificatePut{
			Name: c.Name,
			Type: "client",
		},
	}, nil
}
1289999
func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
	method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)

	resp, err := bot.Client.PostForm(method, params)
	if err != nil {
		return APIResponse{}, err
	}
	defer resp.Body.Close()

	var apiResp APIResponse
	bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp)
	if err != nil {
		return apiResp, err
	}

	if bot.Debug {
		log.Printf("%s resp: %s", endpoint, bytes)
	}

	if !apiResp.Ok {
		parameters := ResponseParameters{}
		if apiResp.Parameters != nil {
			parameters = *apiResp.Parameters
		}
		return apiResp, Error{Code: apiResp.ErrorCode, Message: apiResp.Description, ResponseParameters: parameters}
	}

	return apiResp, nil
}
1261097
func (t *Token) buildRequest() (string, url.Values, error) {
	v := url.Values{}
	j, err := t.Encode()
	if err != nil {
		return t.ClaimSet.Aud, v, err
	}
	v.Set("grant_type", stdGrantType)
	v.Set("assertion", j)
	return t.ClaimSet.Aud, v, nil
}
237537
func decodeRequest(in []byte) (*Request, error) {
	request := &Request{}

	if err := json.NewDecoder(bytes.NewReader(in)).Decode(request); err != nil {
		return nil, err
	}

	// @step: validate the node request
	if err := validateNodeRegistrationRequest(request); err != nil {
		return nil, err
	}

	return request, nil
}
777137
func createRequest(method string, url string,
	payload interface{}, onlyFields []string,
	options ...RequestOptions) (req *http.Request, err error) {

	body, err := convertPayload(payload, onlyFields)
	if err != nil {
		return req, fmt.Errorf("creating request: %s\n", err)
	}
	req, err = http.NewRequest(method, url, bytes.NewBuffer(body))
	if err != nil {
		return req, fmt.Errorf("creating request: %s\n", err)
	}
	for _, option := range options {
		option(req)
	}
	userAgent(req)
	req.Header.Add("Accept", "application/json")
	return req, err
}
74582
func (c *Container) createRequest(method, url, contentType string, body io.Reader) (*http.Request, error) {
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}

	if c.APIKey != "" {
		req.Header.Set("X-Skygear-API-Key", c.APIKey)
	}
	if c.AccessToken != "" {
		req.Header.Set("X-Skygear-Access-Token", c.AccessToken)
	}
	if contentType != "" {
		req.Header.Set("Content-Type", contentType)
	}

	return req, nil
}
426251
func makeTokenRequest(ctx context.Context, client *http.Client, verifier server.Verifier, config *Config) (*server.NodeRegistration, error) {
	registration := &server.NodeRegistration{}

	// @step: create the request payload
	req, err := verifier.VerifyIdentity(ctx)
	if err != nil {
		return nil, err
	}

	hostname, err := getHostname()
	if err != nil {
		return nil, err
	}

	// @step: make the request to the node-authozier
	url := fmt.Sprintf("%s/authorize/%s", strings.TrimSuffix(config.NodeURL, "/authorize"), hostname)
	resp, err := client.Post(url, "application/json", bytes.NewReader(req))
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("invalid response code: %d", resp.StatusCode)
	}

	// @step: read in the response and decode
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	if err := json.Unmarshal(content, registration); err != nil {
		return nil, err
	}

	return registration, nil
}
1057777
func (n *NodeAuthorizer) authorizeNodeRequest(ctx context.Context, request *NodeRegistration) error {
	doneCh := make(chan error, 0)

	// @step: create a context to run under
	ctx, cancel := context.WithTimeout(ctx, n.config.AuthorizationTimeout)
	defer cancel()

	// @step: background the request and wait for either a timeout or a token
	go func() {
		doneCh <- func() error {
			// @step: check if the node request is authorized
			if err := n.safelyAuthorizeNode(ctx, request); err != nil {
				return err
			}
			if request.IsAllowed() {
				return n.safelyProvisionBootstrapToken(ctx, request)
			}

			return nil
		}()
	}()

	// @step: we either wait for the context to timeout or cancel, or we receive a done signal
	select {
	case <-ctx.Done():
		if err := ctx.Err(); err != nil {
			utils.Logger.Error("operation has either timed out or been cancelled",
				zap.String("client", request.Spec.RemoteAddr),
				zap.String("node", request.Spec.NodeName),
				zap.Error(err))
		}

		return nil

	case err := <-doneCh:
		if err != nil {
			utils.Logger.Error("failed to provision a bootstrap token",
				zap.String("client", request.Spec.RemoteAddr),
				zap.String("node", request.Spec.NodeName),
				zap.Error(err))
		}
	}

	if !request.IsAllowed() {
		utils.Logger.Error("the node has been denied authorization",
			zap.String("client", request.Spec.RemoteAddr),
			zap.String("node", request.Spec.NodeName),
			zap.String("reason", request.Status.Reason))

		nodeAuthorizationMetric.WithLabelValues("denied").Inc()

		return nil
	}

	utils.Logger.Info("node has been authorized access",
		zap.String("client", request.Spec.RemoteAddr),
		zap.String("node", request.Spec.NodeName))

	nodeAuthorizationMetric.WithLabelValues("allowed").Inc()

	return nil
}
29565
func (client *Client) NewRequest(method, path string, payload url.Values) (*http.Request, error) {
	url := client.BaseURL + fmt.Sprintf("%s", path)

	req, err := http.NewRequest(method, url, strings.NewReader(payload.Encode()))
	if err != nil {
		return nil, err
	}

	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Accept", "application/json")
	req.Header.Add("User-Agent", client.UserAgent)

	return req, nil
}
436543
func newCodecRequest(r *http.Request) rpc.CodecRequest {
	// Decode the request body and check if RPC method is valid.
	req := new(serverRequest)
	path := r.URL.Path
	index := strings.LastIndex(path, "/")
	if index < 0 {
		return &CodecRequest{request: req, err: fmt.Errorf("rpc: no method: %s", path)}
	}
	req.Method = path[index+1:]
	err := json.NewDecoder(r.Body).Decode(&req.Params)
	r.Body.Close()
	var errr error
	if err != io.EOF {
		errr = err
	}
	return &CodecRequest{request: req, err: errr}
}
436911
func NewClientFromChallenge(chal []byte, opts *Options) (*Client, error) {
	m := &digest{challenge: &challenge{}, response: newResponse(opts)}

	if err := m.challenge.parseChallenge(chal); err != nil {
		return nil, err
	}
	m.response.nonce = m.challenge.nonce
	m.response.charset = m.challenge.charset
	if len(m.challenge.realms) > 0 {
		m.response.realm = m.challenge.realms[0]
	}
	if len(m.challenge.qop) > 0 {
		m.response.qop = m.challenge.qop[0]
	}

	return (*Client)(m), nil
}
612088
func validateRequest(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	devFlag := r.URL.Query().Get("_dev")
	isDev := devFlag != ""
	if !isDev && !IsValidAlexaRequest(w, r) {
		log.Println("Request invalid")
		return
	}
	next(w, r)
}
1019755
func (nsPayloads_) asPayload(doc payloadDoc) payload.FullPayloadInfo {
	labels := make([]string, len(doc.Labels))
	copy(labels, doc.Labels)
	p := payload.FullPayloadInfo{
		Payload: payload.Payload{
			PayloadClass: charm.PayloadClass{
				Name: doc.Name,
				Type: doc.Type,
			},
			ID:     doc.RawID,
			Status: doc.State,
			Labels: labels,
			Unit:   doc.UnitID,
		},
		Machine: doc.MachineID,
	}
	return p
}
43603
func ValidateRequest(r *http.Request, usertoken string) bool {
	var token string
	if strings.Contains(r.Header.Get("content-type"), "/json") {
		decoder := json.NewDecoder(r.Body)
		var i bson.M
		err := decoder.Decode(i)
		if err != nil {
			return false
		}

		token = Decrypt([]byte(FormKey), i["formtoken"].(string))

	} else {
		token = Decrypt([]byte(FormKey), r.FormValue("formtoken"))
	}
	return strings.Contains(token, usertoken) && strings.Contains(token, r.URL.Path)
}
500993
func (c *Container) MakeRequest(action string, request SkygearRequest) (response *SkygearResponse, err error) {
	url := c.actionURL(action)
	payload := request.MakePayload()
	c.fixRequestPayload(action, payload)

	jsonStr, err := json.Marshal(payload)
	if err != nil {
		return nil, err
	}

	req, err := c.createRequest("POST", url, "", bytes.NewBuffer(jsonStr))
	if err != nil {
		return nil, err
	}

	jsonDataFromHTTP, err := getBytesResponse(req)
	if err != nil {
		return nil, err
	}

	var jsonData map[string]interface{}
	err = json.Unmarshal(jsonDataFromHTTP, &jsonData)
	if err != nil {
		return
	}

	return &SkygearResponse{Payload: jsonData}, nil

}
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
}
147745
func (c *Client) MakeRequest(req *http.Request) (*http.Response, error) {
	return c.HTTPClient.Do(req)
}