// isRequestSigned returns if the request is currently signed or presigned
963105
func (ctx *signingCtx) isRequestSigned() bool {
	if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" {
		return true
	}
	if ctx.Request.Header.Get("Authorization") != "" {
		return true
	}

	return false
}
929537
func (md *RootMetadataV2) IsValidAndSigned(
	_ context.Context, codec kbfscodec.Codec,
	_ TeamMembershipChecker, extra ExtraMetadata,
	_ kbfscrypto.VerifyingKey, _ keybase1.OfflineAvailability) error {
	// Optimization -- if the WriterMetadata signature is nil, it
	// will fail verification.
	if md.WriterMetadataSigInfo.IsNil() {
		return errors.New("Missing WriterMetadata signature")
	}

	if md.IsFinal() {
		if md.Revision < RevisionInitial+1 {
			return fmt.Errorf("Invalid final revision %d", md.Revision)
		}

		if md.Revision == (RevisionInitial + 1) {
			if md.PrevRoot != (ID{}) {
				return fmt.Errorf("Invalid PrevRoot %s for initial final revision", md.PrevRoot)
			}
		} else {
			if md.PrevRoot == (ID{}) {
				return errors.New("No PrevRoot for non-initial final revision")
			}
		}
	} else {
		if md.Revision < RevisionInitial {
			return fmt.Errorf("Invalid revision %d", md.Revision)
		}

		if md.Revision == RevisionInitial {
			if md.PrevRoot != (ID{}) {
				return fmt.Errorf("Invalid PrevRoot %s for initial revision", md.PrevRoot)
			}
		} else {
			if md.PrevRoot == (ID{}) {
				return errors.New("No PrevRoot for non-initial revision")
			}
		}
	}

	if len(md.SerializedPrivateMetadata) == 0 {
		return errors.New("No private metadata")
	}

	if (md.MergedStatus() == Merged) != (md.BID() == NullBranchID) {
		return fmt.Errorf("Branch ID %s doesn't match merged status %s",
			md.BID(), md.MergedStatus())
	}

	handle, err := md.MakeBareTlfHandle(extra)
	if err != nil {
		return err
	}

	// Make sure the last writer is valid.  TODO(KBFS-2185): for a
	// team TLF, check that the writer is part of the team.
	writer := md.LastModifyingWriter()
	if !handle.IsWriter(writer.AsUserOrTeam()) {
		return fmt.Errorf("Invalid modifying writer %s", writer)
	}

	// Make sure the last modifier is valid.
	user := md.LastModifyingUser
	if !handle.IsReader(user.AsUserOrTeam()) {
		return fmt.Errorf("Invalid modifying user %s", user)
	}

	// Verify signature. We have to re-marshal the WriterMetadata,
	// since it's embedded.
	buf, err := codec.Encode(md.WriterMetadataV2)
	if err != nil {
		return err
	}

	err = kbfscrypto.Verify(buf, md.WriterMetadataSigInfo)
	if err != nil {
		return fmt.Errorf("Could not verify writer metadata: %v", err)
	}

	return nil
}
853838
func doesPresignedSignatureMatch(hashedPayload string, r *http.Request, region string, stype serviceType) APIErrorCode {
	// Copy request
	req := *r

	// Parse request query string.
	pSignValues, err := parsePreSignV4(req.URL.Query(), region, stype)
	if err != ErrNone {
		return err
	}

	cred, _, s3Err := checkKeyValid(pSignValues.Credential.accessKey)
	if s3Err != ErrNone {
		return s3Err
	}

	// Extract all the signed headers along with its values.
	extractedSignedHeaders, errCode := extractSignedHeaders(pSignValues.SignedHeaders, r)
	if errCode != ErrNone {
		return errCode
	}

	// Construct new query.
	query := make(url.Values)
	if req.URL.Query().Get("X-Amz-Content-Sha256") != "" {
		query.Set("X-Amz-Content-Sha256", hashedPayload)
	}

	query.Set("X-Amz-Algorithm", signV4Algorithm)

	// If the host which signed the request is slightly ahead in time (by less than globalMaxSkewTime) the
	// request should still be allowed.
	if pSignValues.Date.After(UTCNow().Add(globalMaxSkewTime)) {
		return ErrRequestNotReadyYet
	}

	if UTCNow().Sub(pSignValues.Date) > pSignValues.Expires {
		return ErrExpiredPresignRequest
	}

	// Save the date and expires.
	t := pSignValues.Date
	expireSeconds := int(pSignValues.Expires / time.Second)

	// Construct the query.
	query.Set("X-Amz-Date", t.Format(iso8601Format))
	query.Set("X-Amz-Expires", strconv.Itoa(expireSeconds))
	query.Set("X-Amz-SignedHeaders", getSignedHeaders(extractedSignedHeaders))
	query.Set("X-Amz-Credential", cred.AccessKey+"/"+pSignValues.Credential.getScope())

	// Save other headers available in the request parameters.
	for k, v := range req.URL.Query() {

		// Handle the metadata in presigned put query string
		if strings.Contains(strings.ToLower(k), "x-amz-meta-") {
			query.Set(k, v[0])
		}

		if strings.HasPrefix(strings.ToLower(k), "x-amz") {
			continue
		}
		query[k] = v
	}

	// Get the encoded query.
	encodedQuery := query.Encode()

	// Verify if date query is same.
	if req.URL.Query().Get("X-Amz-Date") != query.Get("X-Amz-Date") {
		return ErrSignatureDoesNotMatch
	}
	// Verify if expires query is same.
	if req.URL.Query().Get("X-Amz-Expires") != query.Get("X-Amz-Expires") {
		return ErrSignatureDoesNotMatch
	}
	// Verify if signed headers query is same.
	if req.URL.Query().Get("X-Amz-SignedHeaders") != query.Get("X-Amz-SignedHeaders") {
		return ErrSignatureDoesNotMatch
	}
	// Verify if credential query is same.
	if req.URL.Query().Get("X-Amz-Credential") != query.Get("X-Amz-Credential") {
		return ErrSignatureDoesNotMatch
	}
	// Verify if sha256 payload query is same.
	if req.URL.Query().Get("X-Amz-Content-Sha256") != "" {
		if req.URL.Query().Get("X-Amz-Content-Sha256") != query.Get("X-Amz-Content-Sha256") {
			return ErrContentSHA256Mismatch
		}
	}

	/// Verify finally if signature is same.

	// Get canonical request.
	presignedCanonicalReq := getCanonicalRequest(extractedSignedHeaders, hashedPayload, encodedQuery, req.URL.Path, req.Method)

	// Get string to sign from canonical request.
	presignedStringToSign := getStringToSign(presignedCanonicalReq, t, pSignValues.Credential.getScope())

	// Get hmac presigned signing key.
	presignedSigningKey := getSigningKey(cred.SecretKey, pSignValues.Credential.scope.date,
		pSignValues.Credential.scope.region, stype)

	// Get new signature.
	newSignature := getSignature(presignedSigningKey, presignedStringToSign)

	// Verify signature.
	if !compareSignatureV4(req.URL.Query().Get("X-Amz-Signature"), newSignature) {
		return ErrSignatureDoesNotMatch
	}
	return ErrNone
}
619977
func (s *Signer) IsValid(r *http.Request) error {
	nonce := r.URL.Query().Get(s.nonceParam)
	signature := r.URL.Query().Get(s.signatureParam)
	timestamp, err := strconv.Atoi(r.URL.Query().Get(s.timestampParam))
	if err != nil {
		return fmt.Errorf("gosigner: Can't convert timestamp to int: %s", err.Error())
	}
	if err := s.checkNonceFunc(nonce); err != nil {
		return fmt.Errorf("gosigner: Invalid nonce: %s", err.Error())
	}
	if (int64(timestamp) + int64(s.maxLife)) < int64(time.Now().Unix()) {
		return fmt.Errorf("gosigner: Maxlife for request reached: %v", r)
	}
	if s.Signature(r) != signature {
		return fmt.Errorf("gosigner: Invalid signature: %s", signature)
	}
	return nil
}
1364734
func NewSignedByPolicy(index int32) *common.SignaturePolicy {
	return &common.SignaturePolicy{
		Type: &common.SignaturePolicy_SignedBy{
			SignedBy: index,
		}}
}
1268360
func (c *Client) IsRegistered(subject, schema string) (bool, Schema, error) {
	var fs Schema

	sc := schemaOnlyJSON{schema}
	send, err := json.Marshal(sc)
	if err != nil {
		return false, fs, err
	}

	path := fmt.Sprintf(subjectPath, subject)
	resp, err := c.do(http.MethodPost, path, "", send)
	if err != nil {
		// schema not found?
		if IsSchemaNotFound(err) {
			return false, fs, nil
		}
		// error?
		return false, fs, err
	}

	if err = c.readJSON(resp, &fs); err != nil {
		return true, fs, err // found but error when unmarshal.
	}

	// so we have a schema.
	return true, fs, nil
}
468533
func isRequestPostPolicySignatureV4(r *http.Request) bool {
	return strings.Contains(r.Header.Get("Content-Type"), "multipart/form-data") &&
		r.Method == http.MethodPost
}
381469
func (sd *SignedData) IsDetached() bool {
	return sd.psd.EncapContentInfo.EContent.Bytes == nil
}
1119881
func RequestSigning(id, key string) ClientOpt {
	return func(c *Client) {
		c.Handlers.Sign.Append(request.RequestSigner(id, key))
	}
}
881991
func (s storageclient) GetSignedURLs(context.Context, *coordinator.URLSigningRequest) (*coordinator.URLSigningResponse, error) {
	return nil, errors.New("NOT IMPLEMENTED")
}
650828
func (c Client) PresignedPostPolicy(p *PostPolicy) (u *url.URL, formData map[string]string, err error) {
	// Validate input arguments.
	if p.expiration.IsZero() {
		return nil, nil, errors.New("Expiration time must be specified")
	}
	if _, ok := p.formData["key"]; !ok {
		return nil, nil, errors.New("object key must be specified")
	}
	if _, ok := p.formData["bucket"]; !ok {
		return nil, nil, errors.New("bucket name must be specified")
	}

	bucketName := p.formData["bucket"]
	// Fetch the bucket location.
	location, err := c.getBucketLocation(bucketName)
	if err != nil {
		return nil, nil, err
	}

	isVirtualHost := c.isVirtualHostStyleRequest(*c.endpointURL, bucketName)

	u, err = c.makeTargetURL(bucketName, "", location, isVirtualHost, nil)
	if err != nil {
		return nil, nil, err
	}

	// Get credentials from the configured credentials provider.
	credValues, err := c.credsProvider.Get()
	if err != nil {
		return nil, nil, err
	}

	var (
		signerType      = credValues.SignerType
		sessionToken    = credValues.SessionToken
		accessKeyID     = credValues.AccessKeyID
		secretAccessKey = credValues.SecretAccessKey
	)

	if signerType.IsAnonymous() {
		return nil, nil, ErrInvalidArgument("Presigned operations are not supported for anonymous credentials")
	}

	// Keep time.
	t := time.Now().UTC()
	// For signature version '2' handle here.
	if signerType.IsV2() {
		policyBase64 := p.base64()
		p.formData["policy"] = policyBase64
		// For Google endpoint set this value to be 'GoogleAccessId'.
		if s3utils.IsGoogleEndpoint(*c.endpointURL) {
			p.formData["GoogleAccessId"] = accessKeyID
		} else {
			// For all other endpoints set this value to be 'AWSAccessKeyId'.
			p.formData["AWSAccessKeyId"] = accessKeyID
		}
		// Sign the policy.
		p.formData["signature"] = s3signer.PostPresignSignatureV2(policyBase64, secretAccessKey)
		return u, p.formData, nil
	}

	// Add date policy.
	if err = p.addNewPolicy(policyCondition{
		matchType: "eq",
		condition: "$x-amz-date",
		value:     t.Format(iso8601DateFormat),
	}); err != nil {
		return nil, nil, err
	}

	// Add algorithm policy.
	if err = p.addNewPolicy(policyCondition{
		matchType: "eq",
		condition: "$x-amz-algorithm",
		value:     signV4Algorithm,
	}); err != nil {
		return nil, nil, err
	}

	// Add a credential policy.
	credential := s3signer.GetCredential(accessKeyID, location, t)
	if err = p.addNewPolicy(policyCondition{
		matchType: "eq",
		condition: "$x-amz-credential",
		value:     credential,
	}); err != nil {
		return nil, nil, err
	}

	if sessionToken != "" {
		if err = p.addNewPolicy(policyCondition{
			matchType: "eq",
			condition: "$x-amz-security-token",
			value:     sessionToken,
		}); err != nil {
			return nil, nil, err
		}
	}

	// Get base64 encoded policy.
	policyBase64 := p.base64()

	// Fill in the form data.
	p.formData["policy"] = policyBase64
	p.formData["x-amz-algorithm"] = signV4Algorithm
	p.formData["x-amz-credential"] = credential
	p.formData["x-amz-date"] = t.Format(iso8601DateFormat)
	if sessionToken != "" {
		p.formData["x-amz-security-token"] = sessionToken
	}
	p.formData["x-amz-signature"] = s3signer.PostPresignSignatureV4(policyBase64, t, secretAccessKey, location)
	return u, p.formData, nil
}
105663
func (c Client) Presign(method string, bucketName string, objectName string, expires time.Duration, reqParams url.Values) (u *url.URL, err error) {
	return c.presignURL(method, bucketName, objectName, expires, reqParams)
}
119669
func isRequestPresignedSignatureV4(r *http.Request) bool {
	_, ok := r.URL.Query()["X-Amz-Credential"]
	return ok
}
1216362
func Sign(req *request.Request) {
	// If the request does not need to be signed ignore the signing of the
	// request if the AnonymousCredentials object is used.
	if req.Config.Credentials == credentials.AnonymousCredentials {
		return
	}

	v2 := signer{
		Request:     req.HTTPRequest,
		Time:        req.Time,
		Credentials: req.Config.Credentials,
		Debug:       req.Config.LogLevel.Value(),
		Logger:      req.Config.Logger,
	}

	req.Error = v2.Sign()

	if req.Error != nil {
		return
	}
}
929196
func presignURL(r *request.Request, sourceRegion *string, newParams interface{}) *string {
	cfg := r.Config.Copy(aws.NewConfig().
		WithEndpoint("").
		WithRegion(aws.StringValue(sourceRegion)))

	clientInfo := r.ClientInfo
	resolved, err := r.Config.EndpointResolver.EndpointFor(
		clientInfo.ServiceName, aws.StringValue(cfg.Region),
		func(opt *endpoints.Options) {
			opt.DisableSSL = aws.BoolValue(cfg.DisableSSL)
			opt.UseDualStack = aws.BoolValue(cfg.UseDualStack)
		},
	)
	if err != nil {
		r.Error = err
		return nil
	}

	clientInfo.Endpoint = resolved.URL
	clientInfo.SigningRegion = resolved.SigningRegion

	// Presign a request with modified params
	req := request.New(*cfg, clientInfo, r.Handlers, r.Retryer, r.Operation, newParams, r.Data)
	req.Operation.HTTPMethod = "GET"
	uri, err := req.Presign(5 * time.Minute) // 5 minutes should be enough.
	if err != nil {                          // bubble error back up to original request
		r.Error = err
		return nil
	}

	// We have our URL, set it on params
	return &uri
}
969581
func (c Client) presignURL(method string, bucketName string, objectName string, expires time.Duration, reqParams url.Values) (u *url.URL, err error) {
	// Input validation.
	if method == "" {
		return nil, ErrInvalidArgument("method cannot be empty.")
	}
	if err = s3utils.CheckValidBucketName(bucketName); err != nil {
		return nil, err
	}
	if err = isValidExpiry(expires); err != nil {
		return nil, err
	}

	// Convert expires into seconds.
	expireSeconds := int64(expires / time.Second)
	reqMetadata := requestMetadata{
		presignURL:  true,
		bucketName:  bucketName,
		objectName:  objectName,
		expires:     expireSeconds,
		queryValues: reqParams,
	}

	// Instantiate a new request.
	// Since expires is set newRequest will presign the request.
	var req *http.Request
	if req, err = c.newRequest(method, reqMetadata); err != nil {
		return nil, err
	}
	return req.URL, nil
}
725328
func SignRequest(xml string, privateKeyPath string) (string, error) {
	return sign(xml, privateKeyPath, xmlRequestID)
}