// MakeResponse creates and assigns a new SAML response in ResponseEl. `Assertion` must
// be non-nil. If MakeAssertionEl() has not been called, this function calls it for
// you.
480978
func (req *IdpAuthnRequest) MakeResponse() error {
	if req.AssertionEl == nil {
		if err := req.MakeAssertionEl(); err != nil {
			return err
		}
	}

	response := &Response{
		Destination:  req.ACSEndpoint.Location,
		ID:           fmt.Sprintf("id-%x", randomBytes(20)),
		InResponseTo: req.Request.ID,
		IssueInstant: req.Now,
		Version:      "2.0",
		Issuer: &Issuer{
			Format: "urn:oasis:names:tc:SAML:2.0:nameid-format:entity",
			Value:  req.IDP.MetadataURL.String(),
		},
		Status: Status{
			StatusCode: StatusCode{
				Value: StatusSuccess,
			},
		},
	}

	responseEl := response.Element()
	responseEl.AddChild(req.AssertionEl) // AssertionEl either an EncryptedAssertion or Assertion element

	// Sign the response element (we've already signed the Assertion element)
	{
		keyPair := tls.Certificate{
			Certificate: [][]byte{req.IDP.Certificate.Raw},
			PrivateKey:  req.IDP.Key,
			Leaf:        req.IDP.Certificate,
		}
		for _, cert := range req.IDP.Intermediates {
			keyPair.Certificate = append(keyPair.Certificate, cert.Raw)
		}
		keyStore := dsig.TLSCertKeyStore(keyPair)

		signatureMethod := req.IDP.SignatureMethod
		if signatureMethod == "" {
			signatureMethod = dsig.RSASHA1SignatureMethod
		}

		signingContext := dsig.NewDefaultSigningContext(keyStore)
		signingContext.Canonicalizer = dsig.MakeC14N10ExclusiveCanonicalizerWithPrefixList(canonicalizerPrefixList)
		if err := signingContext.SetSignatureMethod(signatureMethod); err != nil {
			return err
		}

		signedResponseEl, err := signingContext.SignEnveloped(responseEl)
		if err != nil {
			return err
		}

		sigEl := signedResponseEl.ChildElements()[len(signedResponseEl.ChildElements())-1]
		response.Signature = sigEl
		responseEl = response.Element()
		responseEl.AddChild(req.AssertionEl)
	}

	req.ResponseEl = responseEl
	return nil
}
753707
func CheckResponse(response *APIResponse) (err error) {
	if response.HTTP.StatusCode < 200 || response.HTTP.StatusCode >= 400 {

		errorParts := []string{
			fmt.Sprintf("Received HTTP Status '%s'", response.HTTP.Status),
		}
		if message := createErrorResponseMessage(response.Body); message != "" {
			errorParts = append(errorParts, message)
		}

		err = errors.New(strings.Join(errorParts, ": "))
	}
	return
}
167827
func NewValidationResponse(validation ValidationModel, warnings ...string) ValidateResponseModel {
	return ValidateResponseModel{
		Data:     &validation,
		Warnings: warnings,
	}
}
222117
func makeResponse(id, result interface{}, err error) btcjson.Response {
	idPtr := idPointer(id)
	if err != nil {
		return btcjson.Response{
			ID:    idPtr,
			Error: jsonError(err),
		}
	}
	resultBytes, err := json.Marshal(result)
	if err != nil {
		return btcjson.Response{
			ID: idPtr,
			Error: &btcjson.RPCError{
				Code:    btcjson.ErrRPCInternal.Code,
				Message: "Unexpected error marshalling result",
			},
		}
	}
	return btcjson.Response{
		ID:     idPtr,
		Result: json.RawMessage(resultBytes),
	}
}
872105
func (req *IdpAuthnRequest) WriteResponse(w http.ResponseWriter) error {
	if req.Response == nil {
		if err := req.MakeResponse(); err != nil {
			return err
		}
	}
	responseBuf, err := xml.Marshal(req.Response)
	if err != nil {
		return err
	}

	// the only supported binding is the HTTP-POST binding
	switch req.ACSEndpoint.Binding {
	case HTTPPostBinding:
		tmpl := template.Must(template.New("saml-post-form").Parse(`<html>` +
			`<form method="post" action="{{.URL}}" id="SAMLResponseForm">` +
			`<input type="hidden" name="SAMLResponse" value="{{.SAMLResponse}}" />` +
			`<input type="hidden" name="RelayState" value="{{.RelayState}}" />` +
			`<input type="submit" value="Continue" />` +
			`</form>` +
			`<script>document.getElementById('SAMLResponseForm').submit();</script>` +
			`</html>`))
		data := struct {
			URL          string
			SAMLResponse string
			RelayState   string
		}{
			URL:          req.ACSEndpoint.Location,
			SAMLResponse: base64.StdEncoding.EncodeToString(responseBuf),
			RelayState:   req.RelayState,
		}

		buf := bytes.NewBuffer(nil)
		if err := tmpl.Execute(buf, data); err != nil {
			return err
		}
		if _, err := io.Copy(w, buf); err != nil {
			return err
		}
		return nil
	case HTTPRedirectBinding:
		acsURL, _ := url.Parse(req.ACSEndpoint.Location)
		q := acsURL.Query()
		q.Set("RelayState", req.RelayState)
		q.Set("SAMLResponse", base64.StdEncoding.EncodeToString(responseBuf))
		acsURL.RawQuery = q.Encode()
		w.Header().Set("Location", acsURL.String())
		w.WriteHeader(307)
		return nil
	default:
		return fmt.Errorf("%s: unsupported binding %s",
			req.ServiceProviderMetadata.EntityID,
			req.ACSEndpoint.Binding)
	}
}
706097
func createResponse(res *stackr.Response, next func(), app *Server) *Response {

	this := &Response{}

	this.Response = res

	this.SetNext(next)

	this.SetApplication(app)

	this.Charset = "utf-8"

	this.Locals = map[string]string{}

	return this
}
667869
func (c *Sender) AppendAndRepeatResponse(resp *http.Response, repeat int) {
	c.appendAndRepeat(response{r: resp}, repeat)
}
196029
func (logger *RequestLogger) Make(request *http.Request, passedResponse *uaa.Response) error {
	err := logger.displayRequest(request)
	if err != nil {
		logger.output.HandleInternalError(err)
	}

	err = logger.connection.Make(request, passedResponse)

	if passedResponse.HTTPResponse != nil {
		displayErr := logger.displayResponse(passedResponse)
		if displayErr != nil {
			logger.output.HandleInternalError(displayErr)
		}
	}

	return err
}
503836
func NewResponse(r *Request) *Response {
	return &Response{
		Version: r.Version,
		ID:      r.ID,
	}
}
348838
func makeRequest(req *http.Request) *Request {
	request := &Request{
		Request: req,
	}

	return request
}
470101
func (a *auditLogFile) AddResponse(m ResponseErrors) error {
	return errors.Trace(a.addRecord(Record{Errors: &m}))
}
1241563
func (d *Digest) CreateDigestResponse(username, password, method, uri string) string {
	return d.computeAuthorization(username, password, method, uri, d.createCnonce())
}
792108
func BuildResponse(j *interface{}) (*SelectResponse, error) {

	// look for a response element, bail if not present
	response_root := (*j).(map[string]interface{})
	response := response_root["response"]
	if response == nil {
		return nil, fmt.Errorf("Supplied interface appears invalid (missing response)")
	}

	// begin Response creation
	r := SelectResponse{}

	// do status & qtime, if possible
	r_header := (*j).(map[string]interface{})["responseHeader"].(map[string]interface{})
	if r_header != nil {
		r.Status = int(r_header["status"].(float64))
		r.QTime = int(r_header["QTime"].(float64))
	}

	// now do docs, if they exist in the response
	docs := response.(map[string]interface{})["docs"].([]interface{})
	if docs != nil {
		// the total amount of results, irrespective of the amount returned in the response
		num_found := int(response.(map[string]interface{})["numFound"].(float64))

		// and the amount actually returned
		num_results := len(docs)

		coll := DocumentCollection{}
		coll.NumFound = num_found

		ds := []Document{}

		for i := 0; i < num_results; i++ {
			ds = append(ds, Document{docs[i].(map[string]interface{})})
		}

		coll.Collection = ds
		r.Results = &coll
	}

	// facets
	facet_response, ok := response_root["facet_counts"].(interface{})
	if ok == true {
		facet_counts := facet_response.(map[string]interface{})
		if facet_counts != nil {
			// do counts if they exist
			facet_fields := facet_counts["facet_fields"].(map[string]interface{})
			facets := []Facet{}
			if facet_fields != nil {
				// iterate over each facet field, create facet & counts for each field
				for k, v := range facet_fields {
					f := Facet{Name: k}
					chunked := chunk(v.([]interface{}), facet_chunk_size)
					lc := len(chunked)
					for i := 0; i < lc; i++ {
						f.Counts = append(f.Counts, FacetCount{
							Value: chunked[i][0].(string),
							Count: int(chunked[i][1].(float64)),
						})
					}
					facets = append(facets, f)
				}
			}

			// add Facets to collection
			r.Results.Facets = facets
			r.Results.NumFacets = len(facets)

		}
	}

	return &r, nil
}
1247415
func (a *AuthServer) ValidateSAMLResponse(samlResponse string) (*SAMLAuthResponse, error) {
	re, err := a.validateSAMLResponse(samlResponse)
	if err != nil {
		a.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{
			events.LoginMethod:        events.LoginMethodSAML,
			events.AuthAttemptSuccess: false,
			events.AuthAttemptErr:     err.Error(),
		})
	} else {
		a.EmitAuditEvent(events.UserSSOLogin, events.EventFields{
			events.EventUser:          re.Username,
			events.AuthAttemptSuccess: true,
			events.LoginMethod:        events.LoginMethodSAML,
		})
	}
	return re, err
}
1003069
func WriteResponse(w http.ResponseWriter, rec *httptest.ResponseRecorder) {
	w.WriteHeader(rec.Code)
	for k, v := range rec.HeaderMap {
		w.Header()[k] = v
	}
	w.Write(rec.Body.Bytes())
}
218650
func handleResponse(r *http.Response) (*oauth.Token, error) {
	o := &oauth.Token{}
	defer r.Body.Close()
	if r.StatusCode != 200 {
		return o, errors.New("invalid response: " + r.Status)
	}
	b := &respBody{}
	err := json.NewDecoder(r.Body).Decode(b)
	if err != nil {
		return o, err
	}
	o.AccessToken = b.Access
	if b.IdToken != "" {
		// decode returned id token to get expiry
		o.AccessToken = b.IdToken
		s := strings.Split(b.IdToken, ".")
		if len(s) < 2 {
			return nil, errors.New("invalid token received")
		}
		d, err := base64Decode(s[1])
		if err != nil {
			return o, err
		}
		c := &ClaimSet{}
		err = json.NewDecoder(bytes.NewBuffer(d)).Decode(c)
		if err != nil {
			return o, err
		}
		o.Expiry = time.Unix(c.Exp, 0)
		return o, nil
	}
	o.Expiry = time.Now().Add(b.ExpiresIn * time.Second)
	return o, nil
}
915257
func newResponse(r *http.Response) *Response {
	body, _ := ioutil.ReadAll(r.Body)
	response := &Response{
		Status: r.Status,
		StatusCode: r.StatusCode,
		Body: string(body),
		ContentLength: r.ContentLength,
		}
	return response
}