// Use this method to parse the webhook signature given as JSON in the webhook response
492032
func (mg *MailgunImpl) VerifyWebhookSignature(sig Signature) (verified bool, err error) {
	h := hmac.New(sha256.New, []byte(mg.APIKey()))
	io.WriteString(h, sig.TimeStamp)
	io.WriteString(h, sig.Token)

	calculatedSignature := h.Sum(nil)
	signature, err := hex.DecodeString(sig.Signature)
	if err != nil {
		return false, err
	}
	if len(calculatedSignature) != len(signature) {
		return false, nil
	}

	return subtle.ConstantTimeCompare(signature, calculatedSignature) == 1, nil
}
1049988
func (s *HmacSha1Signer) GetSignature(consumerSecret string, tokenSecret string, signatureBase string) string {
	signingKey := consumerSecret + "&" + tokenSecret
	signer := hmac.New(sha1.New, []byte(signingKey))
	signer.Write([]byte(signatureBase))
	oauthSignature := base64.StdEncoding.EncodeToString(signer.Sum(nil))
	return oauthSignature
}
282835
func (v *validatingWebhookConfigurationManager) Webhooks() []v1beta1.Webhook {
	return v.configuration.Load().(*v1beta1.ValidatingWebhookConfiguration).Webhooks
}
148918
func ParseJWS(content []byte) (*JSONSignature, error) {
	type jsParsed struct {
		Payload    string              `json:"payload"`
		Signatures []jsParsedSignature `json:"signatures"`
	}
	parsed := &jsParsed{}
	err := json.Unmarshal(content, parsed)
	if err != nil {
		return nil, err
	}
	if len(parsed.Signatures) == 0 {
		return nil, errors.New("missing signatures")
	}
	payload, err := joseBase64UrlDecode(parsed.Payload)
	if err != nil {
		return nil, err
	}

	js, err := NewJSONSignature(payload)
	if err != nil {
		return nil, err
	}
	js.signatures = make([]jsSignature, len(parsed.Signatures))
	for i, signature := range parsed.Signatures {
		header := jsHeader{
			Algorithm: signature.Header.Algorithm,
		}
		if signature.Header.Chain != nil {
			header.Chain = signature.Header.Chain
		}
		if signature.Header.JWK != nil {
			publicKey, err := UnmarshalPublicKeyJWK([]byte(signature.Header.JWK))
			if err != nil {
				return nil, err
			}
			header.JWK = publicKey
		}
		js.signatures[i] = jsSignature{
			Header:    header,
			Signature: signature.Signature,
			Protected: signature.Protected,
		}
	}

	return js, nil
}
833173
func (wh Webhook) MarshalJSON() ([]byte, error) {
	data := jsonWebhook{
		ID:        wh.ID,
		URL:       wh.URL,
		Token:     wh.Token,
		CreatedAt: wh.CreatedAt.Format(time.RFC3339),
		UpdatedAt: wh.UpdatedAt.Format(time.RFC3339),
	}
	return json.Marshal(data)
}
145433
func Convert_v1_WebhookTokenAuthenticator_To_config_WebhookTokenAuthenticator(in *v1.WebhookTokenAuthenticator, out *config.WebhookTokenAuthenticator, s conversion.Scope) error {
	return autoConvert_v1_WebhookTokenAuthenticator_To_config_WebhookTokenAuthenticator(in, out, s)
}
1027950
func (wc *WebhookContext) Response(code int, s string) {
	wc.gin.String(code, s)
}
1339033
func (client *Client) Sign(params url.Values) (string, error) {
	query := encodeValues(params)
	query = strings.ToLower(query)
	mac := hmac.New(sha1.New, []byte(client.apiSecret))
	_, err := mac.Write([]byte(query))
	if err != nil {
		return "", err
	}

	signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
	return signature, nil
}
597976
func (s *Signer) Sign(r *http.Request) {
	t := time.Now().Unix()
	n := s.GenerateNonce(t, "x", "y")
	values := r.URL.Query()
	values.Add(s.nonceParam, n)
	values.Add(s.timestampParam, strconv.Itoa(int(t)))
	r.URL.RawQuery = values.Encode()
	signature := s.Signature(r)

	//add signature to request
	values.Add(s.signatureParam, signature)
	r.URL.RawQuery = values.Encode()
}
951509
func (js *JSONSignature) Sign(key PrivateKey) error {
	protected, err := js.protectedHeader()
	if err != nil {
		return err
	}
	signBytes, err := js.signBytes(protected)
	if err != nil {
		return err
	}
	sigBytes, algorithm, err := key.Sign(bytes.NewReader(signBytes), crypto.SHA256)
	if err != nil {
		return err
	}

	js.signatures = append(js.signatures, jsSignature{
		Header: jsHeader{
			JWK:       key.PublicKey(),
			Algorithm: algorithm,
		},
		Signature: joseBase64UrlEncode(sigBytes),
		Protected: protected,
	})

	return nil
}
978109
func JSON(w http.ResponseWriter, responses ...interface{}) {
	respond := func(payload interface{}) {
		var result []byte
		var err error
		encode := func(payload interface{}) ([]byte, error) {
			if config.Pretty {
				return json.MarshalIndent(payload, "", "\t")
			}
			return json.Marshal(payload)
		}
		switch value := payload.(type) {
		case []byte:
			result = value
		case error:
			// main key is "error"
			errWithStack := errors.WithStack(value)
			if config.Logger != nil {
				config.Logger(errWithStack)
			}
			result, err = encode(errorResponse(errWithStack))
		case successMessage:
			// main key is "success"
			result, err = encode(value)
		default:
			// main key is "response"
			result, err = encode(struct {
				Response interface{} `json:"response"`
			}{value})
		}
		if err != nil {
			result, _ = encode(errorResponse(errors.WithStack(err)))
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write(result)
	}

	for _, response := range responses {
		switch value := response.(type) {
		case nil:
			// this will match a nil error
			continue
		case func() ([]byte, error):
			result, err := value()
			JSON(w, err, result)
		case func() (interface{}, error):
			result, err := value()
			JSON(w, err, result)
		case func() error:
			err := value()
			if err == nil {
				continue
			}
			respond(err)
		case *error:
			if *value == nil {
				continue
			}
			respond(*value)
		case error:
			respond(value)
		case string:
			if value == "" {
				continue
			}
			respond(value)
		case bool:
			if !value {
				continue
			}
			respond(value)
		case successMessage:
			respond(value)
		default:
			respond(value)
		}
		// Exit on the first output...
		return
	}
	respond(false)
}
220528
func ParseCreateHook(raw []byte) (*CreatePayload, error) {
	hook := new(CreatePayload)
	if err := json.Unmarshal(raw, hook); err != nil {
		return nil, err
	}

	// it is possible the JSON was parsed, however,
	// was not from Gogs (maybe was from Bitbucket)
	// So we'll check to be sure certain key fields
	// were populated
	switch {
	case hook.Repo == nil:
		return nil, ErrInvalidReceiveHook
	case len(hook.Ref) == 0:
		return nil, ErrInvalidReceiveHook
	}
	return hook, nil
}
488751
func NewTokenVerification(response *http.Response) (*TokenVerification, error) {
	tokenVerification := &TokenVerification{HTTPResponse: response}
	body, err := ioutil.ReadAll(response.Body)

	if err != nil {
		Logger.Println("Error reading from API:", err)
		return tokenVerification, err
	}

	err = json.Unmarshal(body, &tokenVerification)
	if err != nil {
		Logger.Println("Error parsing JSON:", err)
		return tokenVerification, err
	}

	return tokenVerification, nil
}
30398
func ParseVerify(src io.Reader, alg jwa.SignatureAlgorithm, key interface{}) (*Token, error) {
	data, err := ioutil.ReadAll(src)
	if err != nil {
		return nil, errors.Wrap(err, `failed to read token from source`)
	}

	v, err := jws.Verify(data, alg, key)
	if err != nil {
		return nil, errors.Wrap(err, `failed to verify jws signature`)
	}

	var token Token
	if err := json.Unmarshal(v, &token); err != nil {
		return nil, errors.Wrap(err, `failed to parse token`)
	}
	return &token, nil
}
853861
func getResponseFromJSON(ctx context.Context, r *httpRequest, v interface{}) error {
	r.addHeader("User-Agent", MailgunGoUserAgent)
	response, err := r.makeGetRequest(ctx)
	if err != nil {
		return err
	}
	if notGood(response.Code, expected) {
		return newError(r.URL, expected, response)
	}
	return response.parseFromJSON(v)
}
1356656
func BodyJSON(r *http.Response, data interface{}) error {
	if data == nil {
		return errors.New("You must pass in an interface{}")
	}

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}
	err = jsonhooks.Unmarshal(body, data)

	return err
}
1228147
func (o *httpOps) DownloadSignature(a *asc) (readSeekCloser, bool, error) {
	ensureLogger(o.Debug)
	diag.Printf("downloading signature from %v", a.Location)
	ascFile, err := a.Get()
	if err == nil {
		return ascFile, false, nil
	}
	if _, ok := err.(*statusAcceptedError); ok {
		log.Printf("server requested deferring the signature download")
		return NopReadSeekCloser(nil), true, nil
	}
	return nil, false, errwrap.Wrap(errors.New("error downloading the signature file"), err)
}