repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
letsencrypt/boulder
sa/model.go
Error
func (e errBadJSON) Error() string { return fmt.Sprintf( "%s: error unmarshaling JSON %q: %s", e.msg, string(e.json), e.err) }
go
func (e errBadJSON) Error() string { return fmt.Sprintf( "%s: error unmarshaling JSON %q: %s", e.msg, string(e.json), e.err) }
[ "func", "(", "e", "errBadJSON", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "msg", ",", "string", "(", "e", ".", "json", ")", ",", "e", ".", "err", ")", "\n", "}" ]
// Error returns an error message that includes the json.Unmarshal error as well // as the bad JSON data.
[ "Error", "returns", "an", "error", "message", "that", "includes", "the", "json", ".", "Unmarshal", "error", "as", "well", "as", "the", "bad", "JSON", "data", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L34-L40
train
letsencrypt/boulder
sa/model.go
badJSONError
func badJSONError(msg string, jsonData []byte, err error) error { return errBadJSON{ msg: msg, json: jsonData, err: err, } }
go
func badJSONError(msg string, jsonData []byte, err error) error { return errBadJSON{ msg: msg, json: jsonData, err: err, } }
[ "func", "badJSONError", "(", "msg", "string", ",", "jsonData", "[", "]", "byte", ",", "err", "error", ")", "error", "{", "return", "errBadJSON", "{", "msg", ":", "msg", ",", "json", ":", "jsonData", ",", "err", ":", "err", ",", "}", "\n", "}" ]
// badJSONError is a convenience function for constructing a errBadJSON instance // with the provided args.
[ "badJSONError", "is", "a", "convenience", "function", "for", "constructing", "a", "errBadJSON", "instance", "with", "the", "provided", "args", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L44-L50
train
letsencrypt/boulder
sa/model.go
selectRegistration
func selectRegistration(s dbOneSelector, q string, args ...interface{}) (*regModel, error) { var model regModel err := s.SelectOne( &model, "SELECT "+regFields+" FROM registrations "+q, args..., ) return &model, err }
go
func selectRegistration(s dbOneSelector, q string, args ...interface{}) (*regModel, error) { var model regModel err := s.SelectOne( &model, "SELECT "+regFields+" FROM registrations "+q, args..., ) return &model, err }
[ "func", "selectRegistration", "(", "s", "dbOneSelector", ",", "q", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "*", "regModel", ",", "error", ")", "{", "var", "model", "regModel", "\n", "err", ":=", "s", ".", "SelectOne", "(", "&", "model", ",", "\"", "\"", "+", "regFields", "+", "\"", "\"", "+", "q", ",", "args", "...", ",", ")", "\n", "return", "&", "model", ",", "err", "\n", "}" ]
// selectRegistration selects all fields of one registration model
[ "selectRegistration", "selects", "all", "fields", "of", "one", "registration", "model" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L87-L95
train
letsencrypt/boulder
sa/model.go
selectPendingAuthz
func selectPendingAuthz(s dbOneSelector, q string, args ...interface{}) (*pendingauthzModel, error) { var model pendingauthzModel err := s.SelectOne( &model, "SELECT id, identifier, registrationID, status, expires, LockCol FROM pendingAuthorizations "+q, args..., ) return &model, err }
go
func selectPendingAuthz(s dbOneSelector, q string, args ...interface{}) (*pendingauthzModel, error) { var model pendingauthzModel err := s.SelectOne( &model, "SELECT id, identifier, registrationID, status, expires, LockCol FROM pendingAuthorizations "+q, args..., ) return &model, err }
[ "func", "selectPendingAuthz", "(", "s", "dbOneSelector", ",", "q", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "*", "pendingauthzModel", ",", "error", ")", "{", "var", "model", "pendingauthzModel", "\n", "err", ":=", "s", ".", "SelectOne", "(", "&", "model", ",", "\"", "\"", "+", "q", ",", "args", "...", ",", ")", "\n", "return", "&", "model", ",", "err", "\n", "}" ]
// selectPendingAuthz selects all fields of one pending authorization model
[ "selectPendingAuthz", "selects", "all", "fields", "of", "one", "pending", "authorization", "model" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L98-L106
train
letsencrypt/boulder
sa/model.go
selectAuthz
func selectAuthz(s dbOneSelector, q string, args ...interface{}) (*authzModel, error) { var model authzModel err := s.SelectOne( &model, "SELECT "+authzFields+" FROM authz "+q, args..., ) return &model, err }
go
func selectAuthz(s dbOneSelector, q string, args ...interface{}) (*authzModel, error) { var model authzModel err := s.SelectOne( &model, "SELECT "+authzFields+" FROM authz "+q, args..., ) return &model, err }
[ "func", "selectAuthz", "(", "s", "dbOneSelector", ",", "q", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "*", "authzModel", ",", "error", ")", "{", "var", "model", "authzModel", "\n", "err", ":=", "s", ".", "SelectOne", "(", "&", "model", ",", "\"", "\"", "+", "authzFields", "+", "\"", "\"", "+", "q", ",", "args", "...", ",", ")", "\n", "return", "&", "model", ",", "err", "\n", "}" ]
// selectAuthz selects all fields of one authorization model
[ "selectAuthz", "selects", "all", "fields", "of", "one", "authorization", "model" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L111-L119
train
letsencrypt/boulder
sa/model.go
selectSctReceipt
func selectSctReceipt(s dbOneSelector, q string, args ...interface{}) (core.SignedCertificateTimestamp, error) { var model core.SignedCertificateTimestamp err := s.SelectOne( &model, "SELECT id, sctVersion, logID, timestamp, extensions, signature, certificateSerial, LockCol FROM sctReceipts "+q, args..., ) return model, err }
go
func selectSctReceipt(s dbOneSelector, q string, args ...interface{}) (core.SignedCertificateTimestamp, error) { var model core.SignedCertificateTimestamp err := s.SelectOne( &model, "SELECT id, sctVersion, logID, timestamp, extensions, signature, certificateSerial, LockCol FROM sctReceipts "+q, args..., ) return model, err }
[ "func", "selectSctReceipt", "(", "s", "dbOneSelector", ",", "q", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "core", ".", "SignedCertificateTimestamp", ",", "error", ")", "{", "var", "model", "core", ".", "SignedCertificateTimestamp", "\n", "err", ":=", "s", ".", "SelectOne", "(", "&", "model", ",", "\"", "\"", "+", "q", ",", "args", "...", ",", ")", "\n", "return", "model", ",", "err", "\n", "}" ]
// selectSctReceipt selects all fields of one SignedCertificateTimestamp object
[ "selectSctReceipt", "selects", "all", "fields", "of", "one", "SignedCertificateTimestamp", "object" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L122-L130
train
letsencrypt/boulder
sa/model.go
SelectCertificate
func SelectCertificate(s dbOneSelector, q string, args ...interface{}) (core.Certificate, error) { var model core.Certificate err := s.SelectOne( &model, "SELECT "+certFields+" FROM certificates "+q, args..., ) return model, err }
go
func SelectCertificate(s dbOneSelector, q string, args ...interface{}) (core.Certificate, error) { var model core.Certificate err := s.SelectOne( &model, "SELECT "+certFields+" FROM certificates "+q, args..., ) return model, err }
[ "func", "SelectCertificate", "(", "s", "dbOneSelector", ",", "q", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "core", ".", "Certificate", ",", "error", ")", "{", "var", "model", "core", ".", "Certificate", "\n", "err", ":=", "s", ".", "SelectOne", "(", "&", "model", ",", "\"", "\"", "+", "certFields", "+", "\"", "\"", "+", "q", ",", "args", "...", ",", ")", "\n", "return", "model", ",", "err", "\n", "}" ]
// SelectCertificate selects all fields of one certificate object
[ "SelectCertificate", "selects", "all", "fields", "of", "one", "certificate", "object" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L135-L143
train
letsencrypt/boulder
sa/model.go
SelectCertificates
func SelectCertificates(s dbSelector, q string, args map[string]interface{}) ([]core.Certificate, error) { var models []core.Certificate _, err := s.Select( &models, "SELECT "+certFields+" FROM certificates "+q, args) return models, err }
go
func SelectCertificates(s dbSelector, q string, args map[string]interface{}) ([]core.Certificate, error) { var models []core.Certificate _, err := s.Select( &models, "SELECT "+certFields+" FROM certificates "+q, args) return models, err }
[ "func", "SelectCertificates", "(", "s", "dbSelector", ",", "q", "string", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "[", "]", "core", ".", "Certificate", ",", "error", ")", "{", "var", "models", "[", "]", "core", ".", "Certificate", "\n", "_", ",", "err", ":=", "s", ".", "Select", "(", "&", "models", ",", "\"", "\"", "+", "certFields", "+", "\"", "\"", "+", "q", ",", "args", ")", "\n", "return", "models", ",", "err", "\n", "}" ]
// SelectCertificates selects all fields of multiple certificate objects
[ "SelectCertificates", "selects", "all", "fields", "of", "multiple", "certificate", "objects" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L146-L152
train
letsencrypt/boulder
sa/model.go
SelectCertificateStatus
func SelectCertificateStatus(s dbOneSelector, q string, args ...interface{}) (certStatusModel, error) { var model certStatusModel err := s.SelectOne( &model, "SELECT "+certStatusFields+" FROM certificateStatus "+q, args..., ) return model, err }
go
func SelectCertificateStatus(s dbOneSelector, q string, args ...interface{}) (certStatusModel, error) { var model certStatusModel err := s.SelectOne( &model, "SELECT "+certStatusFields+" FROM certificateStatus "+q, args..., ) return model, err }
[ "func", "SelectCertificateStatus", "(", "s", "dbOneSelector", ",", "q", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "certStatusModel", ",", "error", ")", "{", "var", "model", "certStatusModel", "\n", "err", ":=", "s", ".", "SelectOne", "(", "&", "model", ",", "\"", "\"", "+", "certStatusFields", "+", "\"", "\"", "+", "q", ",", "args", "...", ",", ")", "\n", "return", "model", ",", "err", "\n", "}" ]
// SelectCertificateStatus selects all fields of one certificate status model
[ "SelectCertificateStatus", "selects", "all", "fields", "of", "one", "certificate", "status", "model" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L157-L165
train
letsencrypt/boulder
sa/model.go
SelectCertificateStatuses
func SelectCertificateStatuses(s dbSelector, q string, args ...interface{}) ([]core.CertificateStatus, error) { var models []core.CertificateStatus _, err := s.Select( &models, "SELECT "+certStatusFields+" FROM certificateStatus "+q, args..., ) return models, err }
go
func SelectCertificateStatuses(s dbSelector, q string, args ...interface{}) ([]core.CertificateStatus, error) { var models []core.CertificateStatus _, err := s.Select( &models, "SELECT "+certStatusFields+" FROM certificateStatus "+q, args..., ) return models, err }
[ "func", "SelectCertificateStatuses", "(", "s", "dbSelector", ",", "q", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "[", "]", "core", ".", "CertificateStatus", ",", "error", ")", "{", "var", "models", "[", "]", "core", ".", "CertificateStatus", "\n", "_", ",", "err", ":=", "s", ".", "Select", "(", "&", "models", ",", "\"", "\"", "+", "certStatusFields", "+", "\"", "\"", "+", "q", ",", "args", "...", ",", ")", "\n", "return", "models", ",", "err", "\n", "}" ]
// SelectCertificateStatuses selects all fields of multiple certificate status objects
[ "SelectCertificateStatuses", "selects", "all", "fields", "of", "multiple", "certificate", "status", "objects" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L168-L176
train
letsencrypt/boulder
sa/model.go
registrationToModel
func registrationToModel(r *core.Registration) (*regModel, error) { key, err := json.Marshal(r.Key) if err != nil { return nil, err } sha, err := core.KeyDigest(r.Key) if err != nil { return nil, err } if r.InitialIP == nil { return nil, fmt.Errorf("initialIP was nil") } if r.Contact == nil { r.Contact = &[]string{} } rm := regModel{ ID: r.ID, Key: key, KeySHA256: sha, Contact: *r.Contact, Agreement: r.Agreement, InitialIP: []byte(r.InitialIP.To16()), CreatedAt: r.CreatedAt, Status: string(r.Status), } return &rm, nil }
go
func registrationToModel(r *core.Registration) (*regModel, error) { key, err := json.Marshal(r.Key) if err != nil { return nil, err } sha, err := core.KeyDigest(r.Key) if err != nil { return nil, err } if r.InitialIP == nil { return nil, fmt.Errorf("initialIP was nil") } if r.Contact == nil { r.Contact = &[]string{} } rm := regModel{ ID: r.ID, Key: key, KeySHA256: sha, Contact: *r.Contact, Agreement: r.Agreement, InitialIP: []byte(r.InitialIP.To16()), CreatedAt: r.CreatedAt, Status: string(r.Status), } return &rm, nil }
[ "func", "registrationToModel", "(", "r", "*", "core", ".", "Registration", ")", "(", "*", "regModel", ",", "error", ")", "{", "key", ",", "err", ":=", "json", ".", "Marshal", "(", "r", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "sha", ",", "err", ":=", "core", ".", "KeyDigest", "(", "r", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "r", ".", "InitialIP", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "r", ".", "Contact", "==", "nil", "{", "r", ".", "Contact", "=", "&", "[", "]", "string", "{", "}", "\n", "}", "\n", "rm", ":=", "regModel", "{", "ID", ":", "r", ".", "ID", ",", "Key", ":", "key", ",", "KeySHA256", ":", "sha", ",", "Contact", ":", "*", "r", ".", "Contact", ",", "Agreement", ":", "r", ".", "Agreement", ",", "InitialIP", ":", "[", "]", "byte", "(", "r", ".", "InitialIP", ".", "To16", "(", ")", ")", ",", "CreatedAt", ":", "r", ".", "CreatedAt", ",", "Status", ":", "string", "(", "r", ".", "Status", ")", ",", "}", "\n\n", "return", "&", "rm", ",", "nil", "\n", "}" ]
// newReg creates a reg model object from a core.Registration
[ "newReg", "creates", "a", "reg", "model", "object", "from", "a", "core", ".", "Registration" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L242-L270
train
letsencrypt/boulder
sa/model.go
hasMultipleNonPendingChallenges
func hasMultipleNonPendingChallenges(challenges []*corepb.Challenge) bool { nonPending := false for _, c := range challenges { if *c.Status == string(core.StatusValid) || *c.Status == string(core.StatusInvalid) { if !nonPending { nonPending = true } else { return true } } } return false }
go
func hasMultipleNonPendingChallenges(challenges []*corepb.Challenge) bool { nonPending := false for _, c := range challenges { if *c.Status == string(core.StatusValid) || *c.Status == string(core.StatusInvalid) { if !nonPending { nonPending = true } else { return true } } } return false }
[ "func", "hasMultipleNonPendingChallenges", "(", "challenges", "[", "]", "*", "corepb", ".", "Challenge", ")", "bool", "{", "nonPending", ":=", "false", "\n", "for", "_", ",", "c", ":=", "range", "challenges", "{", "if", "*", "c", ".", "Status", "==", "string", "(", "core", ".", "StatusValid", ")", "||", "*", "c", ".", "Status", "==", "string", "(", "core", ".", "StatusInvalid", ")", "{", "if", "!", "nonPending", "{", "nonPending", "=", "true", "\n", "}", "else", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// hasMultipleNonPendingChallenges checks if a slice of challenges contains // more than one non-pending challenge
[ "hasMultipleNonPendingChallenges", "checks", "if", "a", "slice", "of", "challenges", "contains", "more", "than", "one", "non", "-", "pending", "challenge" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/model.go#L503-L515
train
letsencrypt/boulder
grpc/interceptors.go
observeLatency
func (si *serverInterceptor) observeLatency(clientReqTime string) error { // Convert the metadata request time into an int64 reqTimeUnixNanos, err := strconv.ParseInt(clientReqTime, 10, 64) if err != nil { return berrors.InternalServerError("grpc metadata had illegal %s value: %q - %s", clientRequestTimeKey, clientReqTime, err) } // Calculate the elapsed time since the client sent the RPC reqTime := time.Unix(0, reqTimeUnixNanos) elapsed := si.clk.Since(reqTime) // Publish an RPC latency observation to the histogram si.metrics.rpcLag.Observe(elapsed.Seconds()) return nil }
go
func (si *serverInterceptor) observeLatency(clientReqTime string) error { // Convert the metadata request time into an int64 reqTimeUnixNanos, err := strconv.ParseInt(clientReqTime, 10, 64) if err != nil { return berrors.InternalServerError("grpc metadata had illegal %s value: %q - %s", clientRequestTimeKey, clientReqTime, err) } // Calculate the elapsed time since the client sent the RPC reqTime := time.Unix(0, reqTimeUnixNanos) elapsed := si.clk.Since(reqTime) // Publish an RPC latency observation to the histogram si.metrics.rpcLag.Observe(elapsed.Seconds()) return nil }
[ "func", "(", "si", "*", "serverInterceptor", ")", "observeLatency", "(", "clientReqTime", "string", ")", "error", "{", "// Convert the metadata request time into an int64", "reqTimeUnixNanos", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "clientReqTime", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "clientRequestTimeKey", ",", "clientReqTime", ",", "err", ")", "\n", "}", "\n", "// Calculate the elapsed time since the client sent the RPC", "reqTime", ":=", "time", ".", "Unix", "(", "0", ",", "reqTimeUnixNanos", ")", "\n", "elapsed", ":=", "si", ".", "clk", ".", "Since", "(", "reqTime", ")", "\n", "// Publish an RPC latency observation to the histogram", "si", ".", "metrics", ".", "rpcLag", ".", "Observe", "(", "elapsed", ".", "Seconds", "(", ")", ")", "\n", "return", "nil", "\n", "}" ]
// observeLatency is called with the `clientRequestTimeKey` value from // a request's gRPC metadata. This string value is converted to a timestamp and // used to calcuate the latency between send and receive time. The latency is // published to the server interceptor's rpcLag prometheus histogram. An error // is returned if the `clientReqTime` string is not a valid timestamp.
[ "observeLatency", "is", "called", "with", "the", "clientRequestTimeKey", "value", "from", "a", "request", "s", "gRPC", "metadata", ".", "This", "string", "value", "is", "converted", "to", "a", "timestamp", "and", "used", "to", "calcuate", "the", "latency", "between", "send", "and", "receive", "time", ".", "The", "latency", "is", "published", "to", "the", "server", "interceptor", "s", "rpcLag", "prometheus", "histogram", ".", "An", "error", "is", "returned", "if", "the", "clientReqTime", "string", "is", "not", "a", "valid", "timestamp", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/interceptors.go#L100-L113
train
letsencrypt/boulder
cmd/gen-key/ecdsa.go
ecArgs
func ecArgs(label string, curve *elliptic.CurveParams, keyID []byte) generateArgs { encodedCurve := curveToOIDDER[curve.Name] log.Printf("\tEncoded curve parameters for %s: %X\n", curve.Params().Name, encodedCurve) return generateArgs{ mechanism: []*pkcs11.Mechanism{ pkcs11.NewMechanism(pkcs11.CKM_EC_KEY_PAIR_GEN, nil), }, publicAttrs: []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_ID, keyID), pkcs11.NewAttribute(pkcs11.CKA_LABEL, label), pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true), pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true), pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, encodedCurve), }, privateAttrs: []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_ID, keyID), pkcs11.NewAttribute(pkcs11.CKA_LABEL, label), pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true), // Prevent attributes being retrieved pkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true), // Prevent the key being extracted from the device pkcs11.NewAttribute(pkcs11.CKA_EXTRACTABLE, false), // Allow the key to sign data pkcs11.NewAttribute(pkcs11.CKA_SIGN, true), }, } }
go
func ecArgs(label string, curve *elliptic.CurveParams, keyID []byte) generateArgs { encodedCurve := curveToOIDDER[curve.Name] log.Printf("\tEncoded curve parameters for %s: %X\n", curve.Params().Name, encodedCurve) return generateArgs{ mechanism: []*pkcs11.Mechanism{ pkcs11.NewMechanism(pkcs11.CKM_EC_KEY_PAIR_GEN, nil), }, publicAttrs: []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_ID, keyID), pkcs11.NewAttribute(pkcs11.CKA_LABEL, label), pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true), pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true), pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, encodedCurve), }, privateAttrs: []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_ID, keyID), pkcs11.NewAttribute(pkcs11.CKA_LABEL, label), pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true), // Prevent attributes being retrieved pkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true), // Prevent the key being extracted from the device pkcs11.NewAttribute(pkcs11.CKA_EXTRACTABLE, false), // Allow the key to sign data pkcs11.NewAttribute(pkcs11.CKA_SIGN, true), }, } }
[ "func", "ecArgs", "(", "label", "string", ",", "curve", "*", "elliptic", ".", "CurveParams", ",", "keyID", "[", "]", "byte", ")", "generateArgs", "{", "encodedCurve", ":=", "curveToOIDDER", "[", "curve", ".", "Name", "]", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "curve", ".", "Params", "(", ")", ".", "Name", ",", "encodedCurve", ")", "\n", "return", "generateArgs", "{", "mechanism", ":", "[", "]", "*", "pkcs11", ".", "Mechanism", "{", "pkcs11", ".", "NewMechanism", "(", "pkcs11", ".", "CKM_EC_KEY_PAIR_GEN", ",", "nil", ")", ",", "}", ",", "publicAttrs", ":", "[", "]", "*", "pkcs11", ".", "Attribute", "{", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_ID", ",", "keyID", ")", ",", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_LABEL", ",", "label", ")", ",", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_TOKEN", ",", "true", ")", ",", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_VERIFY", ",", "true", ")", ",", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_EC_PARAMS", ",", "encodedCurve", ")", ",", "}", ",", "privateAttrs", ":", "[", "]", "*", "pkcs11", ".", "Attribute", "{", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_ID", ",", "keyID", ")", ",", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_LABEL", ",", "label", ")", ",", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_TOKEN", ",", "true", ")", ",", "// Prevent attributes being retrieved", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_SENSITIVE", ",", "true", ")", ",", "// Prevent the key being extracted from the device", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_EXTRACTABLE", ",", "false", ")", ",", "// Allow the key to sign data", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_SIGN", ",", "true", ")", ",", "}", ",", "}", "\n", "}" ]
// ecArgs constructs the private and public key template attributes sent to the // device and specifies which mechanism should be used. curve determines which // type of key should be generated.
[ "ecArgs", "constructs", "the", "private", "and", "public", "key", "template", "attributes", "sent", "to", "the", "device", "and", "specifies", "which", "mechanism", "should", "be", "used", ".", "curve", "determines", "which", "type", "of", "key", "should", "be", "generated", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/gen-key/ecdsa.go#L57-L83
train
letsencrypt/boulder
cmd/gen-key/ecdsa.go
ecPub
func ecPub( ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, expectedCurve *elliptic.CurveParams, ) (*ecdsa.PublicKey, error) { pubKey, err := pkcs11helpers.GetECDSAPublicKey(ctx, session, object) if err != nil { return nil, err } if pubKey.Curve != expectedCurve { return nil, errors.New("Returned EC parameters doesn't match expected curve") } log.Printf("\tX: %X\n", pubKey.X.Bytes()) log.Printf("\tY: %X\n", pubKey.Y.Bytes()) return pubKey, nil }
go
func ecPub( ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, expectedCurve *elliptic.CurveParams, ) (*ecdsa.PublicKey, error) { pubKey, err := pkcs11helpers.GetECDSAPublicKey(ctx, session, object) if err != nil { return nil, err } if pubKey.Curve != expectedCurve { return nil, errors.New("Returned EC parameters doesn't match expected curve") } log.Printf("\tX: %X\n", pubKey.X.Bytes()) log.Printf("\tY: %X\n", pubKey.Y.Bytes()) return pubKey, nil }
[ "func", "ecPub", "(", "ctx", "pkcs11helpers", ".", "PKCtx", ",", "session", "pkcs11", ".", "SessionHandle", ",", "object", "pkcs11", ".", "ObjectHandle", ",", "expectedCurve", "*", "elliptic", ".", "CurveParams", ",", ")", "(", "*", "ecdsa", ".", "PublicKey", ",", "error", ")", "{", "pubKey", ",", "err", ":=", "pkcs11helpers", ".", "GetECDSAPublicKey", "(", "ctx", ",", "session", ",", "object", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "pubKey", ".", "Curve", "!=", "expectedCurve", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "pubKey", ".", "X", ".", "Bytes", "(", ")", ")", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "pubKey", ".", "Y", ".", "Bytes", "(", ")", ")", "\n", "return", "pubKey", ",", "nil", "\n", "}" ]
// ecPub extracts the generated public key, specified by the provided object // handle, and constructs an ecdsa.PublicKey. It also checks that the key is of // the correct curve type.
[ "ecPub", "extracts", "the", "generated", "public", "key", "specified", "by", "the", "provided", "object", "handle", "and", "constructs", "an", "ecdsa", ".", "PublicKey", ".", "It", "also", "checks", "that", "the", "key", "is", "of", "the", "correct", "curve", "type", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/gen-key/ecdsa.go#L88-L104
train
letsencrypt/boulder
cmd/gen-key/ecdsa.go
ecVerify
func ecVerify(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, pub *ecdsa.PublicKey) error { nonce, err := getRandomBytes(ctx, session) if err != nil { return fmt.Errorf("failed to construct nonce: %s", err) } log.Printf("\tConstructed nonce: %d (%X)\n", big.NewInt(0).SetBytes(nonce), nonce) hashFunc := curveToHash[pub.Curve.Params()].New() hashFunc.Write(nonce) digest := hashFunc.Sum(nil) log.Printf("\tMessage %s hash: %X\n", hashToString[curveToHash[pub.Curve.Params()]], digest) signature, err := pkcs11helpers.Sign(ctx, session, object, pkcs11helpers.ECDSAKey, digest, curveToHash[pub.Curve.Params()]) if err != nil { return err } log.Printf("\tMessage signature: %X\n", signature) r := big.NewInt(0).SetBytes(signature[:len(signature)/2]) s := big.NewInt(0).SetBytes(signature[len(signature)/2:]) if !ecdsa.Verify(pub, digest[:], r, s) { return errors.New("failed to verify ECDSA signature over test data") } log.Println("\tSignature verified") return nil }
go
func ecVerify(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, pub *ecdsa.PublicKey) error { nonce, err := getRandomBytes(ctx, session) if err != nil { return fmt.Errorf("failed to construct nonce: %s", err) } log.Printf("\tConstructed nonce: %d (%X)\n", big.NewInt(0).SetBytes(nonce), nonce) hashFunc := curveToHash[pub.Curve.Params()].New() hashFunc.Write(nonce) digest := hashFunc.Sum(nil) log.Printf("\tMessage %s hash: %X\n", hashToString[curveToHash[pub.Curve.Params()]], digest) signature, err := pkcs11helpers.Sign(ctx, session, object, pkcs11helpers.ECDSAKey, digest, curveToHash[pub.Curve.Params()]) if err != nil { return err } log.Printf("\tMessage signature: %X\n", signature) r := big.NewInt(0).SetBytes(signature[:len(signature)/2]) s := big.NewInt(0).SetBytes(signature[len(signature)/2:]) if !ecdsa.Verify(pub, digest[:], r, s) { return errors.New("failed to verify ECDSA signature over test data") } log.Println("\tSignature verified") return nil }
[ "func", "ecVerify", "(", "ctx", "pkcs11helpers", ".", "PKCtx", ",", "session", "pkcs11", ".", "SessionHandle", ",", "object", "pkcs11", ".", "ObjectHandle", ",", "pub", "*", "ecdsa", ".", "PublicKey", ")", "error", "{", "nonce", ",", "err", ":=", "getRandomBytes", "(", "ctx", ",", "session", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "big", ".", "NewInt", "(", "0", ")", ".", "SetBytes", "(", "nonce", ")", ",", "nonce", ")", "\n", "hashFunc", ":=", "curveToHash", "[", "pub", ".", "Curve", ".", "Params", "(", ")", "]", ".", "New", "(", ")", "\n", "hashFunc", ".", "Write", "(", "nonce", ")", "\n", "digest", ":=", "hashFunc", ".", "Sum", "(", "nil", ")", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "hashToString", "[", "curveToHash", "[", "pub", ".", "Curve", ".", "Params", "(", ")", "]", "]", ",", "digest", ")", "\n", "signature", ",", "err", ":=", "pkcs11helpers", ".", "Sign", "(", "ctx", ",", "session", ",", "object", ",", "pkcs11helpers", ".", "ECDSAKey", ",", "digest", ",", "curveToHash", "[", "pub", ".", "Curve", ".", "Params", "(", ")", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "signature", ")", "\n", "r", ":=", "big", ".", "NewInt", "(", "0", ")", ".", "SetBytes", "(", "signature", "[", ":", "len", "(", "signature", ")", "/", "2", "]", ")", "\n", "s", ":=", "big", ".", "NewInt", "(", "0", ")", ".", "SetBytes", "(", "signature", "[", "len", "(", "signature", ")", "/", "2", ":", "]", ")", "\n", "if", "!", "ecdsa", ".", "Verify", "(", "pub", ",", "digest", "[", ":", "]", ",", "r", ",", "s", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "log", ".", "Println", "(", "\"", "\\t", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// ecVerify verifies that the extracted public key corresponds with the generated // private key on the device, specified by the provided object handle, by signing // a nonce generated on the device and verifying the returned signature using the // public key.
[ "ecVerify", "verifies", "that", "the", "extracted", "public", "key", "corresponds", "with", "the", "generated", "private", "key", "on", "the", "device", "specified", "by", "the", "provided", "object", "handle", "by", "signing", "a", "nonce", "generated", "on", "the", "device", "and", "verifying", "the", "returned", "signature", "using", "the", "public", "key", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/gen-key/ecdsa.go#L110-L132
train
letsencrypt/boulder
cmd/gen-key/ecdsa.go
ecGenerate
func ecGenerate(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, label, curveStr string) (*ecdsa.PublicKey, error) { curve, present := stringToCurve[curveStr] if !present { return nil, fmt.Errorf("curve %q not supported", curveStr) } keyID := make([]byte, 4) _, err := rand.Read(keyID) if err != nil { return nil, err } log.Printf("Generating ECDSA key with curve %s and ID %x\n", curveStr, keyID) args := ecArgs(label, curve, keyID) pub, priv, err := ctx.GenerateKeyPair(session, args.mechanism, args.publicAttrs, args.privateAttrs) if err != nil { return nil, err } log.Println("Key generated") log.Println("Extracting public key") pk, err := ecPub(ctx, session, pub, curve) if err != nil { return nil, err } log.Println("Extracted public key") log.Println("Verifying public key") err = ecVerify(ctx, session, priv, pk) if err != nil { return nil, err } log.Println("Key verified") return pk, nil }
go
func ecGenerate(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, label, curveStr string) (*ecdsa.PublicKey, error) { curve, present := stringToCurve[curveStr] if !present { return nil, fmt.Errorf("curve %q not supported", curveStr) } keyID := make([]byte, 4) _, err := rand.Read(keyID) if err != nil { return nil, err } log.Printf("Generating ECDSA key with curve %s and ID %x\n", curveStr, keyID) args := ecArgs(label, curve, keyID) pub, priv, err := ctx.GenerateKeyPair(session, args.mechanism, args.publicAttrs, args.privateAttrs) if err != nil { return nil, err } log.Println("Key generated") log.Println("Extracting public key") pk, err := ecPub(ctx, session, pub, curve) if err != nil { return nil, err } log.Println("Extracted public key") log.Println("Verifying public key") err = ecVerify(ctx, session, priv, pk) if err != nil { return nil, err } log.Println("Key verified") return pk, nil }
[ "func", "ecGenerate", "(", "ctx", "pkcs11helpers", ".", "PKCtx", ",", "session", "pkcs11", ".", "SessionHandle", ",", "label", ",", "curveStr", "string", ")", "(", "*", "ecdsa", ".", "PublicKey", ",", "error", ")", "{", "curve", ",", "present", ":=", "stringToCurve", "[", "curveStr", "]", "\n", "if", "!", "present", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "curveStr", ")", "\n", "}", "\n", "keyID", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "_", ",", "err", ":=", "rand", ".", "Read", "(", "keyID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "curveStr", ",", "keyID", ")", "\n", "args", ":=", "ecArgs", "(", "label", ",", "curve", ",", "keyID", ")", "\n", "pub", ",", "priv", ",", "err", ":=", "ctx", ".", "GenerateKeyPair", "(", "session", ",", "args", ".", "mechanism", ",", "args", ".", "publicAttrs", ",", "args", ".", "privateAttrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "pk", ",", "err", ":=", "ecPub", "(", "ctx", ",", "session", ",", "pub", ",", "curve", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "err", "=", "ecVerify", "(", "ctx", ",", "session", ",", "priv", ",", "pk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "pk", ",", "nil", "\n", "}" ]
// ecGenerate is used to generate and verify a ECDSA key pair of the type // specified by curveStr and with the provided label. It returns the public // part of the generated key pair as a ecdsa.PublicKey.
[ "ecGenerate", "is", "used", "to", "generate", "and", "verify", "a", "ECDSA", "key", "pair", "of", "the", "type", "specified", "by", "curveStr", "and", "with", "the", "provided", "label", ".", "It", "returns", "the", "public", "part", "of", "the", "generated", "key", "pair", "as", "a", "ecdsa", ".", "PublicKey", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/gen-key/ecdsa.go#L137-L167
train
letsencrypt/boulder
va/http.go
DialContext
func (d *preresolvedDialer) DialContext( ctx context.Context, network, origAddr string) (net.Conn, error) { deadline, ok := ctx.Deadline() if !ok { // Shouldn't happen: All requests should have a deadline by this point. deadline = time.Now().Add(100 * time.Second) } else { // Set the context deadline slightly shorter than the HTTP deadline, so we // get a useful error rather than a generic "deadline exceeded" error. This // lets us give a more specific error to the subscriber. deadline = deadline.Add(-10 * time.Millisecond) } ctx, cancel := context.WithDeadline(ctx, deadline) defer cancel() // NOTE(@cpu): I don't capture and check the origPort here because using // `net.SplitHostPort` and also supporting the va's custom httpPort and // httpsPort is cumbersome. The initial origAddr may be "example.com:80" // if the URL used for the dial input was "http://example.com" without an // explicit port. Checking for equality here will fail unless we add // special case logic for converting 80/443 -> httpPort/httpsPort when // configured. This seems more likely to cause bugs than catch them so I'm // ignoring this for now. In the future if we remove the httpPort/httpsPort // (we should!) we can also easily enforce that the preresolved dialer port // matches expected here. origHost, _, err := net.SplitHostPort(origAddr) if err != nil { return nil, err } // If the hostname we're dialing isn't equal to the hostname the dialer was // constructed for then a bug has occurred where we've mismatched the // preresolved dialer. if origHost != d.hostname { return nil, &dialerMismatchError{ dialerHost: d.hostname, dialerIP: d.ip.String(), dialerPort: d.port, host: origHost, } } // Make a new dial address using the pre-resolved IP and port. targetAddr := net.JoinHostPort(d.ip.String(), strconv.Itoa(d.port)) // Create a throw-away dialer using default values and the dialer timeout // (populated from the VA singleDialTimeout). throwAwayDialer := &net.Dialer{ Timeout: d.timeout, // Default KeepAlive - see Golang src/net/http/transport.go DefaultTransport KeepAlive: 30 * time.Second, } return throwAwayDialer.DialContext(ctx, network, targetAddr) }
go
func (d *preresolvedDialer) DialContext( ctx context.Context, network, origAddr string) (net.Conn, error) { deadline, ok := ctx.Deadline() if !ok { // Shouldn't happen: All requests should have a deadline by this point. deadline = time.Now().Add(100 * time.Second) } else { // Set the context deadline slightly shorter than the HTTP deadline, so we // get a useful error rather than a generic "deadline exceeded" error. This // lets us give a more specific error to the subscriber. deadline = deadline.Add(-10 * time.Millisecond) } ctx, cancel := context.WithDeadline(ctx, deadline) defer cancel() // NOTE(@cpu): I don't capture and check the origPort here because using // `net.SplitHostPort` and also supporting the va's custom httpPort and // httpsPort is cumbersome. The initial origAddr may be "example.com:80" // if the URL used for the dial input was "http://example.com" without an // explicit port. Checking for equality here will fail unless we add // special case logic for converting 80/443 -> httpPort/httpsPort when // configured. This seems more likely to cause bugs than catch them so I'm // ignoring this for now. In the future if we remove the httpPort/httpsPort // (we should!) we can also easily enforce that the preresolved dialer port // matches expected here. origHost, _, err := net.SplitHostPort(origAddr) if err != nil { return nil, err } // If the hostname we're dialing isn't equal to the hostname the dialer was // constructed for then a bug has occurred where we've mismatched the // preresolved dialer. if origHost != d.hostname { return nil, &dialerMismatchError{ dialerHost: d.hostname, dialerIP: d.ip.String(), dialerPort: d.port, host: origHost, } } // Make a new dial address using the pre-resolved IP and port. targetAddr := net.JoinHostPort(d.ip.String(), strconv.Itoa(d.port)) // Create a throw-away dialer using default values and the dialer timeout // (populated from the VA singleDialTimeout). throwAwayDialer := &net.Dialer{ Timeout: d.timeout, // Default KeepAlive - see Golang src/net/http/transport.go DefaultTransport KeepAlive: 30 * time.Second, } return throwAwayDialer.DialContext(ctx, network, targetAddr) }
[ "func", "(", "d", "*", "preresolvedDialer", ")", "DialContext", "(", "ctx", "context", ".", "Context", ",", "network", ",", "origAddr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "deadline", ",", "ok", ":=", "ctx", ".", "Deadline", "(", ")", "\n", "if", "!", "ok", "{", "// Shouldn't happen: All requests should have a deadline by this point.", "deadline", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "100", "*", "time", ".", "Second", ")", "\n", "}", "else", "{", "// Set the context deadline slightly shorter than the HTTP deadline, so we", "// get a useful error rather than a generic \"deadline exceeded\" error. This", "// lets us give a more specific error to the subscriber.", "deadline", "=", "deadline", ".", "Add", "(", "-", "10", "*", "time", ".", "Millisecond", ")", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithDeadline", "(", "ctx", ",", "deadline", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "// NOTE(@cpu): I don't capture and check the origPort here because using", "// `net.SplitHostPort` and also supporting the va's custom httpPort and", "// httpsPort is cumbersome. The initial origAddr may be \"example.com:80\"", "// if the URL used for the dial input was \"http://example.com\" without an", "// explicit port. Checking for equality here will fail unless we add", "// special case logic for converting 80/443 -> httpPort/httpsPort when", "// configured. This seems more likely to cause bugs than catch them so I'm", "// ignoring this for now. In the future if we remove the httpPort/httpsPort", "// (we should!) we can also easily enforce that the preresolved dialer port", "// matches expected here.", "origHost", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "origAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// If the hostname we're dialing isn't equal to the hostname the dialer was", "// constructed for then a bug has occurred where we've mismatched the", "// preresolved dialer.", "if", "origHost", "!=", "d", ".", "hostname", "{", "return", "nil", ",", "&", "dialerMismatchError", "{", "dialerHost", ":", "d", ".", "hostname", ",", "dialerIP", ":", "d", ".", "ip", ".", "String", "(", ")", ",", "dialerPort", ":", "d", ".", "port", ",", "host", ":", "origHost", ",", "}", "\n", "}", "\n\n", "// Make a new dial address using the pre-resolved IP and port.", "targetAddr", ":=", "net", ".", "JoinHostPort", "(", "d", ".", "ip", ".", "String", "(", ")", ",", "strconv", ".", "Itoa", "(", "d", ".", "port", ")", ")", "\n\n", "// Create a throw-away dialer using default values and the dialer timeout", "// (populated from the VA singleDialTimeout).", "throwAwayDialer", ":=", "&", "net", ".", "Dialer", "{", "Timeout", ":", "d", ".", "timeout", ",", "// Default KeepAlive - see Golang src/net/http/transport.go DefaultTransport", "KeepAlive", ":", "30", "*", "time", ".", "Second", ",", "}", "\n", "return", "throwAwayDialer", ".", "DialContext", "(", "ctx", ",", "network", ",", "targetAddr", ")", "\n", "}" ]
// DialContext for a preresolvedDialer shaves 10ms off of the context it was // given before calling the default transport DialContext using the pre-resolved // IP and port as the host. If the original host being dialed by DialContext // does not match the expected hostname in the preresolvedDialer an error will // be returned instead. This helps prevents a bug that might use // a preresolvedDialer for the wrong host. // // Shaving the context helps us be able to differentiate between timeouts during // connect and timeouts after connect. // // Using preresolved information for the host argument given to the real // transport dial lets us have fine grained control over IP address resolution for // domain names.
[ "DialContext", "for", "a", "preresolvedDialer", "shaves", "10ms", "off", "of", "the", "context", "it", "was", "given", "before", "calling", "the", "default", "transport", "DialContext", "using", "the", "pre", "-", "resolved", "IP", "and", "port", "as", "the", "host", ".", "If", "the", "original", "host", "being", "dialed", "by", "DialContext", "does", "not", "match", "the", "expected", "hostname", "in", "the", "preresolvedDialer", "an", "error", "will", "be", "returned", "instead", ".", "This", "helps", "prevents", "a", "bug", "that", "might", "use", "a", "preresolvedDialer", "for", "the", "wrong", "host", ".", "Shaving", "the", "context", "helps", "us", "be", "able", "to", "differentiate", "between", "timeouts", "during", "connect", "and", "timeouts", "after", "connect", ".", "Using", "preresolved", "information", "for", "the", "host", "argument", "given", "to", "the", "real", "transport", "dial", "lets", "us", "have", "fine", "grained", "control", "over", "IP", "address", "resolution", "for", "domain", "names", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/http.go#L78-L132
train
letsencrypt/boulder
va/http.go
httpTransport
func httpTransport(df dialerFunc) *http.Transport { return &http.Transport{ DialContext: df, // We are talking to a client that does not yet have a certificate, // so we accept a temporary, invalid one. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't expect to make multiple requests to a client, so close // connection immediately. DisableKeepAlives: true, // We don't want idle connections, but 0 means "unlimited," so we pick 1. MaxIdleConns: 1, IdleConnTimeout: time.Second, TLSHandshakeTimeout: 10 * time.Second, } }
go
func httpTransport(df dialerFunc) *http.Transport { return &http.Transport{ DialContext: df, // We are talking to a client that does not yet have a certificate, // so we accept a temporary, invalid one. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't expect to make multiple requests to a client, so close // connection immediately. DisableKeepAlives: true, // We don't want idle connections, but 0 means "unlimited," so we pick 1. MaxIdleConns: 1, IdleConnTimeout: time.Second, TLSHandshakeTimeout: 10 * time.Second, } }
[ "func", "httpTransport", "(", "df", "dialerFunc", ")", "*", "http", ".", "Transport", "{", "return", "&", "http", ".", "Transport", "{", "DialContext", ":", "df", ",", "// We are talking to a client that does not yet have a certificate,", "// so we accept a temporary, invalid one.", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", "}", ",", "// We don't expect to make multiple requests to a client, so close", "// connection immediately.", "DisableKeepAlives", ":", "true", ",", "// We don't want idle connections, but 0 means \"unlimited,\" so we pick 1.", "MaxIdleConns", ":", "1", ",", "IdleConnTimeout", ":", "time", ".", "Second", ",", "TLSHandshakeTimeout", ":", "10", "*", "time", ".", "Second", ",", "}", "\n", "}" ]
// httpTransport constructs a HTTP Transport with settings appropriate for // HTTP-01 validation. The provided dialerFunc is used as the Transport's // DialContext handler.
[ "httpTransport", "constructs", "a", "HTTP", "Transport", "with", "settings", "appropriate", "for", "HTTP", "-", "01", "validation", ".", "The", "provided", "dialerFunc", "is", "used", "as", "the", "Transport", "s", "DialContext", "handler", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/http.go#L141-L155
train
letsencrypt/boulder
va/http.go
newHTTPValidationTarget
func (va *ValidationAuthorityImpl) newHTTPValidationTarget( ctx context.Context, host string, port int, path string, query string) (*httpValidationTarget, error) { // Resolve IP addresses for the hostname addrs, err := va.getAddrs(ctx, host) if err != nil { // Convert the error into a ConnectionFailureError so it is presented to the // end user in a problem after being fed through detailedError. return nil, berrors.ConnectionFailureError(err.Error()) } target := &httpValidationTarget{ host: host, port: port, path: path, query: query, available: addrs, } // Separate the addresses into the available v4 and v6 addresses v4Addrs, v6Addrs := availableAddresses(addrs) hasV6Addrs := len(v6Addrs) > 0 hasV4Addrs := len(v4Addrs) > 0 if !hasV6Addrs && !hasV4Addrs { // If there are no v6 addrs and no v4addrs there was a bug with getAddrs or // availableAddresses and we need to return an error. return nil, fmt.Errorf("host %q has no IPv4 or IPv6 addresses", host) } else if !hasV6Addrs && hasV4Addrs { // If there are no v6 addrs and there are v4 addrs then use the first v4 // address. There's no fallback address. target.next = []net.IP{v4Addrs[0]} } else if hasV6Addrs && hasV4Addrs { // If there are both v6 addrs and v4 addrs then use the first v6 address and // fallback with the first v4 address. target.next = []net.IP{v6Addrs[0], v4Addrs[0]} } else if hasV6Addrs && !hasV4Addrs { // If there are just v6 addrs then use the first v6 address. There's no // fallback address. target.next = []net.IP{v6Addrs[0]} } // Advance the target using nextIP to populate the cur IP before returning _ = target.nextIP() return target, nil }
go
func (va *ValidationAuthorityImpl) newHTTPValidationTarget( ctx context.Context, host string, port int, path string, query string) (*httpValidationTarget, error) { // Resolve IP addresses for the hostname addrs, err := va.getAddrs(ctx, host) if err != nil { // Convert the error into a ConnectionFailureError so it is presented to the // end user in a problem after being fed through detailedError. return nil, berrors.ConnectionFailureError(err.Error()) } target := &httpValidationTarget{ host: host, port: port, path: path, query: query, available: addrs, } // Separate the addresses into the available v4 and v6 addresses v4Addrs, v6Addrs := availableAddresses(addrs) hasV6Addrs := len(v6Addrs) > 0 hasV4Addrs := len(v4Addrs) > 0 if !hasV6Addrs && !hasV4Addrs { // If there are no v6 addrs and no v4addrs there was a bug with getAddrs or // availableAddresses and we need to return an error. return nil, fmt.Errorf("host %q has no IPv4 or IPv6 addresses", host) } else if !hasV6Addrs && hasV4Addrs { // If there are no v6 addrs and there are v4 addrs then use the first v4 // address. There's no fallback address. target.next = []net.IP{v4Addrs[0]} } else if hasV6Addrs && hasV4Addrs { // If there are both v6 addrs and v4 addrs then use the first v6 address and // fallback with the first v4 address. target.next = []net.IP{v6Addrs[0], v4Addrs[0]} } else if hasV6Addrs && !hasV4Addrs { // If there are just v6 addrs then use the first v6 address. There's no // fallback address. target.next = []net.IP{v6Addrs[0]} } // Advance the target using nextIP to populate the cur IP before returning _ = target.nextIP() return target, nil }
[ "func", "(", "va", "*", "ValidationAuthorityImpl", ")", "newHTTPValidationTarget", "(", "ctx", "context", ".", "Context", ",", "host", "string", ",", "port", "int", ",", "path", "string", ",", "query", "string", ")", "(", "*", "httpValidationTarget", ",", "error", ")", "{", "// Resolve IP addresses for the hostname", "addrs", ",", "err", ":=", "va", ".", "getAddrs", "(", "ctx", ",", "host", ")", "\n", "if", "err", "!=", "nil", "{", "// Convert the error into a ConnectionFailureError so it is presented to the", "// end user in a problem after being fed through detailedError.", "return", "nil", ",", "berrors", ".", "ConnectionFailureError", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "target", ":=", "&", "httpValidationTarget", "{", "host", ":", "host", ",", "port", ":", "port", ",", "path", ":", "path", ",", "query", ":", "query", ",", "available", ":", "addrs", ",", "}", "\n\n", "// Separate the addresses into the available v4 and v6 addresses", "v4Addrs", ",", "v6Addrs", ":=", "availableAddresses", "(", "addrs", ")", "\n", "hasV6Addrs", ":=", "len", "(", "v6Addrs", ")", ">", "0", "\n", "hasV4Addrs", ":=", "len", "(", "v4Addrs", ")", ">", "0", "\n\n", "if", "!", "hasV6Addrs", "&&", "!", "hasV4Addrs", "{", "// If there are no v6 addrs and no v4addrs there was a bug with getAddrs or", "// availableAddresses and we need to return an error.", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "host", ")", "\n", "}", "else", "if", "!", "hasV6Addrs", "&&", "hasV4Addrs", "{", "// If there are no v6 addrs and there are v4 addrs then use the first v4", "// address. There's no fallback address.", "target", ".", "next", "=", "[", "]", "net", ".", "IP", "{", "v4Addrs", "[", "0", "]", "}", "\n", "}", "else", "if", "hasV6Addrs", "&&", "hasV4Addrs", "{", "// If there are both v6 addrs and v4 addrs then use the first v6 address and", "// fallback with the first v4 address.", "target", ".", "next", "=", "[", "]", "net", ".", "IP", "{", "v6Addrs", "[", "0", "]", ",", "v4Addrs", "[", "0", "]", "}", "\n", "}", "else", "if", "hasV6Addrs", "&&", "!", "hasV4Addrs", "{", "// If there are just v6 addrs then use the first v6 address. There's no", "// fallback address.", "target", ".", "next", "=", "[", "]", "net", ".", "IP", "{", "v6Addrs", "[", "0", "]", "}", "\n", "}", "\n\n", "// Advance the target using nextIP to populate the cur IP before returning", "_", "=", "target", ".", "nextIP", "(", ")", "\n", "return", "target", ",", "nil", "\n", "}" ]
// newHTTPValidationTarget creates a httpValidationTarget for the given host, // port, and path. This involves querying DNS for the IP addresses for the host. // An error is returned if there are no usable IP addresses or if the DNS // lookups fail.
[ "newHTTPValidationTarget", "creates", "a", "httpValidationTarget", "for", "the", "given", "host", "port", "and", "path", ".", "This", "involves", "querying", "DNS", "for", "the", "IP", "addresses", "for", "the", "host", ".", "An", "error", "is", "returned", "if", "there", "are", "no", "usable", "IP", "addresses", "or", "if", "the", "DNS", "lookups", "fail", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/http.go#L206-L254
train
letsencrypt/boulder
va/http.go
extractRequestTarget
func (va *ValidationAuthorityImpl) extractRequestTarget(req *http.Request) (string, int, error) { // A nil request is certainly not a valid redirect and has no port to extract. if req == nil { return "", 0, fmt.Errorf("redirect HTTP request was nil") } reqScheme := req.URL.Scheme // The redirect request must use HTTP or HTTPs protocol schemes regardless of the port.. if reqScheme != "http" && reqScheme != "https" { return "", 0, berrors.ConnectionFailureError( "Invalid protocol scheme in redirect target. "+ `Only "http" and "https" protocol schemes are supported, not %q`, reqScheme) } // Try and split an explicit port number from the request URL host. If there is // one we need to make sure its a valid port. If there isn't one we need to // pick the port based on the reqScheme default port. reqHost := req.URL.Host reqPort := 0 if h, p, err := net.SplitHostPort(reqHost); err == nil { reqHost = h reqPort, err = strconv.Atoi(p) if err != nil { return "", 0, err } // The explicit port must match the VA's configured HTTP or HTTPS port. if reqPort != va.httpPort && reqPort != va.httpsPort { return "", 0, berrors.ConnectionFailureError( "Invalid port in redirect target. Only ports %d and %d are supported, not %d", va.httpPort, va.httpsPort, reqPort) } } else if reqScheme == "http" { reqPort = va.httpPort } else if reqScheme == "https" { reqPort = va.httpsPort } else { // This shouldn't happen but defensively return an internal server error in // case it does. return "", 0, fmt.Errorf("unable to determine redirect HTTP request port") } if reqHost == "" { return "", 0, berrors.ConnectionFailureError("Invalid empty hostname in redirect target") } // Check that the request host isn't a bare IP address. We only follow // redirects to hostnames. if net.ParseIP(reqHost) != nil { return "", 0, berrors.ConnectionFailureError( "Invalid host in redirect target %q. "+ "Only domain names are supported, not IP addresses", reqHost) } // Often folks will misconfigure their webserver to send an HTTP redirect // missing a `/' between the FQDN and the path. E.g. in Apache using: // Redirect / https://bad-redirect.org // Instead of // Redirect / https://bad-redirect.org/ // Will produce an invalid HTTP-01 redirect target like: // https://bad-redirect.org.well-known/acme-challenge/xxxx // This happens frequently enough we want to return a distinct error message // for this case by detecting the reqHost ending in ".well-known". if strings.HasSuffix(reqHost, ".well-known") { return "", 0, berrors.ConnectionFailureError( "Invalid host in redirect target %q. Check webserver config for missing '/' in redirect target.", reqHost, ) } if _, err := iana.ExtractSuffix(reqHost); err != nil { return "", 0, berrors.ConnectionFailureError( "Invalid hostname in redirect target, must end in IANA registered TLD") } return reqHost, reqPort, nil }
go
func (va *ValidationAuthorityImpl) extractRequestTarget(req *http.Request) (string, int, error) { // A nil request is certainly not a valid redirect and has no port to extract. if req == nil { return "", 0, fmt.Errorf("redirect HTTP request was nil") } reqScheme := req.URL.Scheme // The redirect request must use HTTP or HTTPs protocol schemes regardless of the port.. if reqScheme != "http" && reqScheme != "https" { return "", 0, berrors.ConnectionFailureError( "Invalid protocol scheme in redirect target. "+ `Only "http" and "https" protocol schemes are supported, not %q`, reqScheme) } // Try and split an explicit port number from the request URL host. If there is // one we need to make sure its a valid port. If there isn't one we need to // pick the port based on the reqScheme default port. reqHost := req.URL.Host reqPort := 0 if h, p, err := net.SplitHostPort(reqHost); err == nil { reqHost = h reqPort, err = strconv.Atoi(p) if err != nil { return "", 0, err } // The explicit port must match the VA's configured HTTP or HTTPS port. if reqPort != va.httpPort && reqPort != va.httpsPort { return "", 0, berrors.ConnectionFailureError( "Invalid port in redirect target. Only ports %d and %d are supported, not %d", va.httpPort, va.httpsPort, reqPort) } } else if reqScheme == "http" { reqPort = va.httpPort } else if reqScheme == "https" { reqPort = va.httpsPort } else { // This shouldn't happen but defensively return an internal server error in // case it does. return "", 0, fmt.Errorf("unable to determine redirect HTTP request port") } if reqHost == "" { return "", 0, berrors.ConnectionFailureError("Invalid empty hostname in redirect target") } // Check that the request host isn't a bare IP address. We only follow // redirects to hostnames. if net.ParseIP(reqHost) != nil { return "", 0, berrors.ConnectionFailureError( "Invalid host in redirect target %q. "+ "Only domain names are supported, not IP addresses", reqHost) } // Often folks will misconfigure their webserver to send an HTTP redirect // missing a `/' between the FQDN and the path. E.g. in Apache using: // Redirect / https://bad-redirect.org // Instead of // Redirect / https://bad-redirect.org/ // Will produce an invalid HTTP-01 redirect target like: // https://bad-redirect.org.well-known/acme-challenge/xxxx // This happens frequently enough we want to return a distinct error message // for this case by detecting the reqHost ending in ".well-known". if strings.HasSuffix(reqHost, ".well-known") { return "", 0, berrors.ConnectionFailureError( "Invalid host in redirect target %q. Check webserver config for missing '/' in redirect target.", reqHost, ) } if _, err := iana.ExtractSuffix(reqHost); err != nil { return "", 0, berrors.ConnectionFailureError( "Invalid hostname in redirect target, must end in IANA registered TLD") } return reqHost, reqPort, nil }
[ "func", "(", "va", "*", "ValidationAuthorityImpl", ")", "extractRequestTarget", "(", "req", "*", "http", ".", "Request", ")", "(", "string", ",", "int", ",", "error", ")", "{", "// A nil request is certainly not a valid redirect and has no port to extract.", "if", "req", "==", "nil", "{", "return", "\"", "\"", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "reqScheme", ":=", "req", ".", "URL", ".", "Scheme", "\n\n", "// The redirect request must use HTTP or HTTPs protocol schemes regardless of the port..", "if", "reqScheme", "!=", "\"", "\"", "&&", "reqScheme", "!=", "\"", "\"", "{", "return", "\"", "\"", ",", "0", ",", "berrors", ".", "ConnectionFailureError", "(", "\"", "\"", "+", "`Only \"http\" and \"https\" protocol schemes are supported, not %q`", ",", "reqScheme", ")", "\n", "}", "\n\n", "// Try and split an explicit port number from the request URL host. If there is", "// one we need to make sure its a valid port. If there isn't one we need to", "// pick the port based on the reqScheme default port.", "reqHost", ":=", "req", ".", "URL", ".", "Host", "\n", "reqPort", ":=", "0", "\n", "if", "h", ",", "p", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "reqHost", ")", ";", "err", "==", "nil", "{", "reqHost", "=", "h", "\n", "reqPort", ",", "err", "=", "strconv", ".", "Atoi", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "0", ",", "err", "\n", "}", "\n\n", "// The explicit port must match the VA's configured HTTP or HTTPS port.", "if", "reqPort", "!=", "va", ".", "httpPort", "&&", "reqPort", "!=", "va", ".", "httpsPort", "{", "return", "\"", "\"", ",", "0", ",", "berrors", ".", "ConnectionFailureError", "(", "\"", "\"", ",", "va", ".", "httpPort", ",", "va", ".", "httpsPort", ",", "reqPort", ")", "\n", "}", "\n", "}", "else", "if", "reqScheme", "==", "\"", "\"", "{", "reqPort", "=", "va", ".", "httpPort", "\n", "}", "else", "if", "reqScheme", "==", "\"", "\"", "{", "reqPort", "=", "va", ".", "httpsPort", "\n", "}", "else", "{", "// This shouldn't happen but defensively return an internal server error in", "// case it does.", "return", "\"", "\"", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "reqHost", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "0", ",", "berrors", ".", "ConnectionFailureError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check that the request host isn't a bare IP address. We only follow", "// redirects to hostnames.", "if", "net", ".", "ParseIP", "(", "reqHost", ")", "!=", "nil", "{", "return", "\"", "\"", ",", "0", ",", "berrors", ".", "ConnectionFailureError", "(", "\"", "\"", "+", "\"", "\"", ",", "reqHost", ")", "\n", "}", "\n\n", "// Often folks will misconfigure their webserver to send an HTTP redirect", "// missing a `/' between the FQDN and the path. E.g. in Apache using:", "// Redirect / https://bad-redirect.org", "// Instead of", "// Redirect / https://bad-redirect.org/", "// Will produce an invalid HTTP-01 redirect target like:", "// https://bad-redirect.org.well-known/acme-challenge/xxxx", "// This happens frequently enough we want to return a distinct error message", "// for this case by detecting the reqHost ending in \".well-known\".", "if", "strings", ".", "HasSuffix", "(", "reqHost", ",", "\"", "\"", ")", "{", "return", "\"", "\"", ",", "0", ",", "berrors", ".", "ConnectionFailureError", "(", "\"", "\"", ",", "reqHost", ",", ")", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "iana", ".", "ExtractSuffix", "(", "reqHost", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "0", ",", "berrors", ".", "ConnectionFailureError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "reqHost", ",", "reqPort", ",", "nil", "\n", "}" ]
// extractRequestTarget extracts the hostname and port specified in the provided // HTTP redirect request. If the request's URL's protocol schema is not HTTP or // HTTPS an error is returned. If an explicit port is specified in the request's // URL and it isn't the VA's HTTP or HTTPS port, an error is returned. If the // request's URL's Host is a bare IPv4 or IPv6 address and not a domain name an // error is returned.
[ "extractRequestTarget", "extracts", "the", "hostname", "and", "port", "specified", "in", "the", "provided", "HTTP", "redirect", "request", ".", "If", "the", "request", "s", "URL", "s", "protocol", "schema", "is", "not", "HTTP", "or", "HTTPS", "an", "error", "is", "returned", ".", "If", "an", "explicit", "port", "is", "specified", "in", "the", "request", "s", "URL", "and", "it", "isn", "t", "the", "VA", "s", "HTTP", "or", "HTTPS", "port", "an", "error", "is", "returned", ".", "If", "the", "request", "s", "URL", "s", "Host", "is", "a", "bare", "IPv4", "or", "IPv6", "address", "and", "not", "a", "domain", "name", "an", "error", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/http.go#L262-L339
train
letsencrypt/boulder
va/http.go
setupHTTPValidation
func (va *ValidationAuthorityImpl) setupHTTPValidation( ctx context.Context, reqURL string, target *httpValidationTarget) (*preresolvedDialer, core.ValidationRecord, error) { if reqURL == "" { return nil, core.ValidationRecord{}, fmt.Errorf("reqURL can not be nil") } if target == nil { // This is the only case where returning an empty validation record makes // sense - we can't construct a better one, something has gone quite wrong. return nil, core.ValidationRecord{}, fmt.Errorf("httpValidationTarget can not be nil") } // Construct a base validation record with the validation target's // information. record := core.ValidationRecord{ Hostname: target.host, Port: strconv.Itoa(target.port), AddressesResolved: target.available, URL: reqURL, } // Get the target IP to build a preresolved dialer with targetIP := target.ip() if targetIP == nil { return nil, record, fmt.Errorf( "host %q has no IP addresses remaining to use", target.host) } record.AddressUsed = targetIP dialer := &preresolvedDialer{ ip: targetIP, port: target.port, hostname: target.host, timeout: va.singleDialTimeout, } return dialer, record, nil }
go
func (va *ValidationAuthorityImpl) setupHTTPValidation( ctx context.Context, reqURL string, target *httpValidationTarget) (*preresolvedDialer, core.ValidationRecord, error) { if reqURL == "" { return nil, core.ValidationRecord{}, fmt.Errorf("reqURL can not be nil") } if target == nil { // This is the only case where returning an empty validation record makes // sense - we can't construct a better one, something has gone quite wrong. return nil, core.ValidationRecord{}, fmt.Errorf("httpValidationTarget can not be nil") } // Construct a base validation record with the validation target's // information. record := core.ValidationRecord{ Hostname: target.host, Port: strconv.Itoa(target.port), AddressesResolved: target.available, URL: reqURL, } // Get the target IP to build a preresolved dialer with targetIP := target.ip() if targetIP == nil { return nil, record, fmt.Errorf( "host %q has no IP addresses remaining to use", target.host) } record.AddressUsed = targetIP dialer := &preresolvedDialer{ ip: targetIP, port: target.port, hostname: target.host, timeout: va.singleDialTimeout, } return dialer, record, nil }
[ "func", "(", "va", "*", "ValidationAuthorityImpl", ")", "setupHTTPValidation", "(", "ctx", "context", ".", "Context", ",", "reqURL", "string", ",", "target", "*", "httpValidationTarget", ")", "(", "*", "preresolvedDialer", ",", "core", ".", "ValidationRecord", ",", "error", ")", "{", "if", "reqURL", "==", "\"", "\"", "{", "return", "nil", ",", "core", ".", "ValidationRecord", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "target", "==", "nil", "{", "// This is the only case where returning an empty validation record makes", "// sense - we can't construct a better one, something has gone quite wrong.", "return", "nil", ",", "core", ".", "ValidationRecord", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Construct a base validation record with the validation target's", "// information.", "record", ":=", "core", ".", "ValidationRecord", "{", "Hostname", ":", "target", ".", "host", ",", "Port", ":", "strconv", ".", "Itoa", "(", "target", ".", "port", ")", ",", "AddressesResolved", ":", "target", ".", "available", ",", "URL", ":", "reqURL", ",", "}", "\n\n", "// Get the target IP to build a preresolved dialer with", "targetIP", ":=", "target", ".", "ip", "(", ")", "\n", "if", "targetIP", "==", "nil", "{", "return", "nil", ",", "record", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "target", ".", "host", ")", "\n", "}", "\n", "record", ".", "AddressUsed", "=", "targetIP", "\n\n", "dialer", ":=", "&", "preresolvedDialer", "{", "ip", ":", "targetIP", ",", "port", ":", "target", ".", "port", ",", "hostname", ":", "target", ".", "host", ",", "timeout", ":", "va", ".", "singleDialTimeout", ",", "}", "\n", "return", "dialer", ",", "record", ",", "nil", "\n", "}" ]
// setupHTTPValidation sets up a preresolvedDialer and a validation record for // the given request URL and httpValidationTarget. If the req URL is empty, or // the validation target is nil or has no available IP addresses, an error will // be returned.
[ "setupHTTPValidation", "sets", "up", "a", "preresolvedDialer", "and", "a", "validation", "record", "for", "the", "given", "request", "URL", "and", "httpValidationTarget", ".", "If", "the", "req", "URL", "is", "empty", "or", "the", "validation", "target", "is", "nil", "or", "has", "no", "available", "IP", "addresses", "an", "error", "will", "be", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/http.go#L345-L389
train
letsencrypt/boulder
va/http.go
fetchHTTP
func (va *ValidationAuthorityImpl) fetchHTTP( ctx context.Context, host string, path string) ([]byte, []core.ValidationRecord, *probs.ProblemDetails) { body, records, err := va.processHTTPValidation(ctx, host, path) if err != nil { // Use detailedError to convert the error into a problem return body, records, detailedError(err) } return body, records, nil }
go
func (va *ValidationAuthorityImpl) fetchHTTP( ctx context.Context, host string, path string) ([]byte, []core.ValidationRecord, *probs.ProblemDetails) { body, records, err := va.processHTTPValidation(ctx, host, path) if err != nil { // Use detailedError to convert the error into a problem return body, records, detailedError(err) } return body, records, nil }
[ "func", "(", "va", "*", "ValidationAuthorityImpl", ")", "fetchHTTP", "(", "ctx", "context", ".", "Context", ",", "host", "string", ",", "path", "string", ")", "(", "[", "]", "byte", ",", "[", "]", "core", ".", "ValidationRecord", ",", "*", "probs", ".", "ProblemDetails", ")", "{", "body", ",", "records", ",", "err", ":=", "va", ".", "processHTTPValidation", "(", "ctx", ",", "host", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "// Use detailedError to convert the error into a problem", "return", "body", ",", "records", ",", "detailedError", "(", "err", ")", "\n", "}", "\n", "return", "body", ",", "records", ",", "nil", "\n", "}" ]
// fetchHTTP invokes processHTTPValidation and if an error result is // returned, converts it to a problem. Otherwise the results from // processHTTPValidation are returned.
[ "fetchHTTP", "invokes", "processHTTPValidation", "and", "if", "an", "error", "result", "is", "returned", "converts", "it", "to", "a", "problem", ".", "Otherwise", "the", "results", "from", "processHTTPValidation", "are", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/http.go#L394-L404
train
letsencrypt/boulder
cmd/shell.go
StatsAndLogging
func StatsAndLogging(logConf SyslogConfig, addr string) (metrics.Scope, blog.Logger) { logger := NewLogger(logConf) scope := newScope(addr, logger) return scope, logger }
go
func StatsAndLogging(logConf SyslogConfig, addr string) (metrics.Scope, blog.Logger) { logger := NewLogger(logConf) scope := newScope(addr, logger) return scope, logger }
[ "func", "StatsAndLogging", "(", "logConf", "SyslogConfig", ",", "addr", "string", ")", "(", "metrics", ".", "Scope", ",", "blog", ".", "Logger", ")", "{", "logger", ":=", "NewLogger", "(", "logConf", ")", "\n", "scope", ":=", "newScope", "(", "addr", ",", "logger", ")", "\n", "return", "scope", ",", "logger", "\n", "}" ]
// StatsAndLogging constructs a metrics.Scope and an AuditLogger based on its config // parameters, and return them both. It also spawns off an HTTP server on the // provided port to report the stats and provide pprof profiling handlers. // Crashes if any setup fails. // Also sets the constructed AuditLogger as the default logger, and configures // the cfssl, mysql, and grpc packages to use our logger. // This must be called before any gRPC code is called, because gRPC's SetLogger // doesn't use any locking.
[ "StatsAndLogging", "constructs", "a", "metrics", ".", "Scope", "and", "an", "AuditLogger", "based", "on", "its", "config", "parameters", "and", "return", "them", "both", ".", "It", "also", "spawns", "off", "an", "HTTP", "server", "on", "the", "provided", "port", "to", "report", "the", "stats", "and", "provide", "pprof", "profiling", "handlers", ".", "Crashes", "if", "any", "setup", "fails", ".", "Also", "sets", "the", "constructed", "AuditLogger", "as", "the", "default", "logger", "and", "configures", "the", "cfssl", "mysql", "and", "grpc", "packages", "to", "use", "our", "logger", ".", "This", "must", "be", "called", "before", "any", "gRPC", "code", "is", "called", "because", "gRPC", "s", "SetLogger", "doesn", "t", "use", "any", "locking", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/shell.go#L153-L157
train
letsencrypt/boulder
cmd/shell.go
Fail
func Fail(msg string) { logger := blog.Get() logger.AuditErr(msg) fmt.Fprintf(os.Stderr, msg) os.Exit(1) }
go
func Fail(msg string) { logger := blog.Get() logger.AuditErr(msg) fmt.Fprintf(os.Stderr, msg) os.Exit(1) }
[ "func", "Fail", "(", "msg", "string", ")", "{", "logger", ":=", "blog", ".", "Get", "(", ")", "\n", "logger", ".", "AuditErr", "(", "msg", ")", "\n", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "msg", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// Fail exits and prints an error message to stderr and the logger audit log.
[ "Fail", "exits", "and", "prints", "an", "error", "message", "to", "stderr", "and", "the", "logger", "audit", "log", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/shell.go#L221-L226
train
letsencrypt/boulder
cmd/shell.go
FailOnError
func FailOnError(err error, msg string) { if err != nil { msg := fmt.Sprintf("%s: %s", msg, err) Fail(msg) } }
go
func FailOnError(err error, msg string) { if err != nil { msg := fmt.Sprintf("%s: %s", msg, err) Fail(msg) } }
[ "func", "FailOnError", "(", "err", "error", ",", "msg", "string", ")", "{", "if", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ",", "err", ")", "\n", "Fail", "(", "msg", ")", "\n", "}", "\n", "}" ]
// FailOnError exits and prints an error message, but only if we encountered // a problem and err != nil
[ "FailOnError", "exits", "and", "prints", "an", "error", "message", "but", "only", "if", "we", "encountered", "a", "problem", "and", "err", "!", "=", "nil" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/shell.go#L230-L235
train
letsencrypt/boulder
cmd/shell.go
LoadCert
func LoadCert(path string) (cert []byte, err error) { if path == "" { err = errors.New("Issuer certificate was not provided in config.") return } pemBytes, err := ioutil.ReadFile(path) if err != nil { return } block, _ := pem.Decode(pemBytes) if block == nil || block.Type != "CERTIFICATE" { err = errors.New("Invalid certificate value returned") return } cert = block.Bytes return }
go
func LoadCert(path string) (cert []byte, err error) { if path == "" { err = errors.New("Issuer certificate was not provided in config.") return } pemBytes, err := ioutil.ReadFile(path) if err != nil { return } block, _ := pem.Decode(pemBytes) if block == nil || block.Type != "CERTIFICATE" { err = errors.New("Invalid certificate value returned") return } cert = block.Bytes return }
[ "func", "LoadCert", "(", "path", "string", ")", "(", "cert", "[", "]", "byte", ",", "err", "error", ")", "{", "if", "path", "==", "\"", "\"", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "pemBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "pemBytes", ")", "\n", "if", "block", "==", "nil", "||", "block", ".", "Type", "!=", "\"", "\"", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "cert", "=", "block", ".", "Bytes", "\n", "return", "\n", "}" ]
// LoadCert loads a PEM-formatted certificate from the provided path, returning // it as a byte array, or an error if it couldn't be decoded.
[ "LoadCert", "loads", "a", "PEM", "-", "formatted", "certificate", "from", "the", "provided", "path", "returning", "it", "as", "a", "byte", "array", "or", "an", "error", "if", "it", "couldn", "t", "be", "decoded", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/shell.go#L239-L257
train
letsencrypt/boulder
cmd/shell.go
ReadConfigFile
func ReadConfigFile(filename string, out interface{}) error { configData, err := ioutil.ReadFile(filename) if err != nil { return err } return json.Unmarshal(configData, out) }
go
func ReadConfigFile(filename string, out interface{}) error { configData, err := ioutil.ReadFile(filename) if err != nil { return err } return json.Unmarshal(configData, out) }
[ "func", "ReadConfigFile", "(", "filename", "string", ",", "out", "interface", "{", "}", ")", "error", "{", "configData", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "json", ".", "Unmarshal", "(", "configData", ",", "out", ")", "\n", "}" ]
// ReadConfigFile takes a file path as an argument and attempts to // unmarshal the content of the file into a struct containing a // configuration of a boulder component.
[ "ReadConfigFile", "takes", "a", "file", "path", "as", "an", "argument", "and", "attempts", "to", "unmarshal", "the", "content", "of", "the", "file", "into", "a", "struct", "containing", "a", "configuration", "of", "a", "boulder", "component", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/shell.go#L262-L268
train
letsencrypt/boulder
cmd/shell.go
VersionString
func VersionString() string { name := path.Base(os.Args[0]) return fmt.Sprintf("Versions: %s=(%s %s) Golang=(%s) BuildHost=(%s)", name, core.GetBuildID(), core.GetBuildTime(), runtime.Version(), core.GetBuildHost()) }
go
func VersionString() string { name := path.Base(os.Args[0]) return fmt.Sprintf("Versions: %s=(%s %s) Golang=(%s) BuildHost=(%s)", name, core.GetBuildID(), core.GetBuildTime(), runtime.Version(), core.GetBuildHost()) }
[ "func", "VersionString", "(", ")", "string", "{", "name", ":=", "path", ".", "Base", "(", "os", ".", "Args", "[", "0", "]", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ",", "core", ".", "GetBuildID", "(", ")", ",", "core", ".", "GetBuildTime", "(", ")", ",", "runtime", ".", "Version", "(", ")", ",", "core", ".", "GetBuildHost", "(", ")", ")", "\n", "}" ]
// VersionString produces a friendly Application version string.
[ "VersionString", "produces", "a", "friendly", "Application", "version", "string", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/shell.go#L271-L274
train
letsencrypt/boulder
cmd/shell.go
CatchSignals
func CatchSignals(logger blog.Logger, callback func()) { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM) signal.Notify(sigChan, syscall.SIGINT) signal.Notify(sigChan, syscall.SIGHUP) sig := <-sigChan if logger != nil { logger.Infof("Caught %s", signalToName[sig]) } if callback != nil { callback() } if logger != nil { logger.Info("Exiting") } os.Exit(0) }
go
func CatchSignals(logger blog.Logger, callback func()) { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM) signal.Notify(sigChan, syscall.SIGINT) signal.Notify(sigChan, syscall.SIGHUP) sig := <-sigChan if logger != nil { logger.Infof("Caught %s", signalToName[sig]) } if callback != nil { callback() } if logger != nil { logger.Info("Exiting") } os.Exit(0) }
[ "func", "CatchSignals", "(", "logger", "blog", ".", "Logger", ",", "callback", "func", "(", ")", ")", "{", "sigChan", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "sigChan", ",", "syscall", ".", "SIGTERM", ")", "\n", "signal", ".", "Notify", "(", "sigChan", ",", "syscall", ".", "SIGINT", ")", "\n", "signal", ".", "Notify", "(", "sigChan", ",", "syscall", ".", "SIGHUP", ")", "\n\n", "sig", ":=", "<-", "sigChan", "\n", "if", "logger", "!=", "nil", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "signalToName", "[", "sig", "]", ")", "\n", "}", "\n\n", "if", "callback", "!=", "nil", "{", "callback", "(", ")", "\n", "}", "\n\n", "if", "logger", "!=", "nil", "{", "logger", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "os", ".", "Exit", "(", "0", ")", "\n", "}" ]
// CatchSignals catches SIGTERM, SIGINT, SIGHUP and executes a callback // method before exiting
[ "CatchSignals", "catches", "SIGTERM", "SIGINT", "SIGHUP", "and", "executes", "a", "callback", "method", "before", "exiting" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/shell.go#L284-L303
train
letsencrypt/boulder
cmd/expired-authz-purger/main.go
saveCheckpoint
func saveCheckpoint(checkpointFile, id string) error { tmpDir, err := ioutil.TempDir("", "checkpoint-tmp") if err != nil { return err } defer func() { _ = os.RemoveAll(tmpDir) }() tmp, err := ioutil.TempFile(tmpDir, "checkpoint-atomic") if err != nil { return err } if _, err = tmp.Write([]byte(id)); err != nil { return err } return os.Rename(tmp.Name(), checkpointFile) }
go
func saveCheckpoint(checkpointFile, id string) error { tmpDir, err := ioutil.TempDir("", "checkpoint-tmp") if err != nil { return err } defer func() { _ = os.RemoveAll(tmpDir) }() tmp, err := ioutil.TempFile(tmpDir, "checkpoint-atomic") if err != nil { return err } if _, err = tmp.Write([]byte(id)); err != nil { return err } return os.Rename(tmp.Name(), checkpointFile) }
[ "func", "saveCheckpoint", "(", "checkpointFile", ",", "id", "string", ")", "error", "{", "tmpDir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "_", "=", "os", ".", "RemoveAll", "(", "tmpDir", ")", "}", "(", ")", "\n", "tmp", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "tmpDir", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", "=", "tmp", ".", "Write", "(", "[", "]", "byte", "(", "id", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "os", ".", "Rename", "(", "tmp", ".", "Name", "(", ")", ",", "checkpointFile", ")", "\n", "}" ]
// saveCheckpoint atomically writes the provided ID to the provided file. The // method os.Rename makes use of the renameat syscall to atomically replace // one file with another. It creates a temporary file in a temporary directory // before using os.Rename to replace the old file with the new one.
[ "saveCheckpoint", "atomically", "writes", "the", "provided", "ID", "to", "the", "provided", "file", ".", "The", "method", "os", ".", "Rename", "makes", "use", "of", "the", "renameat", "syscall", "to", "atomically", "replace", "one", "file", "with", "another", ".", "It", "creates", "a", "temporary", "file", "in", "a", "temporary", "directory", "before", "using", "os", ".", "Rename", "to", "replace", "the", "old", "file", "with", "the", "new", "one", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/expired-authz-purger/main.go#L93-L107
train
letsencrypt/boulder
cmd/expired-authz-purger/main.go
getWork
func (p *expiredAuthzPurger) getWork(work chan string, query string, initialID string, purgeBefore time.Time, batchSize int64) (string, int, error) { var idBatch []string _, err := p.db.Select( &idBatch, query, map[string]interface{}{ "id": initialID, "expires": purgeBefore, "limit": batchSize, }, ) if err != nil && err != sql.ErrNoRows { return "", 0, fmt.Errorf("Getting a batch: %s", err) } if len(idBatch) == 0 { return initialID, 0, nil } var count int var lastID string for _, v := range idBatch { work <- v count++ lastID = v } return lastID, count, nil }
go
func (p *expiredAuthzPurger) getWork(work chan string, query string, initialID string, purgeBefore time.Time, batchSize int64) (string, int, error) { var idBatch []string _, err := p.db.Select( &idBatch, query, map[string]interface{}{ "id": initialID, "expires": purgeBefore, "limit": batchSize, }, ) if err != nil && err != sql.ErrNoRows { return "", 0, fmt.Errorf("Getting a batch: %s", err) } if len(idBatch) == 0 { return initialID, 0, nil } var count int var lastID string for _, v := range idBatch { work <- v count++ lastID = v } return lastID, count, nil }
[ "func", "(", "p", "*", "expiredAuthzPurger", ")", "getWork", "(", "work", "chan", "string", ",", "query", "string", ",", "initialID", "string", ",", "purgeBefore", "time", ".", "Time", ",", "batchSize", "int64", ")", "(", "string", ",", "int", ",", "error", ")", "{", "var", "idBatch", "[", "]", "string", "\n", "_", ",", "err", ":=", "p", ".", "db", ".", "Select", "(", "&", "idBatch", ",", "query", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "initialID", ",", "\"", "\"", ":", "purgeBefore", ",", "\"", "\"", ":", "batchSize", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "sql", ".", "ErrNoRows", "{", "return", "\"", "\"", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "idBatch", ")", "==", "0", "{", "return", "initialID", ",", "0", ",", "nil", "\n", "}", "\n", "var", "count", "int", "\n", "var", "lastID", "string", "\n", "for", "_", ",", "v", ":=", "range", "idBatch", "{", "work", "<-", "v", "\n", "count", "++", "\n", "lastID", "=", "v", "\n", "}", "\n", "return", "lastID", ",", "count", ",", "nil", "\n", "}" ]
// getWork selects a set of authorizations that expired before purgeBefore, bounded by batchSize, // that have IDs that are more than initialID from either the pendingAuthorizations or authz tables // and adds them to the work channel. It returns the last ID it selected and the number of IDs it // added to the work channel or an error.
[ "getWork", "selects", "a", "set", "of", "authorizations", "that", "expired", "before", "purgeBefore", "bounded", "by", "batchSize", "that", "have", "IDs", "that", "are", "more", "than", "initialID", "from", "either", "the", "pendingAuthorizations", "or", "authz", "tables", "and", "adds", "them", "to", "the", "work", "channel", ".", "It", "returns", "the", "last", "ID", "it", "selected", "and", "the", "number", "of", "IDs", "it", "added", "to", "the", "work", "channel", "or", "an", "error", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/expired-authz-purger/main.go#L113-L138
train
letsencrypt/boulder
cmd/expired-authz-purger/main.go
deleteAuthorizations
func (p *expiredAuthzPurger) deleteAuthorizations(work chan string, maxDPS int, parallelism int, table string, checkpointFile string) { wg := new(sync.WaitGroup) deleted := int64(0) var ticker *time.Ticker if maxDPS > 0 { ticker = time.NewTicker(time.Duration(float64(time.Second) / float64(maxDPS))) } for i := 0; i < parallelism; i++ { wg.Add(1) go func() { defer wg.Done() for id := range work { if ticker != nil { <-ticker.C } err := deleteAuthorization(p.db, table, id) if err != nil { p.log.AuditErrf("Deleting %s: %s", id, err) } numDeleted := atomic.AddInt64(&deleted, 1) // Only checkpoint every 1000 IDs in order to prevent unnecessary churn // in the checkpoint file if checkpointFile != "" && numDeleted%1000 == 0 { err = saveCheckpoint(checkpointFile, id) if err != nil { p.log.AuditErrf("failed to checkpoint %q table at ID %q: %s", table, id, err) } } } }() } wg.Wait() p.log.Infof("Deleted a total of %d expired authorizations from %s", deleted, table) }
go
func (p *expiredAuthzPurger) deleteAuthorizations(work chan string, maxDPS int, parallelism int, table string, checkpointFile string) { wg := new(sync.WaitGroup) deleted := int64(0) var ticker *time.Ticker if maxDPS > 0 { ticker = time.NewTicker(time.Duration(float64(time.Second) / float64(maxDPS))) } for i := 0; i < parallelism; i++ { wg.Add(1) go func() { defer wg.Done() for id := range work { if ticker != nil { <-ticker.C } err := deleteAuthorization(p.db, table, id) if err != nil { p.log.AuditErrf("Deleting %s: %s", id, err) } numDeleted := atomic.AddInt64(&deleted, 1) // Only checkpoint every 1000 IDs in order to prevent unnecessary churn // in the checkpoint file if checkpointFile != "" && numDeleted%1000 == 0 { err = saveCheckpoint(checkpointFile, id) if err != nil { p.log.AuditErrf("failed to checkpoint %q table at ID %q: %s", table, id, err) } } } }() } wg.Wait() p.log.Infof("Deleted a total of %d expired authorizations from %s", deleted, table) }
[ "func", "(", "p", "*", "expiredAuthzPurger", ")", "deleteAuthorizations", "(", "work", "chan", "string", ",", "maxDPS", "int", ",", "parallelism", "int", ",", "table", "string", ",", "checkpointFile", "string", ")", "{", "wg", ":=", "new", "(", "sync", ".", "WaitGroup", ")", "\n", "deleted", ":=", "int64", "(", "0", ")", "\n", "var", "ticker", "*", "time", ".", "Ticker", "\n", "if", "maxDPS", ">", "0", "{", "ticker", "=", "time", ".", "NewTicker", "(", "time", ".", "Duration", "(", "float64", "(", "time", ".", "Second", ")", "/", "float64", "(", "maxDPS", ")", ")", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "parallelism", ";", "i", "++", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "for", "id", ":=", "range", "work", "{", "if", "ticker", "!=", "nil", "{", "<-", "ticker", ".", "C", "\n", "}", "\n", "err", ":=", "deleteAuthorization", "(", "p", ".", "db", ",", "table", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "id", ",", "err", ")", "\n", "}", "\n", "numDeleted", ":=", "atomic", ".", "AddInt64", "(", "&", "deleted", ",", "1", ")", "\n", "// Only checkpoint every 1000 IDs in order to prevent unnecessary churn", "// in the checkpoint file", "if", "checkpointFile", "!=", "\"", "\"", "&&", "numDeleted", "%", "1000", "==", "0", "{", "err", "=", "saveCheckpoint", "(", "checkpointFile", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "table", ",", "id", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n\n", "wg", ".", "Wait", "(", ")", "\n", "p", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "deleted", ",", "table", ")", "\n", "}" ]
// deleteAuthorizations reads from the work channel and deletes each authorization // from either the pendingAuthorization or authz tables. If maxDPS is more than 0 // it will throttle the number of DELETE statements it generates to the passed rate.
[ "deleteAuthorizations", "reads", "from", "the", "work", "channel", "and", "deletes", "each", "authorization", "from", "either", "the", "pendingAuthorization", "or", "authz", "tables", ".", "If", "maxDPS", "is", "more", "than", "0", "it", "will", "throttle", "the", "number", "of", "DELETE", "statements", "it", "generates", "to", "the", "passed", "rate", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/expired-authz-purger/main.go#L143-L177
train
letsencrypt/boulder
metrics/measured_http/http.go
Write
func (r *responseWriterWithStatus) Write(body []byte) (int, error) { if r.code == 0 { r.code = http.StatusOK } return r.ResponseWriter.Write(body) }
go
func (r *responseWriterWithStatus) Write(body []byte) (int, error) { if r.code == 0 { r.code = http.StatusOK } return r.ResponseWriter.Write(body) }
[ "func", "(", "r", "*", "responseWriterWithStatus", ")", "Write", "(", "body", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "r", ".", "code", "==", "0", "{", "r", ".", "code", "=", "http", ".", "StatusOK", "\n", "}", "\n", "return", "r", ".", "ResponseWriter", ".", "Write", "(", "body", ")", "\n", "}" ]
// Write writes the body and sets the status code to 200 if a status code // has not already been set.
[ "Write", "writes", "the", "body", "and", "sets", "the", "status", "code", "to", "200", "if", "a", "status", "code", "has", "not", "already", "been", "set", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/measured_http/http.go#L27-L32
train
letsencrypt/boulder
canceled/canceled.go
Is
func Is(err error) bool { return err == context.Canceled || grpc.Code(err) == codes.Canceled }
go
func Is(err error) bool { return err == context.Canceled || grpc.Code(err) == codes.Canceled }
[ "func", "Is", "(", "err", "error", ")", "bool", "{", "return", "err", "==", "context", ".", "Canceled", "||", "grpc", ".", "Code", "(", "err", ")", "==", "codes", ".", "Canceled", "\n", "}" ]
// Is returns true if err is non-nil and is either context.Canceled, or has a // grpc code of Canceled. This is useful because cancelations propagate through // gRPC boundaries, and if we choose to treat in-process cancellations a certain // way, we usually want to treat cross-process cancellations the same way.
[ "Is", "returns", "true", "if", "err", "is", "non", "-", "nil", "and", "is", "either", "context", ".", "Canceled", "or", "has", "a", "grpc", "code", "of", "Canceled", ".", "This", "is", "useful", "because", "cancelations", "propagate", "through", "gRPC", "boundaries", "and", "if", "we", "choose", "to", "treat", "in", "-", "process", "cancellations", "a", "certain", "way", "we", "usually", "want", "to", "treat", "cross", "-", "process", "cancellations", "the", "same", "way", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/canceled/canceled.go#L14-L16
train
letsencrypt/boulder
ra/ra.go
NewRegistrationAuthorityImpl
func NewRegistrationAuthorityImpl( clk clock.Clock, logger blog.Logger, stats metrics.Scope, maxContactsPerReg int, keyPolicy goodkey.KeyPolicy, maxNames int, forceCNFromSAN bool, reuseValidAuthz bool, authorizationLifetime time.Duration, pendingAuthorizationLifetime time.Duration, pubc core.Publisher, caaClient caaChecker, orderLifetime time.Duration, ctp *ctpolicy.CTPolicy, purger akamaipb.AkamaiPurgerClient, issuer *x509.Certificate, ) *RegistrationAuthorityImpl { ctpolicyResults := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "ctpolicy_results", Help: "Histogram of latencies of ctpolicy.GetSCTs calls with success/failure/deadlineExceeded labels", Buckets: metrics.InternetFacingBuckets, }, []string{"result"}, ) stats.MustRegister(ctpolicyResults) ra := &RegistrationAuthorityImpl{ stats: stats, clk: clk, log: logger, authorizationLifetime: authorizationLifetime, pendingAuthorizationLifetime: pendingAuthorizationLifetime, rlPolicies: ratelimit.New(), maxContactsPerReg: maxContactsPerReg, keyPolicy: keyPolicy, maxNames: maxNames, forceCNFromSAN: forceCNFromSAN, reuseValidAuthz: reuseValidAuthz, regByIPStats: stats.NewScope("RateLimit", "RegistrationsByIP"), regByIPRangeStats: stats.NewScope("RateLimit", "RegistrationsByIPRange"), pendAuthByRegIDStats: stats.NewScope("RateLimit", "PendingAuthorizationsByRegID"), pendOrdersByRegIDStats: stats.NewScope("RateLimit", "PendingOrdersByRegID"), newOrderByRegIDStats: stats.NewScope("RateLimit", "NewOrdersByRegID"), certsForDomainStats: stats.NewScope("RateLimit", "CertificatesForDomain"), publisher: pubc, caa: caaClient, orderLifetime: orderLifetime, ctpolicy: ctp, ctpolicyResults: ctpolicyResults, purger: purger, issuer: issuer, } return ra }
go
func NewRegistrationAuthorityImpl( clk clock.Clock, logger blog.Logger, stats metrics.Scope, maxContactsPerReg int, keyPolicy goodkey.KeyPolicy, maxNames int, forceCNFromSAN bool, reuseValidAuthz bool, authorizationLifetime time.Duration, pendingAuthorizationLifetime time.Duration, pubc core.Publisher, caaClient caaChecker, orderLifetime time.Duration, ctp *ctpolicy.CTPolicy, purger akamaipb.AkamaiPurgerClient, issuer *x509.Certificate, ) *RegistrationAuthorityImpl { ctpolicyResults := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "ctpolicy_results", Help: "Histogram of latencies of ctpolicy.GetSCTs calls with success/failure/deadlineExceeded labels", Buckets: metrics.InternetFacingBuckets, }, []string{"result"}, ) stats.MustRegister(ctpolicyResults) ra := &RegistrationAuthorityImpl{ stats: stats, clk: clk, log: logger, authorizationLifetime: authorizationLifetime, pendingAuthorizationLifetime: pendingAuthorizationLifetime, rlPolicies: ratelimit.New(), maxContactsPerReg: maxContactsPerReg, keyPolicy: keyPolicy, maxNames: maxNames, forceCNFromSAN: forceCNFromSAN, reuseValidAuthz: reuseValidAuthz, regByIPStats: stats.NewScope("RateLimit", "RegistrationsByIP"), regByIPRangeStats: stats.NewScope("RateLimit", "RegistrationsByIPRange"), pendAuthByRegIDStats: stats.NewScope("RateLimit", "PendingAuthorizationsByRegID"), pendOrdersByRegIDStats: stats.NewScope("RateLimit", "PendingOrdersByRegID"), newOrderByRegIDStats: stats.NewScope("RateLimit", "NewOrdersByRegID"), certsForDomainStats: stats.NewScope("RateLimit", "CertificatesForDomain"), publisher: pubc, caa: caaClient, orderLifetime: orderLifetime, ctpolicy: ctp, ctpolicyResults: ctpolicyResults, purger: purger, issuer: issuer, } return ra }
[ "func", "NewRegistrationAuthorityImpl", "(", "clk", "clock", ".", "Clock", ",", "logger", "blog", ".", "Logger", ",", "stats", "metrics", ".", "Scope", ",", "maxContactsPerReg", "int", ",", "keyPolicy", "goodkey", ".", "KeyPolicy", ",", "maxNames", "int", ",", "forceCNFromSAN", "bool", ",", "reuseValidAuthz", "bool", ",", "authorizationLifetime", "time", ".", "Duration", ",", "pendingAuthorizationLifetime", "time", ".", "Duration", ",", "pubc", "core", ".", "Publisher", ",", "caaClient", "caaChecker", ",", "orderLifetime", "time", ".", "Duration", ",", "ctp", "*", "ctpolicy", ".", "CTPolicy", ",", "purger", "akamaipb", ".", "AkamaiPurgerClient", ",", "issuer", "*", "x509", ".", "Certificate", ",", ")", "*", "RegistrationAuthorityImpl", "{", "ctpolicyResults", ":=", "prometheus", ".", "NewHistogramVec", "(", "prometheus", ".", "HistogramOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "Buckets", ":", "metrics", ".", "InternetFacingBuckets", ",", "}", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", ")", "\n", "stats", ".", "MustRegister", "(", "ctpolicyResults", ")", "\n\n", "ra", ":=", "&", "RegistrationAuthorityImpl", "{", "stats", ":", "stats", ",", "clk", ":", "clk", ",", "log", ":", "logger", ",", "authorizationLifetime", ":", "authorizationLifetime", ",", "pendingAuthorizationLifetime", ":", "pendingAuthorizationLifetime", ",", "rlPolicies", ":", "ratelimit", ".", "New", "(", ")", ",", "maxContactsPerReg", ":", "maxContactsPerReg", ",", "keyPolicy", ":", "keyPolicy", ",", "maxNames", ":", "maxNames", ",", "forceCNFromSAN", ":", "forceCNFromSAN", ",", "reuseValidAuthz", ":", "reuseValidAuthz", ",", "regByIPStats", ":", "stats", ".", "NewScope", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "regByIPRangeStats", ":", "stats", ".", "NewScope", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "pendAuthByRegIDStats", ":", "stats", ".", "NewScope", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "pendOrdersByRegIDStats", ":", "stats", ".", "NewScope", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "newOrderByRegIDStats", ":", "stats", ".", "NewScope", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "certsForDomainStats", ":", "stats", ".", "NewScope", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "publisher", ":", "pubc", ",", "caa", ":", "caaClient", ",", "orderLifetime", ":", "orderLifetime", ",", "ctpolicy", ":", "ctp", ",", "ctpolicyResults", ":", "ctpolicyResults", ",", "purger", ":", "purger", ",", "issuer", ":", "issuer", ",", "}", "\n", "return", "ra", "\n", "}" ]
// NewRegistrationAuthorityImpl constructs a new RA object.
[ "NewRegistrationAuthorityImpl", "constructs", "a", "new", "RA", "object", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L92-L147
train
letsencrypt/boulder
ra/ra.go
checkRegistrationIPLimit
func (ra *RegistrationAuthorityImpl) checkRegistrationIPLimit( ctx context.Context, limit ratelimit.RateLimitPolicy, ip net.IP, counter registrationCounter) error { if !limit.Enabled() { return nil } now := ra.clk.Now() windowBegin := limit.WindowBegin(now) count, err := counter(ctx, ip, windowBegin, now) if err != nil { return err } if count >= limit.GetThreshold(ip.String(), noRegistrationID) { return berrors.RateLimitError("too many registrations for this IP") } return nil }
go
func (ra *RegistrationAuthorityImpl) checkRegistrationIPLimit( ctx context.Context, limit ratelimit.RateLimitPolicy, ip net.IP, counter registrationCounter) error { if !limit.Enabled() { return nil } now := ra.clk.Now() windowBegin := limit.WindowBegin(now) count, err := counter(ctx, ip, windowBegin, now) if err != nil { return err } if count >= limit.GetThreshold(ip.String(), noRegistrationID) { return berrors.RateLimitError("too many registrations for this IP") } return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "checkRegistrationIPLimit", "(", "ctx", "context", ".", "Context", ",", "limit", "ratelimit", ".", "RateLimitPolicy", ",", "ip", "net", ".", "IP", ",", "counter", "registrationCounter", ")", "error", "{", "if", "!", "limit", ".", "Enabled", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "now", ":=", "ra", ".", "clk", ".", "Now", "(", ")", "\n", "windowBegin", ":=", "limit", ".", "WindowBegin", "(", "now", ")", "\n", "count", ",", "err", ":=", "counter", "(", "ctx", ",", "ip", ",", "windowBegin", ",", "now", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "count", ">=", "limit", ".", "GetThreshold", "(", "ip", ".", "String", "(", ")", ",", "noRegistrationID", ")", "{", "return", "berrors", ".", "RateLimitError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkRegistrationIPLimit checks a specific registraton limit by using the // provided registrationCounter function to determine if the limit has been // exceeded for a given IP or IP range
[ "checkRegistrationIPLimit", "checks", "a", "specific", "registraton", "limit", "by", "using", "the", "provided", "registrationCounter", "function", "to", "determine", "if", "the", "limit", "has", "been", "exceeded", "for", "a", "given", "IP", "or", "IP", "range" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L216-L238
train
letsencrypt/boulder
ra/ra.go
checkRegistrationLimits
func (ra *RegistrationAuthorityImpl) checkRegistrationLimits(ctx context.Context, ip net.IP) error { // Check the registrations per IP limit using the CountRegistrationsByIP SA // function that matches IP addresses exactly exactRegLimit := ra.rlPolicies.RegistrationsPerIP() err := ra.checkRegistrationIPLimit(ctx, exactRegLimit, ip, ra.SA.CountRegistrationsByIP) if err != nil { ra.regByIPStats.Inc("Exceeded", 1) ra.log.Infof("Rate limit exceeded, RegistrationsByIP, IP: %s", ip) return err } ra.regByIPStats.Inc("Pass", 1) // We only apply the fuzzy reg limit to IPv6 addresses. // Per https://golang.org/pkg/net/#IP.To4 "If ip is not an IPv4 address, To4 // returns nil" if ip.To4() != nil { return nil } // Check the registrations per IP range limit using the // CountRegistrationsByIPRange SA function that fuzzy-matches IPv6 addresses // within a larger address range fuzzyRegLimit := ra.rlPolicies.RegistrationsPerIPRange() err = ra.checkRegistrationIPLimit(ctx, fuzzyRegLimit, ip, ra.SA.CountRegistrationsByIPRange) if err != nil { ra.regByIPRangeStats.Inc("Exceeded", 1) ra.log.Infof("Rate limit exceeded, RegistrationsByIPRange, IP: %s", ip) // For the fuzzyRegLimit we use a new error message that specifically // mentions that the limit being exceeded is applied to a *range* of IPs return berrors.RateLimitError("too many registrations for this IP range") } ra.regByIPRangeStats.Inc("Pass", 1) return nil }
go
func (ra *RegistrationAuthorityImpl) checkRegistrationLimits(ctx context.Context, ip net.IP) error { // Check the registrations per IP limit using the CountRegistrationsByIP SA // function that matches IP addresses exactly exactRegLimit := ra.rlPolicies.RegistrationsPerIP() err := ra.checkRegistrationIPLimit(ctx, exactRegLimit, ip, ra.SA.CountRegistrationsByIP) if err != nil { ra.regByIPStats.Inc("Exceeded", 1) ra.log.Infof("Rate limit exceeded, RegistrationsByIP, IP: %s", ip) return err } ra.regByIPStats.Inc("Pass", 1) // We only apply the fuzzy reg limit to IPv6 addresses. // Per https://golang.org/pkg/net/#IP.To4 "If ip is not an IPv4 address, To4 // returns nil" if ip.To4() != nil { return nil } // Check the registrations per IP range limit using the // CountRegistrationsByIPRange SA function that fuzzy-matches IPv6 addresses // within a larger address range fuzzyRegLimit := ra.rlPolicies.RegistrationsPerIPRange() err = ra.checkRegistrationIPLimit(ctx, fuzzyRegLimit, ip, ra.SA.CountRegistrationsByIPRange) if err != nil { ra.regByIPRangeStats.Inc("Exceeded", 1) ra.log.Infof("Rate limit exceeded, RegistrationsByIPRange, IP: %s", ip) // For the fuzzyRegLimit we use a new error message that specifically // mentions that the limit being exceeded is applied to a *range* of IPs return berrors.RateLimitError("too many registrations for this IP range") } ra.regByIPRangeStats.Inc("Pass", 1) return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "checkRegistrationLimits", "(", "ctx", "context", ".", "Context", ",", "ip", "net", ".", "IP", ")", "error", "{", "// Check the registrations per IP limit using the CountRegistrationsByIP SA", "// function that matches IP addresses exactly", "exactRegLimit", ":=", "ra", ".", "rlPolicies", ".", "RegistrationsPerIP", "(", ")", "\n", "err", ":=", "ra", ".", "checkRegistrationIPLimit", "(", "ctx", ",", "exactRegLimit", ",", "ip", ",", "ra", ".", "SA", ".", "CountRegistrationsByIP", ")", "\n", "if", "err", "!=", "nil", "{", "ra", ".", "regByIPStats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "ra", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "ip", ")", "\n", "return", "err", "\n", "}", "\n", "ra", ".", "regByIPStats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n\n", "// We only apply the fuzzy reg limit to IPv6 addresses.", "// Per https://golang.org/pkg/net/#IP.To4 \"If ip is not an IPv4 address, To4", "// returns nil\"", "if", "ip", ".", "To4", "(", ")", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// Check the registrations per IP range limit using the", "// CountRegistrationsByIPRange SA function that fuzzy-matches IPv6 addresses", "// within a larger address range", "fuzzyRegLimit", ":=", "ra", ".", "rlPolicies", ".", "RegistrationsPerIPRange", "(", ")", "\n", "err", "=", "ra", ".", "checkRegistrationIPLimit", "(", "ctx", ",", "fuzzyRegLimit", ",", "ip", ",", "ra", ".", "SA", ".", "CountRegistrationsByIPRange", ")", "\n", "if", "err", "!=", "nil", "{", "ra", ".", "regByIPRangeStats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "ra", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "ip", ")", "\n", "// For the fuzzyRegLimit we use a new error message that specifically", "// mentions that the limit being exceeded is applied to a *range* of IPs", "return", "berrors", ".", "RateLimitError", "(", "\"", "\"", ")", "\n", "}", "\n", "ra", ".", "regByIPRangeStats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n\n", "return", "nil", "\n", "}" ]
// checkRegistrationLimits enforces the RegistrationsPerIP and // RegistrationsPerIPRange limits
[ "checkRegistrationLimits", "enforces", "the", "RegistrationsPerIP", "and", "RegistrationsPerIPRange", "limits" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L242-L276
train
letsencrypt/boulder
ra/ra.go
NewRegistration
func (ra *RegistrationAuthorityImpl) NewRegistration(ctx context.Context, init core.Registration) (core.Registration, error) { if err := ra.keyPolicy.GoodKey(init.Key.Key); err != nil { return core.Registration{}, berrors.MalformedError("invalid public key: %s", err.Error()) } if err := ra.checkRegistrationLimits(ctx, init.InitialIP); err != nil { return core.Registration{}, err } reg := core.Registration{ Key: init.Key, Status: core.StatusValid, } _ = mergeUpdate(&reg, init) // This field isn't updatable by the end user, so it isn't copied by // MergeUpdate. But we need to fill it in for new registrations. reg.InitialIP = init.InitialIP if err := ra.validateContacts(ctx, reg.Contact); err != nil { return core.Registration{}, err } // Store the authorization object, then return it reg, err := ra.SA.NewRegistration(ctx, reg) if err != nil { return core.Registration{}, err } ra.stats.Inc("NewRegistrations", 1) return reg, nil }
go
func (ra *RegistrationAuthorityImpl) NewRegistration(ctx context.Context, init core.Registration) (core.Registration, error) { if err := ra.keyPolicy.GoodKey(init.Key.Key); err != nil { return core.Registration{}, berrors.MalformedError("invalid public key: %s", err.Error()) } if err := ra.checkRegistrationLimits(ctx, init.InitialIP); err != nil { return core.Registration{}, err } reg := core.Registration{ Key: init.Key, Status: core.StatusValid, } _ = mergeUpdate(&reg, init) // This field isn't updatable by the end user, so it isn't copied by // MergeUpdate. But we need to fill it in for new registrations. reg.InitialIP = init.InitialIP if err := ra.validateContacts(ctx, reg.Contact); err != nil { return core.Registration{}, err } // Store the authorization object, then return it reg, err := ra.SA.NewRegistration(ctx, reg) if err != nil { return core.Registration{}, err } ra.stats.Inc("NewRegistrations", 1) return reg, nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "NewRegistration", "(", "ctx", "context", ".", "Context", ",", "init", "core", ".", "Registration", ")", "(", "core", ".", "Registration", ",", "error", ")", "{", "if", "err", ":=", "ra", ".", "keyPolicy", ".", "GoodKey", "(", "init", ".", "Key", ".", "Key", ")", ";", "err", "!=", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "berrors", ".", "MalformedError", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "err", ":=", "ra", ".", "checkRegistrationLimits", "(", "ctx", ",", "init", ".", "InitialIP", ")", ";", "err", "!=", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "err", "\n", "}", "\n\n", "reg", ":=", "core", ".", "Registration", "{", "Key", ":", "init", ".", "Key", ",", "Status", ":", "core", ".", "StatusValid", ",", "}", "\n", "_", "=", "mergeUpdate", "(", "&", "reg", ",", "init", ")", "\n\n", "// This field isn't updatable by the end user, so it isn't copied by", "// MergeUpdate. But we need to fill it in for new registrations.", "reg", ".", "InitialIP", "=", "init", ".", "InitialIP", "\n\n", "if", "err", ":=", "ra", ".", "validateContacts", "(", "ctx", ",", "reg", ".", "Contact", ")", ";", "err", "!=", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "err", "\n", "}", "\n\n", "// Store the authorization object, then return it", "reg", ",", "err", ":=", "ra", ".", "SA", ".", "NewRegistration", "(", "ctx", ",", "reg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "err", "\n", "}", "\n\n", "ra", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "reg", ",", "nil", "\n", "}" ]
// NewRegistration constructs a new Registration from a request.
[ "NewRegistration", "constructs", "a", "new", "Registration", "from", "a", "request", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L279-L309
train
letsencrypt/boulder
ra/ra.go
validateEmail
func validateEmail(address string) error { email, err := mail.ParseAddress(address) if err != nil { return unparseableEmailError } splitEmail := strings.SplitN(email.Address, "@", -1) domain := strings.ToLower(splitEmail[len(splitEmail)-1]) if forbiddenMailDomains[domain] { return berrors.InvalidEmailError( "invalid contact domain. Contact emails @%s are forbidden", domain) } if _, err := iana.ExtractSuffix(domain); err != nil { return berrors.InvalidEmailError("email domain name does not end in a IANA suffix") } return nil }
go
func validateEmail(address string) error { email, err := mail.ParseAddress(address) if err != nil { return unparseableEmailError } splitEmail := strings.SplitN(email.Address, "@", -1) domain := strings.ToLower(splitEmail[len(splitEmail)-1]) if forbiddenMailDomains[domain] { return berrors.InvalidEmailError( "invalid contact domain. Contact emails @%s are forbidden", domain) } if _, err := iana.ExtractSuffix(domain); err != nil { return berrors.InvalidEmailError("email domain name does not end in a IANA suffix") } return nil }
[ "func", "validateEmail", "(", "address", "string", ")", "error", "{", "email", ",", "err", ":=", "mail", ".", "ParseAddress", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "unparseableEmailError", "\n", "}", "\n", "splitEmail", ":=", "strings", ".", "SplitN", "(", "email", ".", "Address", ",", "\"", "\"", ",", "-", "1", ")", "\n", "domain", ":=", "strings", ".", "ToLower", "(", "splitEmail", "[", "len", "(", "splitEmail", ")", "-", "1", "]", ")", "\n", "if", "forbiddenMailDomains", "[", "domain", "]", "{", "return", "berrors", ".", "InvalidEmailError", "(", "\"", "\"", ",", "domain", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "iana", ".", "ExtractSuffix", "(", "domain", ")", ";", "err", "!=", "nil", "{", "return", "berrors", ".", "InvalidEmailError", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateEmail returns an error if the given address is not parseable as an // email address or if the domain portion of the email address is a member of // the forbiddenMailDomains map.
[ "validateEmail", "returns", "an", "error", "if", "the", "given", "address", "is", "not", "parseable", "as", "an", "email", "address", "or", "if", "the", "domain", "portion", "of", "the", "email", "address", "is", "a", "member", "of", "the", "forbiddenMailDomains", "map", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L378-L394
train
letsencrypt/boulder
ra/ra.go
checkNewOrdersPerAccountLimit
func (ra *RegistrationAuthorityImpl) checkNewOrdersPerAccountLimit(ctx context.Context, acctID int64) error { limit := ra.rlPolicies.NewOrdersPerAccount() if !limit.Enabled() { return nil } latest := ra.clk.Now() earliest := latest.Add(-limit.Window.Duration) count, err := ra.SA.CountOrders(ctx, acctID, earliest, latest) if err != nil { return err } // There is no meaningful override key to use for this rate limit noKey := "" if count >= limit.GetThreshold(noKey, acctID) { ra.newOrderByRegIDStats.Inc("Exceeded", 1) return berrors.RateLimitError("too many new orders recently") } ra.newOrderByRegIDStats.Inc("Pass", 1) return nil }
go
func (ra *RegistrationAuthorityImpl) checkNewOrdersPerAccountLimit(ctx context.Context, acctID int64) error { limit := ra.rlPolicies.NewOrdersPerAccount() if !limit.Enabled() { return nil } latest := ra.clk.Now() earliest := latest.Add(-limit.Window.Duration) count, err := ra.SA.CountOrders(ctx, acctID, earliest, latest) if err != nil { return err } // There is no meaningful override key to use for this rate limit noKey := "" if count >= limit.GetThreshold(noKey, acctID) { ra.newOrderByRegIDStats.Inc("Exceeded", 1) return berrors.RateLimitError("too many new orders recently") } ra.newOrderByRegIDStats.Inc("Pass", 1) return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "checkNewOrdersPerAccountLimit", "(", "ctx", "context", ".", "Context", ",", "acctID", "int64", ")", "error", "{", "limit", ":=", "ra", ".", "rlPolicies", ".", "NewOrdersPerAccount", "(", ")", "\n", "if", "!", "limit", ".", "Enabled", "(", ")", "{", "return", "nil", "\n", "}", "\n", "latest", ":=", "ra", ".", "clk", ".", "Now", "(", ")", "\n", "earliest", ":=", "latest", ".", "Add", "(", "-", "limit", ".", "Window", ".", "Duration", ")", "\n", "count", ",", "err", ":=", "ra", ".", "SA", ".", "CountOrders", "(", "ctx", ",", "acctID", ",", "earliest", ",", "latest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// There is no meaningful override key to use for this rate limit", "noKey", ":=", "\"", "\"", "\n", "if", "count", ">=", "limit", ".", "GetThreshold", "(", "noKey", ",", "acctID", ")", "{", "ra", ".", "newOrderByRegIDStats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "berrors", ".", "RateLimitError", "(", "\"", "\"", ")", "\n", "}", "\n", "ra", ".", "newOrderByRegIDStats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "nil", "\n", "}" ]
// checkNewOrdersPerAccountLimit enforces the rlPolicies `NewOrdersPerAccount` // rate limit. This rate limit ensures a client can not create more than the // specified threshold of new orders within the specified time window.
[ "checkNewOrdersPerAccountLimit", "enforces", "the", "rlPolicies", "NewOrdersPerAccount", "rate", "limit", ".", "This", "rate", "limit", "ensures", "a", "client", "can", "not", "create", "more", "than", "the", "specified", "threshold", "of", "new", "orders", "within", "the", "specified", "time", "window", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L456-L475
train
letsencrypt/boulder
ra/ra.go
checkOrderAuthorizations
func (ra *RegistrationAuthorityImpl) checkOrderAuthorizations( ctx context.Context, names []string, acctID accountID, orderID orderID) (map[string]*core.Authorization, error) { acctIDInt := int64(acctID) orderIDInt := int64(orderID) // Get all of the valid authorizations for this account/order authzs, err := ra.SA.GetValidOrderAuthorizations( ctx, &sapb.GetValidOrderAuthorizationsRequest{ Id: &orderIDInt, AcctID: &acctIDInt, }) if err != nil { return nil, berrors.InternalServerError("error in GetValidOrderAuthorizations: %s", err) } // Ensure the names from the CSR are free of duplicates & lowercased. names = core.UniqueLowerNames(names) // Check the authorizations to ensure validity for the names required. if err = ra.checkAuthorizationsCAA(ctx, names, authzs, acctIDInt, ra.clk.Now()); err != nil { return nil, err } return authzs, nil }
go
func (ra *RegistrationAuthorityImpl) checkOrderAuthorizations( ctx context.Context, names []string, acctID accountID, orderID orderID) (map[string]*core.Authorization, error) { acctIDInt := int64(acctID) orderIDInt := int64(orderID) // Get all of the valid authorizations for this account/order authzs, err := ra.SA.GetValidOrderAuthorizations( ctx, &sapb.GetValidOrderAuthorizationsRequest{ Id: &orderIDInt, AcctID: &acctIDInt, }) if err != nil { return nil, berrors.InternalServerError("error in GetValidOrderAuthorizations: %s", err) } // Ensure the names from the CSR are free of duplicates & lowercased. names = core.UniqueLowerNames(names) // Check the authorizations to ensure validity for the names required. if err = ra.checkAuthorizationsCAA(ctx, names, authzs, acctIDInt, ra.clk.Now()); err != nil { return nil, err } return authzs, nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "checkOrderAuthorizations", "(", "ctx", "context", ".", "Context", ",", "names", "[", "]", "string", ",", "acctID", "accountID", ",", "orderID", "orderID", ")", "(", "map", "[", "string", "]", "*", "core", ".", "Authorization", ",", "error", ")", "{", "acctIDInt", ":=", "int64", "(", "acctID", ")", "\n", "orderIDInt", ":=", "int64", "(", "orderID", ")", "\n", "// Get all of the valid authorizations for this account/order", "authzs", ",", "err", ":=", "ra", ".", "SA", ".", "GetValidOrderAuthorizations", "(", "ctx", ",", "&", "sapb", ".", "GetValidOrderAuthorizationsRequest", "{", "Id", ":", "&", "orderIDInt", ",", "AcctID", ":", "&", "acctIDInt", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// Ensure the names from the CSR are free of duplicates & lowercased.", "names", "=", "core", ".", "UniqueLowerNames", "(", "names", ")", "\n", "// Check the authorizations to ensure validity for the names required.", "if", "err", "=", "ra", ".", "checkAuthorizationsCAA", "(", "ctx", ",", "names", ",", "authzs", ",", "acctIDInt", ",", "ra", ".", "clk", ".", "Now", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "authzs", ",", "nil", "\n", "}" ]
// checkOrderAuthorizations verifies that a provided set of names associated // with a specific order and account has all of the required valid, unexpired // authorizations to proceed with issuance. It is the ACME v2 equivalent of // `checkAuthorizations`. It returns the authorizations that satisfied the set // of names or it returns an error. If it returns an error, it will be of type // BoulderError.
[ "checkOrderAuthorizations", "verifies", "that", "a", "provided", "set", "of", "names", "associated", "with", "a", "specific", "order", "and", "account", "has", "all", "of", "the", "required", "valid", "unexpired", "authorizations", "to", "proceed", "with", "issuance", ".", "It", "is", "the", "ACME", "v2", "equivalent", "of", "checkAuthorizations", ".", "It", "returns", "the", "authorizations", "that", "satisfied", "the", "set", "of", "names", "or", "it", "returns", "an", "error", ".", "If", "it", "returns", "an", "error", "it", "will", "be", "of", "type", "BoulderError", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L657-L682
train
letsencrypt/boulder
ra/ra.go
checkAuthorizations
func (ra *RegistrationAuthorityImpl) checkAuthorizations(ctx context.Context, names []string, regID int64) (map[string]*core.Authorization, error) { now := ra.clk.Now() for i := range names { names[i] = strings.ToLower(names[i]) } auths, err := ra.SA.GetValidAuthorizations(ctx, regID, names, now) if err != nil { return nil, berrors.InternalServerError("error in GetValidAuthorizations: %s", err) } if err = ra.checkAuthorizationsCAA(ctx, names, auths, regID, now); err != nil { return nil, err } return auths, nil }
go
func (ra *RegistrationAuthorityImpl) checkAuthorizations(ctx context.Context, names []string, regID int64) (map[string]*core.Authorization, error) { now := ra.clk.Now() for i := range names { names[i] = strings.ToLower(names[i]) } auths, err := ra.SA.GetValidAuthorizations(ctx, regID, names, now) if err != nil { return nil, berrors.InternalServerError("error in GetValidAuthorizations: %s", err) } if err = ra.checkAuthorizationsCAA(ctx, names, auths, regID, now); err != nil { return nil, err } return auths, nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "checkAuthorizations", "(", "ctx", "context", ".", "Context", ",", "names", "[", "]", "string", ",", "regID", "int64", ")", "(", "map", "[", "string", "]", "*", "core", ".", "Authorization", ",", "error", ")", "{", "now", ":=", "ra", ".", "clk", ".", "Now", "(", ")", "\n", "for", "i", ":=", "range", "names", "{", "names", "[", "i", "]", "=", "strings", ".", "ToLower", "(", "names", "[", "i", "]", ")", "\n", "}", "\n", "auths", ",", "err", ":=", "ra", ".", "SA", ".", "GetValidAuthorizations", "(", "ctx", ",", "regID", ",", "names", ",", "now", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", "=", "ra", ".", "checkAuthorizationsCAA", "(", "ctx", ",", "names", ",", "auths", ",", "regID", ",", "now", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "auths", ",", "nil", "\n", "}" ]
// checkAuthorizations checks that each requested name has a valid authorization // that won't expire before the certificate expires. It returns the // authorizations that satisifed the set of names or it returns an error. // If it returns an error, it will be of type BoulderError.
[ "checkAuthorizations", "checks", "that", "each", "requested", "name", "has", "a", "valid", "authorization", "that", "won", "t", "expire", "before", "the", "certificate", "expires", ".", "It", "returns", "the", "authorizations", "that", "satisifed", "the", "set", "of", "names", "or", "it", "returns", "an", "error", ".", "If", "it", "returns", "an", "error", "it", "will", "be", "of", "type", "BoulderError", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L688-L703
train
letsencrypt/boulder
ra/ra.go
checkAuthorizationsCAA
func (ra *RegistrationAuthorityImpl) checkAuthorizationsCAA( ctx context.Context, names []string, authzs map[string]*core.Authorization, regID int64, now time.Time) error { // badNames contains the names that were unauthorized var badNames []string // recheckAuthzs is a list of authorizations that must have their CAA records rechecked var recheckAuthzs []*core.Authorization // Per Baseline Requirements, CAA must be checked within 8 hours of issuance. // CAA is checked when an authorization is validated, so as long as that was // less than 8 hours ago, we're fine. If it was more than 8 hours ago // we have to recheck. Since we don't record the validation time for // authorizations, we instead look at the expiration time and subtract out the // expected authorization lifetime. Note: If we adjust the authorization // lifetime in the future we will need to tweak this correspondingly so it // works correctly during the switchover. caaRecheckTime := now.Add(ra.authorizationLifetime).Add(-8 * time.Hour) for _, name := range names { authz := authzs[name] if authz == nil { badNames = append(badNames, name) } else if authz.Expires == nil { return berrors.InternalServerError("found an authorization with a nil Expires field: id %s", authz.ID) } else if authz.Expires.Before(now) { badNames = append(badNames, name) } else if authz.Expires.Before(caaRecheckTime) { // Ensure that CAA is rechecked for this name recheckAuthzs = append(recheckAuthzs, authz) } } if len(recheckAuthzs) > 0 { if err := ra.recheckCAA(ctx, recheckAuthzs); err != nil { return err } } if len(badNames) > 0 { return berrors.UnauthorizedError( "authorizations for these names not found or expired: %s", strings.Join(badNames, ", "), ) } return nil }
go
func (ra *RegistrationAuthorityImpl) checkAuthorizationsCAA( ctx context.Context, names []string, authzs map[string]*core.Authorization, regID int64, now time.Time) error { // badNames contains the names that were unauthorized var badNames []string // recheckAuthzs is a list of authorizations that must have their CAA records rechecked var recheckAuthzs []*core.Authorization // Per Baseline Requirements, CAA must be checked within 8 hours of issuance. // CAA is checked when an authorization is validated, so as long as that was // less than 8 hours ago, we're fine. If it was more than 8 hours ago // we have to recheck. Since we don't record the validation time for // authorizations, we instead look at the expiration time and subtract out the // expected authorization lifetime. Note: If we adjust the authorization // lifetime in the future we will need to tweak this correspondingly so it // works correctly during the switchover. caaRecheckTime := now.Add(ra.authorizationLifetime).Add(-8 * time.Hour) for _, name := range names { authz := authzs[name] if authz == nil { badNames = append(badNames, name) } else if authz.Expires == nil { return berrors.InternalServerError("found an authorization with a nil Expires field: id %s", authz.ID) } else if authz.Expires.Before(now) { badNames = append(badNames, name) } else if authz.Expires.Before(caaRecheckTime) { // Ensure that CAA is rechecked for this name recheckAuthzs = append(recheckAuthzs, authz) } } if len(recheckAuthzs) > 0 { if err := ra.recheckCAA(ctx, recheckAuthzs); err != nil { return err } } if len(badNames) > 0 { return berrors.UnauthorizedError( "authorizations for these names not found or expired: %s", strings.Join(badNames, ", "), ) } return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "checkAuthorizationsCAA", "(", "ctx", "context", ".", "Context", ",", "names", "[", "]", "string", ",", "authzs", "map", "[", "string", "]", "*", "core", ".", "Authorization", ",", "regID", "int64", ",", "now", "time", ".", "Time", ")", "error", "{", "// badNames contains the names that were unauthorized", "var", "badNames", "[", "]", "string", "\n", "// recheckAuthzs is a list of authorizations that must have their CAA records rechecked", "var", "recheckAuthzs", "[", "]", "*", "core", ".", "Authorization", "\n", "// Per Baseline Requirements, CAA must be checked within 8 hours of issuance.", "// CAA is checked when an authorization is validated, so as long as that was", "// less than 8 hours ago, we're fine. If it was more than 8 hours ago", "// we have to recheck. Since we don't record the validation time for", "// authorizations, we instead look at the expiration time and subtract out the", "// expected authorization lifetime. Note: If we adjust the authorization", "// lifetime in the future we will need to tweak this correspondingly so it", "// works correctly during the switchover.", "caaRecheckTime", ":=", "now", ".", "Add", "(", "ra", ".", "authorizationLifetime", ")", ".", "Add", "(", "-", "8", "*", "time", ".", "Hour", ")", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "authz", ":=", "authzs", "[", "name", "]", "\n", "if", "authz", "==", "nil", "{", "badNames", "=", "append", "(", "badNames", ",", "name", ")", "\n", "}", "else", "if", "authz", ".", "Expires", "==", "nil", "{", "return", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "authz", ".", "ID", ")", "\n", "}", "else", "if", "authz", ".", "Expires", ".", "Before", "(", "now", ")", "{", "badNames", "=", "append", "(", "badNames", ",", "name", ")", "\n", "}", "else", "if", "authz", ".", "Expires", ".", "Before", "(", "caaRecheckTime", ")", "{", "// Ensure that CAA is rechecked for this name", "recheckAuthzs", "=", "append", "(", "recheckAuthzs", ",", "authz", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "recheckAuthzs", ")", ">", "0", "{", "if", "err", ":=", "ra", ".", "recheckCAA", "(", "ctx", ",", "recheckAuthzs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "badNames", ")", ">", "0", "{", "return", "berrors", ".", "UnauthorizedError", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "badNames", ",", "\"", "\"", ")", ",", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkAuthorizationsCAA implements the common logic of validating a set of // authorizations against a set of names that is used by both // `checkAuthorizations` and `checkOrderAuthorizations`. If required CAA will be // rechecked for authorizations that are too old. // If it returns an error, it will be of type BoulderError.
[ "checkAuthorizationsCAA", "implements", "the", "common", "logic", "of", "validating", "a", "set", "of", "authorizations", "against", "a", "set", "of", "names", "that", "is", "used", "by", "both", "checkAuthorizations", "and", "checkOrderAuthorizations", ".", "If", "required", "CAA", "will", "be", "rechecked", "for", "authorizations", "that", "are", "too", "old", ".", "If", "it", "returns", "an", "error", "it", "will", "be", "of", "type", "BoulderError", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L710-L757
train
letsencrypt/boulder
ra/ra.go
recheckCAA
func (ra *RegistrationAuthorityImpl) recheckCAA(ctx context.Context, authzs []*core.Authorization) error { ra.stats.Inc("recheck_caa", 1) ra.stats.Inc("recheck_caa_authzs", int64(len(authzs))) ch := make(chan error, len(authzs)) for _, authz := range authzs { go func(authz *core.Authorization) { name := authz.Identifier.Value // If an authorization has multiple valid challenges, // the type of the first valid challenge is used for // the purposes of CAA rechecking. var method string for _, challenge := range authz.Challenges { if challenge.Status == core.StatusValid { method = challenge.Type break } } if method == "" { ch <- berrors.InternalServerError( "Internal error determining validation method for authorization ID %v (%v)", authz.ID, name, ) return } resp, err := ra.caa.IsCAAValid(ctx, &vaPB.IsCAAValidRequest{ Domain: &name, ValidationMethod: &method, AccountURIID: &authz.RegistrationID, }) if err != nil { ra.log.AuditErrf("Rechecking CAA: %s", err) err = berrors.InternalServerError( "Internal error rechecking CAA for authorization ID %v (%v)", authz.ID, name, ) } else if resp.Problem != nil { err = berrors.CAAError(*resp.Problem.Detail) } ch <- err }(authz) } var caaFailures []string for _ = range authzs { if err := <-ch; berrors.Is(err, berrors.CAA) { caaFailures = append(caaFailures, err.Error()) } else if err != nil { return err } } if len(caaFailures) > 0 { return berrors.CAAError("Rechecking CAA: %v", strings.Join(caaFailures, ", ")) } return nil }
go
func (ra *RegistrationAuthorityImpl) recheckCAA(ctx context.Context, authzs []*core.Authorization) error { ra.stats.Inc("recheck_caa", 1) ra.stats.Inc("recheck_caa_authzs", int64(len(authzs))) ch := make(chan error, len(authzs)) for _, authz := range authzs { go func(authz *core.Authorization) { name := authz.Identifier.Value // If an authorization has multiple valid challenges, // the type of the first valid challenge is used for // the purposes of CAA rechecking. var method string for _, challenge := range authz.Challenges { if challenge.Status == core.StatusValid { method = challenge.Type break } } if method == "" { ch <- berrors.InternalServerError( "Internal error determining validation method for authorization ID %v (%v)", authz.ID, name, ) return } resp, err := ra.caa.IsCAAValid(ctx, &vaPB.IsCAAValidRequest{ Domain: &name, ValidationMethod: &method, AccountURIID: &authz.RegistrationID, }) if err != nil { ra.log.AuditErrf("Rechecking CAA: %s", err) err = berrors.InternalServerError( "Internal error rechecking CAA for authorization ID %v (%v)", authz.ID, name, ) } else if resp.Problem != nil { err = berrors.CAAError(*resp.Problem.Detail) } ch <- err }(authz) } var caaFailures []string for _ = range authzs { if err := <-ch; berrors.Is(err, berrors.CAA) { caaFailures = append(caaFailures, err.Error()) } else if err != nil { return err } } if len(caaFailures) > 0 { return berrors.CAAError("Rechecking CAA: %v", strings.Join(caaFailures, ", ")) } return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "recheckCAA", "(", "ctx", "context", ".", "Context", ",", "authzs", "[", "]", "*", "core", ".", "Authorization", ")", "error", "{", "ra", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "ra", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "int64", "(", "len", "(", "authzs", ")", ")", ")", "\n", "ch", ":=", "make", "(", "chan", "error", ",", "len", "(", "authzs", ")", ")", "\n", "for", "_", ",", "authz", ":=", "range", "authzs", "{", "go", "func", "(", "authz", "*", "core", ".", "Authorization", ")", "{", "name", ":=", "authz", ".", "Identifier", ".", "Value", "\n\n", "// If an authorization has multiple valid challenges,", "// the type of the first valid challenge is used for", "// the purposes of CAA rechecking.", "var", "method", "string", "\n", "for", "_", ",", "challenge", ":=", "range", "authz", ".", "Challenges", "{", "if", "challenge", ".", "Status", "==", "core", ".", "StatusValid", "{", "method", "=", "challenge", ".", "Type", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "method", "==", "\"", "\"", "{", "ch", "<-", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "authz", ".", "ID", ",", "name", ",", ")", "\n", "return", "\n", "}", "\n\n", "resp", ",", "err", ":=", "ra", ".", "caa", ".", "IsCAAValid", "(", "ctx", ",", "&", "vaPB", ".", "IsCAAValidRequest", "{", "Domain", ":", "&", "name", ",", "ValidationMethod", ":", "&", "method", ",", "AccountURIID", ":", "&", "authz", ".", "RegistrationID", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "ra", ".", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "err", ")", "\n", "err", "=", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "authz", ".", "ID", ",", "name", ",", ")", "\n", "}", "else", "if", "resp", ".", "Problem", "!=", "nil", "{", "err", "=", "berrors", ".", "CAAError", "(", "*", "resp", ".", "Problem", ".", "Detail", ")", "\n", "}", "\n", "ch", "<-", "err", "\n", "}", "(", "authz", ")", "\n", "}", "\n", "var", "caaFailures", "[", "]", "string", "\n", "for", "_", "=", "range", "authzs", "{", "if", "err", ":=", "<-", "ch", ";", "berrors", ".", "Is", "(", "err", ",", "berrors", ".", "CAA", ")", "{", "caaFailures", "=", "append", "(", "caaFailures", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "len", "(", "caaFailures", ")", ">", "0", "{", "return", "berrors", ".", "CAAError", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "caaFailures", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// recheckCAA accepts a list of of names that need to have their CAA records // rechecked because their associated authorizations are sufficiently old and // performs the CAA checks required for each. If any of the rechecks fail an // error is returned.
[ "recheckCAA", "accepts", "a", "list", "of", "of", "names", "that", "need", "to", "have", "their", "CAA", "records", "rechecked", "because", "their", "associated", "authorizations", "are", "sufficiently", "old", "and", "performs", "the", "CAA", "checks", "required", "for", "each", ".", "If", "any", "of", "the", "rechecks", "fail", "an", "error", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L763-L818
train
letsencrypt/boulder
ra/ra.go
failOrder
func (ra *RegistrationAuthorityImpl) failOrder( ctx context.Context, order *corepb.Order, prob *probs.ProblemDetails) *corepb.Order { // Convert the problem to a protobuf problem for the *corepb.Order field pbProb, err := bgrpc.ProblemDetailsToPB(prob) if err != nil { ra.log.AuditErrf("Could not convert order error problem to PB: %q", err) return order } // Assign the protobuf problem to the field and save it via the SA order.Error = pbProb if err := ra.SA.SetOrderError(ctx, order); err != nil { ra.log.AuditErrf("Could not persist order error: %q", err) } return order }
go
func (ra *RegistrationAuthorityImpl) failOrder( ctx context.Context, order *corepb.Order, prob *probs.ProblemDetails) *corepb.Order { // Convert the problem to a protobuf problem for the *corepb.Order field pbProb, err := bgrpc.ProblemDetailsToPB(prob) if err != nil { ra.log.AuditErrf("Could not convert order error problem to PB: %q", err) return order } // Assign the protobuf problem to the field and save it via the SA order.Error = pbProb if err := ra.SA.SetOrderError(ctx, order); err != nil { ra.log.AuditErrf("Could not persist order error: %q", err) } return order }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "failOrder", "(", "ctx", "context", ".", "Context", ",", "order", "*", "corepb", ".", "Order", ",", "prob", "*", "probs", ".", "ProblemDetails", ")", "*", "corepb", ".", "Order", "{", "// Convert the problem to a protobuf problem for the *corepb.Order field", "pbProb", ",", "err", ":=", "bgrpc", ".", "ProblemDetailsToPB", "(", "prob", ")", "\n", "if", "err", "!=", "nil", "{", "ra", ".", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "order", "\n", "}", "\n\n", "// Assign the protobuf problem to the field and save it via the SA", "order", ".", "Error", "=", "pbProb", "\n", "if", "err", ":=", "ra", ".", "SA", ".", "SetOrderError", "(", "ctx", ",", "order", ")", ";", "err", "!=", "nil", "{", "ra", ".", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "order", "\n", "}" ]
// failOrder marks an order as failed by setting the problem details field of // the order & persisting it through the SA. If an error occurs doing this we // log it and return the order as-is. There aren't any alternatives if we can't // add the error to the order.
[ "failOrder", "marks", "an", "order", "as", "failed", "by", "setting", "the", "problem", "details", "field", "of", "the", "order", "&", "persisting", "it", "through", "the", "SA", ".", "If", "an", "error", "occurs", "doing", "this", "we", "log", "it", "and", "return", "the", "order", "as", "-", "is", ".", "There", "aren", "t", "any", "alternatives", "if", "we", "can", "t", "add", "the", "error", "to", "the", "order", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L824-L842
train
letsencrypt/boulder
ra/ra.go
FinalizeOrder
func (ra *RegistrationAuthorityImpl) FinalizeOrder(ctx context.Context, req *rapb.FinalizeOrderRequest) (*corepb.Order, error) { order := req.Order if *order.Status != string(core.StatusReady) { return nil, berrors.OrderNotReadyError( "Order's status (%q) is not acceptable for finalization", *order.Status) } // There should never be an order with 0 names at the stage the RA is // processing the order but we check to be on the safe side, throwing an // internal server error if this assumption is ever violated. if len(order.Names) == 0 { return nil, berrors.InternalServerError("Order has no associated names") } // Parse the CSR from the request csrOb, err := x509.ParseCertificateRequest(req.Csr) if err != nil { return nil, err } if err := csrlib.VerifyCSR(csrOb, ra.maxNames, &ra.keyPolicy, ra.PA, ra.forceCNFromSAN, *req.Order.RegistrationID); err != nil { return nil, berrors.MalformedError(err.Error()) } // Dedupe, lowercase and sort both the names from the CSR and the names in the // order. csrNames := core.UniqueLowerNames(csrOb.DNSNames) orderNames := core.UniqueLowerNames(order.Names) // Immediately reject the request if the number of names differ if len(orderNames) != len(csrNames) { return nil, berrors.UnauthorizedError("Order includes different number of names than CSR specifies") } // Check that the order names and the CSR names are an exact match for i, name := range orderNames { if name != csrNames[i] { return nil, berrors.UnauthorizedError("CSR is missing Order domain %q", name) } } // Update the order to be status processing - we issue synchronously at the // present time so this is somewhat artificial/unnecessary but allows planning // for the future. // // NOTE(@cpu): After this point any errors that are encountered must update // the state of the order to invalid by setting the order's error field. // Otherwise the order will be "stuck" in processing state. It can not be // finalized because it isn't pending, but we aren't going to process it // further because we already did and encountered an error. if err := ra.SA.SetOrderProcessing(ctx, order); err != nil { // Fail the order with a server internal error - we weren't able to set the // status to processing and that's unexpected & weird. ra.failOrder(ctx, order, probs.ServerInternal("Error setting order processing")) return nil, err } // Attempt issuance for the order. If the order isn't fully authorized this // will return an error. issueReq := core.CertificateRequest{ Bytes: req.Csr, CSR: csrOb, } cert, err := ra.issueCertificate(ctx, issueReq, accountID(*order.RegistrationID), orderID(*order.Id)) if err != nil { // Fail the order. The problem is computed using // `web.ProblemDetailsForError`, the same function the WFE uses to convert // between `berrors` and problems. This will turn normal expected berrors like // berrors.UnauthorizedError into the correct // `urn:ietf:params:acme:error:unauthorized` problem while not letting // anything like a server internal error through with sensitive info. ra.failOrder(ctx, order, web.ProblemDetailsForError(err, "Error finalizing order")) return nil, err } // Parse the issued certificate to get the serial parsedCertificate, err := x509.ParseCertificate([]byte(cert.DER)) if err != nil { // Fail the order with a server internal error. The certificate we failed // to parse was from our own CA. Bad news! ra.failOrder(ctx, order, probs.ServerInternal("Error parsing certificate DER")) return nil, err } serial := core.SerialToString(parsedCertificate.SerialNumber) // Finalize the order with its new CertificateSerial order.CertificateSerial = &serial if err := ra.SA.FinalizeOrder(ctx, order); err != nil { // Fail the order with a server internal error. We weren't able to persist // the certificate serial and that's unexpected & weird. ra.failOrder(ctx, order, probs.ServerInternal("Error persisting finalized order")) return nil, err } // Update the order status locally since the SA doesn't return the updated // order itself after setting the status validStatus := string(core.StatusValid) order.Status = &validStatus return order, nil }
go
func (ra *RegistrationAuthorityImpl) FinalizeOrder(ctx context.Context, req *rapb.FinalizeOrderRequest) (*corepb.Order, error) { order := req.Order if *order.Status != string(core.StatusReady) { return nil, berrors.OrderNotReadyError( "Order's status (%q) is not acceptable for finalization", *order.Status) } // There should never be an order with 0 names at the stage the RA is // processing the order but we check to be on the safe side, throwing an // internal server error if this assumption is ever violated. if len(order.Names) == 0 { return nil, berrors.InternalServerError("Order has no associated names") } // Parse the CSR from the request csrOb, err := x509.ParseCertificateRequest(req.Csr) if err != nil { return nil, err } if err := csrlib.VerifyCSR(csrOb, ra.maxNames, &ra.keyPolicy, ra.PA, ra.forceCNFromSAN, *req.Order.RegistrationID); err != nil { return nil, berrors.MalformedError(err.Error()) } // Dedupe, lowercase and sort both the names from the CSR and the names in the // order. csrNames := core.UniqueLowerNames(csrOb.DNSNames) orderNames := core.UniqueLowerNames(order.Names) // Immediately reject the request if the number of names differ if len(orderNames) != len(csrNames) { return nil, berrors.UnauthorizedError("Order includes different number of names than CSR specifies") } // Check that the order names and the CSR names are an exact match for i, name := range orderNames { if name != csrNames[i] { return nil, berrors.UnauthorizedError("CSR is missing Order domain %q", name) } } // Update the order to be status processing - we issue synchronously at the // present time so this is somewhat artificial/unnecessary but allows planning // for the future. // // NOTE(@cpu): After this point any errors that are encountered must update // the state of the order to invalid by setting the order's error field. // Otherwise the order will be "stuck" in processing state. It can not be // finalized because it isn't pending, but we aren't going to process it // further because we already did and encountered an error. if err := ra.SA.SetOrderProcessing(ctx, order); err != nil { // Fail the order with a server internal error - we weren't able to set the // status to processing and that's unexpected & weird. ra.failOrder(ctx, order, probs.ServerInternal("Error setting order processing")) return nil, err } // Attempt issuance for the order. If the order isn't fully authorized this // will return an error. issueReq := core.CertificateRequest{ Bytes: req.Csr, CSR: csrOb, } cert, err := ra.issueCertificate(ctx, issueReq, accountID(*order.RegistrationID), orderID(*order.Id)) if err != nil { // Fail the order. The problem is computed using // `web.ProblemDetailsForError`, the same function the WFE uses to convert // between `berrors` and problems. This will turn normal expected berrors like // berrors.UnauthorizedError into the correct // `urn:ietf:params:acme:error:unauthorized` problem while not letting // anything like a server internal error through with sensitive info. ra.failOrder(ctx, order, web.ProblemDetailsForError(err, "Error finalizing order")) return nil, err } // Parse the issued certificate to get the serial parsedCertificate, err := x509.ParseCertificate([]byte(cert.DER)) if err != nil { // Fail the order with a server internal error. The certificate we failed // to parse was from our own CA. Bad news! ra.failOrder(ctx, order, probs.ServerInternal("Error parsing certificate DER")) return nil, err } serial := core.SerialToString(parsedCertificate.SerialNumber) // Finalize the order with its new CertificateSerial order.CertificateSerial = &serial if err := ra.SA.FinalizeOrder(ctx, order); err != nil { // Fail the order with a server internal error. We weren't able to persist // the certificate serial and that's unexpected & weird. ra.failOrder(ctx, order, probs.ServerInternal("Error persisting finalized order")) return nil, err } // Update the order status locally since the SA doesn't return the updated // order itself after setting the status validStatus := string(core.StatusValid) order.Status = &validStatus return order, nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "FinalizeOrder", "(", "ctx", "context", ".", "Context", ",", "req", "*", "rapb", ".", "FinalizeOrderRequest", ")", "(", "*", "corepb", ".", "Order", ",", "error", ")", "{", "order", ":=", "req", ".", "Order", "\n\n", "if", "*", "order", ".", "Status", "!=", "string", "(", "core", ".", "StatusReady", ")", "{", "return", "nil", ",", "berrors", ".", "OrderNotReadyError", "(", "\"", "\"", ",", "*", "order", ".", "Status", ")", "\n", "}", "\n\n", "// There should never be an order with 0 names at the stage the RA is", "// processing the order but we check to be on the safe side, throwing an", "// internal server error if this assumption is ever violated.", "if", "len", "(", "order", ".", "Names", ")", "==", "0", "{", "return", "nil", ",", "berrors", ".", "InternalServerError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Parse the CSR from the request", "csrOb", ",", "err", ":=", "x509", ".", "ParseCertificateRequest", "(", "req", ".", "Csr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "csrlib", ".", "VerifyCSR", "(", "csrOb", ",", "ra", ".", "maxNames", ",", "&", "ra", ".", "keyPolicy", ",", "ra", ".", "PA", ",", "ra", ".", "forceCNFromSAN", ",", "*", "req", ".", "Order", ".", "RegistrationID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "berrors", ".", "MalformedError", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "// Dedupe, lowercase and sort both the names from the CSR and the names in the", "// order.", "csrNames", ":=", "core", ".", "UniqueLowerNames", "(", "csrOb", ".", "DNSNames", ")", "\n", "orderNames", ":=", "core", ".", "UniqueLowerNames", "(", "order", ".", "Names", ")", "\n\n", "// Immediately reject the request if the number of names differ", "if", "len", "(", "orderNames", ")", "!=", "len", "(", "csrNames", ")", "{", "return", "nil", ",", "berrors", ".", "UnauthorizedError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check that the order names and the CSR names are an exact match", "for", "i", ",", "name", ":=", "range", "orderNames", "{", "if", "name", "!=", "csrNames", "[", "i", "]", "{", "return", "nil", ",", "berrors", ".", "UnauthorizedError", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "}", "\n\n", "// Update the order to be status processing - we issue synchronously at the", "// present time so this is somewhat artificial/unnecessary but allows planning", "// for the future.", "//", "// NOTE(@cpu): After this point any errors that are encountered must update", "// the state of the order to invalid by setting the order's error field.", "// Otherwise the order will be \"stuck\" in processing state. It can not be", "// finalized because it isn't pending, but we aren't going to process it", "// further because we already did and encountered an error.", "if", "err", ":=", "ra", ".", "SA", ".", "SetOrderProcessing", "(", "ctx", ",", "order", ")", ";", "err", "!=", "nil", "{", "// Fail the order with a server internal error - we weren't able to set the", "// status to processing and that's unexpected & weird.", "ra", ".", "failOrder", "(", "ctx", ",", "order", ",", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Attempt issuance for the order. If the order isn't fully authorized this", "// will return an error.", "issueReq", ":=", "core", ".", "CertificateRequest", "{", "Bytes", ":", "req", ".", "Csr", ",", "CSR", ":", "csrOb", ",", "}", "\n", "cert", ",", "err", ":=", "ra", ".", "issueCertificate", "(", "ctx", ",", "issueReq", ",", "accountID", "(", "*", "order", ".", "RegistrationID", ")", ",", "orderID", "(", "*", "order", ".", "Id", ")", ")", "\n", "if", "err", "!=", "nil", "{", "// Fail the order. The problem is computed using", "// `web.ProblemDetailsForError`, the same function the WFE uses to convert", "// between `berrors` and problems. This will turn normal expected berrors like", "// berrors.UnauthorizedError into the correct", "// `urn:ietf:params:acme:error:unauthorized` problem while not letting", "// anything like a server internal error through with sensitive info.", "ra", ".", "failOrder", "(", "ctx", ",", "order", ",", "web", ".", "ProblemDetailsForError", "(", "err", ",", "\"", "\"", ")", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Parse the issued certificate to get the serial", "parsedCertificate", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "[", "]", "byte", "(", "cert", ".", "DER", ")", ")", "\n", "if", "err", "!=", "nil", "{", "// Fail the order with a server internal error. The certificate we failed", "// to parse was from our own CA. Bad news!", "ra", ".", "failOrder", "(", "ctx", ",", "order", ",", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "serial", ":=", "core", ".", "SerialToString", "(", "parsedCertificate", ".", "SerialNumber", ")", "\n\n", "// Finalize the order with its new CertificateSerial", "order", ".", "CertificateSerial", "=", "&", "serial", "\n", "if", "err", ":=", "ra", ".", "SA", ".", "FinalizeOrder", "(", "ctx", ",", "order", ")", ";", "err", "!=", "nil", "{", "// Fail the order with a server internal error. We weren't able to persist", "// the certificate serial and that's unexpected & weird.", "ra", ".", "failOrder", "(", "ctx", ",", "order", ",", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Update the order status locally since the SA doesn't return the updated", "// order itself after setting the status", "validStatus", ":=", "string", "(", "core", ".", "StatusValid", ")", "\n", "order", ".", "Status", "=", "&", "validStatus", "\n", "return", "order", ",", "nil", "\n", "}" ]
// FinalizeOrder accepts a request to finalize an order object and, if possible, // issues a certificate to satisfy the order. If an order does not have valid, // unexpired authorizations for all of its associated names an error is // returned. Similarly we vet that all of the names in the order are acceptable // based on current policy and return an error if the order can't be fulfilled. // If successful the order will be returned in processing status for the client // to poll while awaiting finalization to occur.
[ "FinalizeOrder", "accepts", "a", "request", "to", "finalize", "an", "order", "object", "and", "if", "possible", "issues", "a", "certificate", "to", "satisfy", "the", "order", ".", "If", "an", "order", "does", "not", "have", "valid", "unexpired", "authorizations", "for", "all", "of", "its", "associated", "names", "an", "error", "is", "returned", ".", "Similarly", "we", "vet", "that", "all", "of", "the", "names", "in", "the", "order", "are", "acceptable", "based", "on", "current", "policy", "and", "return", "an", "error", "if", "the", "order", "can", "t", "be", "fulfilled", ".", "If", "successful", "the", "order", "will", "be", "returned", "in", "processing", "status", "for", "the", "client", "to", "poll", "while", "awaiting", "finalization", "to", "occur", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L851-L952
train
letsencrypt/boulder
ra/ra.go
NewCertificate
func (ra *RegistrationAuthorityImpl) NewCertificate(ctx context.Context, req core.CertificateRequest, regID int64) (core.Certificate, error) { // Verify the CSR if err := csrlib.VerifyCSR(req.CSR, ra.maxNames, &ra.keyPolicy, ra.PA, ra.forceCNFromSAN, regID); err != nil { return core.Certificate{}, berrors.MalformedError(err.Error()) } // NewCertificate provides an order ID of 0, indicating this is a classic ACME // v1 issuance request from the new certificate endpoint that is not // associated with an ACME v2 order. return ra.issueCertificate(ctx, req, accountID(regID), orderID(0)) }
go
func (ra *RegistrationAuthorityImpl) NewCertificate(ctx context.Context, req core.CertificateRequest, regID int64) (core.Certificate, error) { // Verify the CSR if err := csrlib.VerifyCSR(req.CSR, ra.maxNames, &ra.keyPolicy, ra.PA, ra.forceCNFromSAN, regID); err != nil { return core.Certificate{}, berrors.MalformedError(err.Error()) } // NewCertificate provides an order ID of 0, indicating this is a classic ACME // v1 issuance request from the new certificate endpoint that is not // associated with an ACME v2 order. return ra.issueCertificate(ctx, req, accountID(regID), orderID(0)) }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "NewCertificate", "(", "ctx", "context", ".", "Context", ",", "req", "core", ".", "CertificateRequest", ",", "regID", "int64", ")", "(", "core", ".", "Certificate", ",", "error", ")", "{", "// Verify the CSR", "if", "err", ":=", "csrlib", ".", "VerifyCSR", "(", "req", ".", "CSR", ",", "ra", ".", "maxNames", ",", "&", "ra", ".", "keyPolicy", ",", "ra", ".", "PA", ",", "ra", ".", "forceCNFromSAN", ",", "regID", ")", ";", "err", "!=", "nil", "{", "return", "core", ".", "Certificate", "{", "}", ",", "berrors", ".", "MalformedError", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "// NewCertificate provides an order ID of 0, indicating this is a classic ACME", "// v1 issuance request from the new certificate endpoint that is not", "// associated with an ACME v2 order.", "return", "ra", ".", "issueCertificate", "(", "ctx", ",", "req", ",", "accountID", "(", "regID", ")", ",", "orderID", "(", "0", ")", ")", "\n", "}" ]
// NewCertificate requests the issuance of a certificate.
[ "NewCertificate", "requests", "the", "issuance", "of", "a", "certificate", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L955-L964
train
letsencrypt/boulder
ra/ra.go
issueCertificate
func (ra *RegistrationAuthorityImpl) issueCertificate( ctx context.Context, req core.CertificateRequest, acctID accountID, oID orderID) (core.Certificate, error) { // Construct the log event logEvent := certificateRequestEvent{ ID: core.NewToken(), OrderID: int64(oID), Requester: int64(acctID), RequestTime: ra.clk.Now(), } var result string cert, err := ra.issueCertificateInner(ctx, req, acctID, oID, &logEvent) if err != nil { logEvent.Error = err.Error() result = "error" } else { result = "successful" } logEvent.ResponseTime = ra.clk.Now() ra.log.AuditObject(fmt.Sprintf("Certificate request - %s", result), logEvent) return cert, err }
go
func (ra *RegistrationAuthorityImpl) issueCertificate( ctx context.Context, req core.CertificateRequest, acctID accountID, oID orderID) (core.Certificate, error) { // Construct the log event logEvent := certificateRequestEvent{ ID: core.NewToken(), OrderID: int64(oID), Requester: int64(acctID), RequestTime: ra.clk.Now(), } var result string cert, err := ra.issueCertificateInner(ctx, req, acctID, oID, &logEvent) if err != nil { logEvent.Error = err.Error() result = "error" } else { result = "successful" } logEvent.ResponseTime = ra.clk.Now() ra.log.AuditObject(fmt.Sprintf("Certificate request - %s", result), logEvent) return cert, err }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "issueCertificate", "(", "ctx", "context", ".", "Context", ",", "req", "core", ".", "CertificateRequest", ",", "acctID", "accountID", ",", "oID", "orderID", ")", "(", "core", ".", "Certificate", ",", "error", ")", "{", "// Construct the log event", "logEvent", ":=", "certificateRequestEvent", "{", "ID", ":", "core", ".", "NewToken", "(", ")", ",", "OrderID", ":", "int64", "(", "oID", ")", ",", "Requester", ":", "int64", "(", "acctID", ")", ",", "RequestTime", ":", "ra", ".", "clk", ".", "Now", "(", ")", ",", "}", "\n", "var", "result", "string", "\n", "cert", ",", "err", ":=", "ra", ".", "issueCertificateInner", "(", "ctx", ",", "req", ",", "acctID", ",", "oID", ",", "&", "logEvent", ")", "\n", "if", "err", "!=", "nil", "{", "logEvent", ".", "Error", "=", "err", ".", "Error", "(", ")", "\n", "result", "=", "\"", "\"", "\n", "}", "else", "{", "result", "=", "\"", "\"", "\n", "}", "\n", "logEvent", ".", "ResponseTime", "=", "ra", ".", "clk", ".", "Now", "(", ")", "\n", "ra", ".", "log", ".", "AuditObject", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "result", ")", ",", "logEvent", ")", "\n", "return", "cert", ",", "err", "\n", "}" ]
// issueCertificate sets up a log event structure and captures any errors // encountered during issuance, then calls issueCertificateInner.
[ "issueCertificate", "sets", "up", "a", "log", "event", "structure", "and", "captures", "any", "errors", "encountered", "during", "issuance", "then", "calls", "issueCertificateInner", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L974-L997
train
letsencrypt/boulder
ra/ra.go
domainsForRateLimiting
func domainsForRateLimiting(names []string) ([]string, error) { var domains []string for _, name := range names { domain, err := publicsuffix.Domain(name) if err != nil { // The only possible errors are: // (1) publicsuffix.Domain is giving garbage values // (2) the public suffix is the domain itself // We assume 2 and do not include it in the result. continue } domains = append(domains, domain) } return core.UniqueLowerNames(domains), nil }
go
func domainsForRateLimiting(names []string) ([]string, error) { var domains []string for _, name := range names { domain, err := publicsuffix.Domain(name) if err != nil { // The only possible errors are: // (1) publicsuffix.Domain is giving garbage values // (2) the public suffix is the domain itself // We assume 2 and do not include it in the result. continue } domains = append(domains, domain) } return core.UniqueLowerNames(domains), nil }
[ "func", "domainsForRateLimiting", "(", "names", "[", "]", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "domains", "[", "]", "string", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "domain", ",", "err", ":=", "publicsuffix", ".", "Domain", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "// The only possible errors are:", "// (1) publicsuffix.Domain is giving garbage values", "// (2) the public suffix is the domain itself", "// We assume 2 and do not include it in the result.", "continue", "\n", "}", "\n", "domains", "=", "append", "(", "domains", ",", "domain", ")", "\n", "}", "\n", "return", "core", ".", "UniqueLowerNames", "(", "domains", ")", ",", "nil", "\n", "}" ]
// domainsForRateLimiting transforms a list of FQDNs into a list of eTLD+1's // for the purpose of rate limiting. It also de-duplicates the output // domains. Exact public suffix matches are not included.
[ "domainsForRateLimiting", "transforms", "a", "list", "of", "FQDNs", "into", "a", "list", "of", "eTLD", "+", "1", "s", "for", "the", "purpose", "of", "rate", "limiting", ".", "It", "also", "de", "-", "duplicates", "the", "output", "domains", ".", "Exact", "public", "suffix", "matches", "are", "not", "included", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1174-L1188
train
letsencrypt/boulder
ra/ra.go
suffixesForRateLimiting
func suffixesForRateLimiting(names []string) ([]string, error) { var suffixMatches []string for _, name := range names { _, err := publicsuffix.Domain(name) if err != nil { // Like `domainsForRateLimiting`, the only possible errors here are: // (1) publicsuffix.Domain is giving garbage values // (2) the public suffix is the domain itself // We assume 2 and collect it into the result suffixMatches = append(suffixMatches, name) } } return core.UniqueLowerNames(suffixMatches), nil }
go
func suffixesForRateLimiting(names []string) ([]string, error) { var suffixMatches []string for _, name := range names { _, err := publicsuffix.Domain(name) if err != nil { // Like `domainsForRateLimiting`, the only possible errors here are: // (1) publicsuffix.Domain is giving garbage values // (2) the public suffix is the domain itself // We assume 2 and collect it into the result suffixMatches = append(suffixMatches, name) } } return core.UniqueLowerNames(suffixMatches), nil }
[ "func", "suffixesForRateLimiting", "(", "names", "[", "]", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "suffixMatches", "[", "]", "string", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "_", ",", "err", ":=", "publicsuffix", ".", "Domain", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "// Like `domainsForRateLimiting`, the only possible errors here are:", "// (1) publicsuffix.Domain is giving garbage values", "// (2) the public suffix is the domain itself", "// We assume 2 and collect it into the result", "suffixMatches", "=", "append", "(", "suffixMatches", ",", "name", ")", "\n", "}", "\n", "}", "\n", "return", "core", ".", "UniqueLowerNames", "(", "suffixMatches", ")", ",", "nil", "\n", "}" ]
// suffixesForRateLimiting returns the unique subset of input names that are // exactly equal to a public suffix.
[ "suffixesForRateLimiting", "returns", "the", "unique", "subset", "of", "input", "names", "that", "are", "exactly", "equal", "to", "a", "public", "suffix", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1192-L1205
train
letsencrypt/boulder
ra/ra.go
enforceNameCounts
func (ra *RegistrationAuthorityImpl) enforceNameCounts( ctx context.Context, names []string, limit ratelimit.RateLimitPolicy, regID int64, countFunc certCountRPC) ([]string, error) { now := ra.clk.Now() windowBegin := limit.WindowBegin(now) counts, err := countFunc(ctx, names, windowBegin, now) if err != nil { return nil, err } var badNames []string for _, entry := range counts { // Should not happen, but be defensive. if entry.Count == nil || entry.Name == nil { return nil, fmt.Errorf("CountByNames_MapElement had nil Count or Name") } if int(*entry.Count) >= limit.GetThreshold(*entry.Name, regID) { badNames = append(badNames, *entry.Name) } } return badNames, nil }
go
func (ra *RegistrationAuthorityImpl) enforceNameCounts( ctx context.Context, names []string, limit ratelimit.RateLimitPolicy, regID int64, countFunc certCountRPC) ([]string, error) { now := ra.clk.Now() windowBegin := limit.WindowBegin(now) counts, err := countFunc(ctx, names, windowBegin, now) if err != nil { return nil, err } var badNames []string for _, entry := range counts { // Should not happen, but be defensive. if entry.Count == nil || entry.Name == nil { return nil, fmt.Errorf("CountByNames_MapElement had nil Count or Name") } if int(*entry.Count) >= limit.GetThreshold(*entry.Name, regID) { badNames = append(badNames, *entry.Name) } } return badNames, nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "enforceNameCounts", "(", "ctx", "context", ".", "Context", ",", "names", "[", "]", "string", ",", "limit", "ratelimit", ".", "RateLimitPolicy", ",", "regID", "int64", ",", "countFunc", "certCountRPC", ")", "(", "[", "]", "string", ",", "error", ")", "{", "now", ":=", "ra", ".", "clk", ".", "Now", "(", ")", "\n", "windowBegin", ":=", "limit", ".", "WindowBegin", "(", "now", ")", "\n", "counts", ",", "err", ":=", "countFunc", "(", "ctx", ",", "names", ",", "windowBegin", ",", "now", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "badNames", "[", "]", "string", "\n", "for", "_", ",", "entry", ":=", "range", "counts", "{", "// Should not happen, but be defensive.", "if", "entry", ".", "Count", "==", "nil", "||", "entry", ".", "Name", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "int", "(", "*", "entry", ".", "Count", ")", ">=", "limit", ".", "GetThreshold", "(", "*", "entry", ".", "Name", ",", "regID", ")", "{", "badNames", "=", "append", "(", "badNames", ",", "*", "entry", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "return", "badNames", ",", "nil", "\n", "}" ]
// enforceNameCounts uses the provided count RPC to find a count of certificates // for each of the names. If the count for any of the names exceeds the limit // for the given registration then the names out of policy are returned to be // used for a rate limit error.
[ "enforceNameCounts", "uses", "the", "provided", "count", "RPC", "to", "find", "a", "count", "of", "certificates", "for", "each", "of", "the", "names", ".", "If", "the", "count", "for", "any", "of", "the", "names", "exceeds", "the", "limit", "for", "the", "given", "registration", "then", "the", "names", "out", "of", "policy", "are", "returned", "to", "be", "used", "for", "a", "rate", "limit", "error", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1215-L1240
train
letsencrypt/boulder
ra/ra.go
UpdateRegistration
func (ra *RegistrationAuthorityImpl) UpdateRegistration(ctx context.Context, base core.Registration, update core.Registration) (core.Registration, error) { if changed := mergeUpdate(&base, update); !changed { // If merging the update didn't actually change the base then our work is // done, we can return before calling ra.SA.UpdateRegistration since theres // nothing for the SA to do return base, nil } err := ra.validateContacts(ctx, base.Contact) if err != nil { return core.Registration{}, err } err = ra.SA.UpdateRegistration(ctx, base) if err != nil { // berrors.InternalServerError since the user-data was validated before being // passed to the SA. err = berrors.InternalServerError("Could not update registration: %s", err) return core.Registration{}, err } ra.stats.Inc("UpdatedRegistrations", 1) return base, nil }
go
func (ra *RegistrationAuthorityImpl) UpdateRegistration(ctx context.Context, base core.Registration, update core.Registration) (core.Registration, error) { if changed := mergeUpdate(&base, update); !changed { // If merging the update didn't actually change the base then our work is // done, we can return before calling ra.SA.UpdateRegistration since theres // nothing for the SA to do return base, nil } err := ra.validateContacts(ctx, base.Contact) if err != nil { return core.Registration{}, err } err = ra.SA.UpdateRegistration(ctx, base) if err != nil { // berrors.InternalServerError since the user-data was validated before being // passed to the SA. err = berrors.InternalServerError("Could not update registration: %s", err) return core.Registration{}, err } ra.stats.Inc("UpdatedRegistrations", 1) return base, nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "UpdateRegistration", "(", "ctx", "context", ".", "Context", ",", "base", "core", ".", "Registration", ",", "update", "core", ".", "Registration", ")", "(", "core", ".", "Registration", ",", "error", ")", "{", "if", "changed", ":=", "mergeUpdate", "(", "&", "base", ",", "update", ")", ";", "!", "changed", "{", "// If merging the update didn't actually change the base then our work is", "// done, we can return before calling ra.SA.UpdateRegistration since theres", "// nothing for the SA to do", "return", "base", ",", "nil", "\n", "}", "\n\n", "err", ":=", "ra", ".", "validateContacts", "(", "ctx", ",", "base", ".", "Contact", ")", "\n", "if", "err", "!=", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "err", "\n", "}", "\n\n", "err", "=", "ra", ".", "SA", ".", "UpdateRegistration", "(", "ctx", ",", "base", ")", "\n", "if", "err", "!=", "nil", "{", "// berrors.InternalServerError since the user-data was validated before being", "// passed to the SA.", "err", "=", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "err", ")", "\n", "return", "core", ".", "Registration", "{", "}", ",", "err", "\n", "}", "\n\n", "ra", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "base", ",", "nil", "\n", "}" ]
// UpdateRegistration updates an existing Registration with new values. Caller // is responsible for making sure that update.Key is only different from base.Key // if it is being called from the WFE key change endpoint.
[ "UpdateRegistration", "updates", "an", "existing", "Registration", "with", "new", "values", ".", "Caller", "is", "responsible", "for", "making", "sure", "that", "update", ".", "Key", "is", "only", "different", "from", "base", ".", "Key", "if", "it", "is", "being", "called", "from", "the", "WFE", "key", "change", "endpoint", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1355-L1378
train
letsencrypt/boulder
ra/ra.go
mergeUpdate
func mergeUpdate(r *core.Registration, input core.Registration) bool { var changed bool // Note: we allow input.Contact to overwrite r.Contact even if the former is // empty in order to allow users to remove the contact associated with // a registration. Since the field type is a pointer to slice of pointers we // can perform a nil check to differentiate between an empty value and a nil // (e.g. not provided) value if input.Contact != nil && !contactsEqual(r, input) { r.Contact = input.Contact changed = true } // If there is an agreement in the input and it's not the same as the base, // then we update the base if len(input.Agreement) > 0 && input.Agreement != r.Agreement { r.Agreement = input.Agreement changed = true } if input.Key != nil { if r.Key != nil { sameKey, _ := core.PublicKeysEqual(r.Key.Key, input.Key.Key) if !sameKey { r.Key = input.Key changed = true } } } return changed }
go
func mergeUpdate(r *core.Registration, input core.Registration) bool { var changed bool // Note: we allow input.Contact to overwrite r.Contact even if the former is // empty in order to allow users to remove the contact associated with // a registration. Since the field type is a pointer to slice of pointers we // can perform a nil check to differentiate between an empty value and a nil // (e.g. not provided) value if input.Contact != nil && !contactsEqual(r, input) { r.Contact = input.Contact changed = true } // If there is an agreement in the input and it's not the same as the base, // then we update the base if len(input.Agreement) > 0 && input.Agreement != r.Agreement { r.Agreement = input.Agreement changed = true } if input.Key != nil { if r.Key != nil { sameKey, _ := core.PublicKeysEqual(r.Key.Key, input.Key.Key) if !sameKey { r.Key = input.Key changed = true } } } return changed }
[ "func", "mergeUpdate", "(", "r", "*", "core", ".", "Registration", ",", "input", "core", ".", "Registration", ")", "bool", "{", "var", "changed", "bool", "\n\n", "// Note: we allow input.Contact to overwrite r.Contact even if the former is", "// empty in order to allow users to remove the contact associated with", "// a registration. Since the field type is a pointer to slice of pointers we", "// can perform a nil check to differentiate between an empty value and a nil", "// (e.g. not provided) value", "if", "input", ".", "Contact", "!=", "nil", "&&", "!", "contactsEqual", "(", "r", ",", "input", ")", "{", "r", ".", "Contact", "=", "input", ".", "Contact", "\n", "changed", "=", "true", "\n", "}", "\n\n", "// If there is an agreement in the input and it's not the same as the base,", "// then we update the base", "if", "len", "(", "input", ".", "Agreement", ")", ">", "0", "&&", "input", ".", "Agreement", "!=", "r", ".", "Agreement", "{", "r", ".", "Agreement", "=", "input", ".", "Agreement", "\n", "changed", "=", "true", "\n", "}", "\n\n", "if", "input", ".", "Key", "!=", "nil", "{", "if", "r", ".", "Key", "!=", "nil", "{", "sameKey", ",", "_", ":=", "core", ".", "PublicKeysEqual", "(", "r", ".", "Key", ".", "Key", ",", "input", ".", "Key", ".", "Key", ")", "\n", "if", "!", "sameKey", "{", "r", ".", "Key", "=", "input", ".", "Key", "\n", "changed", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "changed", "\n", "}" ]
// MergeUpdate copies a subset of information from the input Registration // into the Registration r. It returns true if an update was performed and the base object // was changed, and false if no change was made.
[ "MergeUpdate", "copies", "a", "subset", "of", "information", "from", "the", "input", "Registration", "into", "the", "Registration", "r", ".", "It", "returns", "true", "if", "an", "update", "was", "performed", "and", "the", "base", "object", "was", "changed", "and", "false", "if", "no", "change", "was", "made", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1410-L1441
train
letsencrypt/boulder
ra/ra.go
revokeCertificate
func (ra *RegistrationAuthorityImpl) revokeCertificate(ctx context.Context, cert x509.Certificate, code revocation.Reason) error { now := time.Now() signRequest := core.OCSPSigningRequest{ CertDER: cert.Raw, Status: string(core.OCSPStatusRevoked), Reason: code, RevokedAt: now, } ocspResponse, err := ra.CA.GenerateOCSP(ctx, signRequest) if err != nil { return err } serial := core.SerialToString(cert.SerialNumber) nowUnix := now.UnixNano() reason := int64(code) err = ra.SA.RevokeCertificate(ctx, &sapb.RevokeCertificateRequest{ Serial: &serial, Reason: &reason, Date: &nowUnix, Response: ocspResponse, }) if err != nil { return err } purgeURLs, err := akamai.GeneratePurgeURLs(cert.Raw, ra.issuer) if err != nil { return err } _, err = ra.purger.Purge(ctx, &akamaipb.PurgeRequest{Urls: purgeURLs}) if err != nil { return err } return nil }
go
func (ra *RegistrationAuthorityImpl) revokeCertificate(ctx context.Context, cert x509.Certificate, code revocation.Reason) error { now := time.Now() signRequest := core.OCSPSigningRequest{ CertDER: cert.Raw, Status: string(core.OCSPStatusRevoked), Reason: code, RevokedAt: now, } ocspResponse, err := ra.CA.GenerateOCSP(ctx, signRequest) if err != nil { return err } serial := core.SerialToString(cert.SerialNumber) nowUnix := now.UnixNano() reason := int64(code) err = ra.SA.RevokeCertificate(ctx, &sapb.RevokeCertificateRequest{ Serial: &serial, Reason: &reason, Date: &nowUnix, Response: ocspResponse, }) if err != nil { return err } purgeURLs, err := akamai.GeneratePurgeURLs(cert.Raw, ra.issuer) if err != nil { return err } _, err = ra.purger.Purge(ctx, &akamaipb.PurgeRequest{Urls: purgeURLs}) if err != nil { return err } return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "revokeCertificate", "(", "ctx", "context", ".", "Context", ",", "cert", "x509", ".", "Certificate", ",", "code", "revocation", ".", "Reason", ")", "error", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "signRequest", ":=", "core", ".", "OCSPSigningRequest", "{", "CertDER", ":", "cert", ".", "Raw", ",", "Status", ":", "string", "(", "core", ".", "OCSPStatusRevoked", ")", ",", "Reason", ":", "code", ",", "RevokedAt", ":", "now", ",", "}", "\n", "ocspResponse", ",", "err", ":=", "ra", ".", "CA", ".", "GenerateOCSP", "(", "ctx", ",", "signRequest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "serial", ":=", "core", ".", "SerialToString", "(", "cert", ".", "SerialNumber", ")", "\n", "nowUnix", ":=", "now", ".", "UnixNano", "(", ")", "\n", "reason", ":=", "int64", "(", "code", ")", "\n", "err", "=", "ra", ".", "SA", ".", "RevokeCertificate", "(", "ctx", ",", "&", "sapb", ".", "RevokeCertificateRequest", "{", "Serial", ":", "&", "serial", ",", "Reason", ":", "&", "reason", ",", "Date", ":", "&", "nowUnix", ",", "Response", ":", "ocspResponse", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "purgeURLs", ",", "err", ":=", "akamai", ".", "GeneratePurgeURLs", "(", "cert", ".", "Raw", ",", "ra", ".", "issuer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "ra", ".", "purger", ".", "Purge", "(", "ctx", ",", "&", "akamaipb", ".", "PurgeRequest", "{", "Urls", ":", "purgeURLs", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// revokeCertificate generates a revoked OCSP response for the given certificate, stores // the revocation information, and purges OCSP request URLs from Akamai.
[ "revokeCertificate", "generates", "a", "revoked", "OCSP", "response", "for", "the", "given", "certificate", "stores", "the", "revocation", "information", "and", "purges", "OCSP", "request", "URLs", "from", "Akamai", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1572-L1606
train
letsencrypt/boulder
ra/ra.go
RevokeCertificateWithReg
func (ra *RegistrationAuthorityImpl) RevokeCertificateWithReg(ctx context.Context, cert x509.Certificate, revocationCode revocation.Reason, regID int64) error { serialString := core.SerialToString(cert.SerialNumber) var err error if features.Enabled(features.RevokeAtRA) { err = ra.revokeCertificate(ctx, cert, revocationCode) } else { err = ra.SA.MarkCertificateRevoked(ctx, serialString, revocationCode) } state := "Failure" defer func() { // Needed: // Serial // CN // DNS names // Revocation reason // Registration ID of requester // Error (if there was one) ra.log.AuditInfof("%s, Request by registration ID: %d", revokeEvent(state, serialString, cert.Subject.CommonName, cert.DNSNames, revocationCode), regID) }() if err != nil { state = fmt.Sprintf("Failure -- %s", err) return err } state = "Success" ra.stats.Inc("RevokedCertificates", 1) return nil }
go
func (ra *RegistrationAuthorityImpl) RevokeCertificateWithReg(ctx context.Context, cert x509.Certificate, revocationCode revocation.Reason, regID int64) error { serialString := core.SerialToString(cert.SerialNumber) var err error if features.Enabled(features.RevokeAtRA) { err = ra.revokeCertificate(ctx, cert, revocationCode) } else { err = ra.SA.MarkCertificateRevoked(ctx, serialString, revocationCode) } state := "Failure" defer func() { // Needed: // Serial // CN // DNS names // Revocation reason // Registration ID of requester // Error (if there was one) ra.log.AuditInfof("%s, Request by registration ID: %d", revokeEvent(state, serialString, cert.Subject.CommonName, cert.DNSNames, revocationCode), regID) }() if err != nil { state = fmt.Sprintf("Failure -- %s", err) return err } state = "Success" ra.stats.Inc("RevokedCertificates", 1) return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "RevokeCertificateWithReg", "(", "ctx", "context", ".", "Context", ",", "cert", "x509", ".", "Certificate", ",", "revocationCode", "revocation", ".", "Reason", ",", "regID", "int64", ")", "error", "{", "serialString", ":=", "core", ".", "SerialToString", "(", "cert", ".", "SerialNumber", ")", "\n", "var", "err", "error", "\n", "if", "features", ".", "Enabled", "(", "features", ".", "RevokeAtRA", ")", "{", "err", "=", "ra", ".", "revokeCertificate", "(", "ctx", ",", "cert", ",", "revocationCode", ")", "\n", "}", "else", "{", "err", "=", "ra", ".", "SA", ".", "MarkCertificateRevoked", "(", "ctx", ",", "serialString", ",", "revocationCode", ")", "\n", "}", "\n\n", "state", ":=", "\"", "\"", "\n", "defer", "func", "(", ")", "{", "// Needed:", "// Serial", "// CN", "// DNS names", "// Revocation reason", "// Registration ID of requester", "// Error (if there was one)", "ra", ".", "log", ".", "AuditInfof", "(", "\"", "\"", ",", "revokeEvent", "(", "state", ",", "serialString", ",", "cert", ".", "Subject", ".", "CommonName", ",", "cert", ".", "DNSNames", ",", "revocationCode", ")", ",", "regID", ")", "\n", "}", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "state", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "state", "=", "\"", "\"", "\n", "ra", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "nil", "\n", "}" ]
// RevokeCertificateWithReg terminates trust in the certificate provided.
[ "RevokeCertificateWithReg", "terminates", "trust", "in", "the", "certificate", "provided", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1609-L1640
train
letsencrypt/boulder
ra/ra.go
onValidationUpdate
func (ra *RegistrationAuthorityImpl) onValidationUpdate(ctx context.Context, authz core.Authorization) error { // Consider validation successful if any of the challenges // specified in the authorization has been fulfilled for _, ch := range authz.Challenges { if ch.Status == core.StatusValid { authz.Status = core.StatusValid } } // If no validation succeeded, then the authorization is invalid if authz.Status != core.StatusValid { authz.Status = core.StatusInvalid } else { exp := ra.clk.Now().Add(ra.authorizationLifetime) authz.Expires = &exp } // Finalize the authorization err := ra.SA.FinalizeAuthorization(ctx, authz) if err != nil { return err } ra.stats.Inc("FinalizedAuthorizations", 1) return nil }
go
func (ra *RegistrationAuthorityImpl) onValidationUpdate(ctx context.Context, authz core.Authorization) error { // Consider validation successful if any of the challenges // specified in the authorization has been fulfilled for _, ch := range authz.Challenges { if ch.Status == core.StatusValid { authz.Status = core.StatusValid } } // If no validation succeeded, then the authorization is invalid if authz.Status != core.StatusValid { authz.Status = core.StatusInvalid } else { exp := ra.clk.Now().Add(ra.authorizationLifetime) authz.Expires = &exp } // Finalize the authorization err := ra.SA.FinalizeAuthorization(ctx, authz) if err != nil { return err } ra.stats.Inc("FinalizedAuthorizations", 1) return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "onValidationUpdate", "(", "ctx", "context", ".", "Context", ",", "authz", "core", ".", "Authorization", ")", "error", "{", "// Consider validation successful if any of the challenges", "// specified in the authorization has been fulfilled", "for", "_", ",", "ch", ":=", "range", "authz", ".", "Challenges", "{", "if", "ch", ".", "Status", "==", "core", ".", "StatusValid", "{", "authz", ".", "Status", "=", "core", ".", "StatusValid", "\n", "}", "\n", "}", "\n\n", "// If no validation succeeded, then the authorization is invalid", "if", "authz", ".", "Status", "!=", "core", ".", "StatusValid", "{", "authz", ".", "Status", "=", "core", ".", "StatusInvalid", "\n", "}", "else", "{", "exp", ":=", "ra", ".", "clk", ".", "Now", "(", ")", ".", "Add", "(", "ra", ".", "authorizationLifetime", ")", "\n", "authz", ".", "Expires", "=", "&", "exp", "\n", "}", "\n\n", "// Finalize the authorization", "err", ":=", "ra", ".", "SA", ".", "FinalizeAuthorization", "(", "ctx", ",", "authz", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "ra", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "nil", "\n", "}" ]
// onValidationUpdate saves a validation's new status after receiving an // authorization back from the VA.
[ "onValidationUpdate", "saves", "a", "validation", "s", "new", "status", "after", "receiving", "an", "authorization", "back", "from", "the", "VA", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1680-L1705
train
letsencrypt/boulder
ra/ra.go
DeactivateRegistration
func (ra *RegistrationAuthorityImpl) DeactivateRegistration(ctx context.Context, reg core.Registration) error { if reg.Status != core.StatusValid { return berrors.MalformedError("only valid registrations can be deactivated") } err := ra.SA.DeactivateRegistration(ctx, reg.ID) if err != nil { return berrors.InternalServerError(err.Error()) } return nil }
go
func (ra *RegistrationAuthorityImpl) DeactivateRegistration(ctx context.Context, reg core.Registration) error { if reg.Status != core.StatusValid { return berrors.MalformedError("only valid registrations can be deactivated") } err := ra.SA.DeactivateRegistration(ctx, reg.ID) if err != nil { return berrors.InternalServerError(err.Error()) } return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "DeactivateRegistration", "(", "ctx", "context", ".", "Context", ",", "reg", "core", ".", "Registration", ")", "error", "{", "if", "reg", ".", "Status", "!=", "core", ".", "StatusValid", "{", "return", "berrors", ".", "MalformedError", "(", "\"", "\"", ")", "\n", "}", "\n", "err", ":=", "ra", ".", "SA", ".", "DeactivateRegistration", "(", "ctx", ",", "reg", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "berrors", ".", "InternalServerError", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeactivateRegistration deactivates a valid registration
[ "DeactivateRegistration", "deactivates", "a", "valid", "registration" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1708-L1717
train
letsencrypt/boulder
ra/ra.go
DeactivateAuthorization
func (ra *RegistrationAuthorityImpl) DeactivateAuthorization(ctx context.Context, auth core.Authorization) error { if auth.Status != core.StatusValid && auth.Status != core.StatusPending { return berrors.MalformedError("only valid and pending authorizations can be deactivated") } err := ra.SA.DeactivateAuthorization(ctx, auth.ID) if err != nil { return berrors.InternalServerError(err.Error()) } return nil }
go
func (ra *RegistrationAuthorityImpl) DeactivateAuthorization(ctx context.Context, auth core.Authorization) error { if auth.Status != core.StatusValid && auth.Status != core.StatusPending { return berrors.MalformedError("only valid and pending authorizations can be deactivated") } err := ra.SA.DeactivateAuthorization(ctx, auth.ID) if err != nil { return berrors.InternalServerError(err.Error()) } return nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "DeactivateAuthorization", "(", "ctx", "context", ".", "Context", ",", "auth", "core", ".", "Authorization", ")", "error", "{", "if", "auth", ".", "Status", "!=", "core", ".", "StatusValid", "&&", "auth", ".", "Status", "!=", "core", ".", "StatusPending", "{", "return", "berrors", ".", "MalformedError", "(", "\"", "\"", ")", "\n", "}", "\n", "err", ":=", "ra", ".", "SA", ".", "DeactivateAuthorization", "(", "ctx", ",", "auth", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "berrors", ".", "InternalServerError", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeactivateAuthorization deactivates a currently valid authorization
[ "DeactivateAuthorization", "deactivates", "a", "currently", "valid", "authorization" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1720-L1729
train
letsencrypt/boulder
ra/ra.go
createPendingAuthz
func (ra *RegistrationAuthorityImpl) createPendingAuthz(ctx context.Context, reg int64, identifier core.AcmeIdentifier, v2 bool) (*corepb.Authorization, error) { expires := ra.clk.Now().Add(ra.pendingAuthorizationLifetime).Truncate(time.Second).UnixNano() status := string(core.StatusPending) authz := &corepb.Authorization{ Identifier: &identifier.Value, RegistrationID: &reg, Status: &status, Expires: &expires, V2: &v2, } // Create challenges. The WFE will update them with URIs before sending them out. challenges, err := ra.PA.ChallengesFor(identifier) if err != nil { // The only time ChallengesFor errors it is a fatal configuration error // where challenges required by policy for an identifier are not enabled. We // want to treat this as an internal server error. return nil, berrors.InternalServerError(err.Error()) } // Check each challenge for sanity. for _, challenge := range challenges { if err := challenge.CheckConsistencyForClientOffer(); err != nil { // berrors.InternalServerError because we generated these challenges, they should // be OK. err = berrors.InternalServerError("challenge didn't pass sanity check: %+v", challenge) return nil, err } challPB, err := bgrpc.ChallengeToPB(challenge) if err != nil { return nil, err } authz.Challenges = append(authz.Challenges, challPB) } return authz, nil }
go
func (ra *RegistrationAuthorityImpl) createPendingAuthz(ctx context.Context, reg int64, identifier core.AcmeIdentifier, v2 bool) (*corepb.Authorization, error) { expires := ra.clk.Now().Add(ra.pendingAuthorizationLifetime).Truncate(time.Second).UnixNano() status := string(core.StatusPending) authz := &corepb.Authorization{ Identifier: &identifier.Value, RegistrationID: &reg, Status: &status, Expires: &expires, V2: &v2, } // Create challenges. The WFE will update them with URIs before sending them out. challenges, err := ra.PA.ChallengesFor(identifier) if err != nil { // The only time ChallengesFor errors it is a fatal configuration error // where challenges required by policy for an identifier are not enabled. We // want to treat this as an internal server error. return nil, berrors.InternalServerError(err.Error()) } // Check each challenge for sanity. for _, challenge := range challenges { if err := challenge.CheckConsistencyForClientOffer(); err != nil { // berrors.InternalServerError because we generated these challenges, they should // be OK. err = berrors.InternalServerError("challenge didn't pass sanity check: %+v", challenge) return nil, err } challPB, err := bgrpc.ChallengeToPB(challenge) if err != nil { return nil, err } authz.Challenges = append(authz.Challenges, challPB) } return authz, nil }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "createPendingAuthz", "(", "ctx", "context", ".", "Context", ",", "reg", "int64", ",", "identifier", "core", ".", "AcmeIdentifier", ",", "v2", "bool", ")", "(", "*", "corepb", ".", "Authorization", ",", "error", ")", "{", "expires", ":=", "ra", ".", "clk", ".", "Now", "(", ")", ".", "Add", "(", "ra", ".", "pendingAuthorizationLifetime", ")", ".", "Truncate", "(", "time", ".", "Second", ")", ".", "UnixNano", "(", ")", "\n", "status", ":=", "string", "(", "core", ".", "StatusPending", ")", "\n", "authz", ":=", "&", "corepb", ".", "Authorization", "{", "Identifier", ":", "&", "identifier", ".", "Value", ",", "RegistrationID", ":", "&", "reg", ",", "Status", ":", "&", "status", ",", "Expires", ":", "&", "expires", ",", "V2", ":", "&", "v2", ",", "}", "\n\n", "// Create challenges. The WFE will update them with URIs before sending them out.", "challenges", ",", "err", ":=", "ra", ".", "PA", ".", "ChallengesFor", "(", "identifier", ")", "\n", "if", "err", "!=", "nil", "{", "// The only time ChallengesFor errors it is a fatal configuration error", "// where challenges required by policy for an identifier are not enabled. We", "// want to treat this as an internal server error.", "return", "nil", ",", "berrors", ".", "InternalServerError", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "// Check each challenge for sanity.", "for", "_", ",", "challenge", ":=", "range", "challenges", "{", "if", "err", ":=", "challenge", ".", "CheckConsistencyForClientOffer", "(", ")", ";", "err", "!=", "nil", "{", "// berrors.InternalServerError because we generated these challenges, they should", "// be OK.", "err", "=", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "challenge", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "challPB", ",", "err", ":=", "bgrpc", ".", "ChallengeToPB", "(", "challenge", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "authz", ".", "Challenges", "=", "append", "(", "authz", ".", "Challenges", ",", "challPB", ")", "\n", "}", "\n", "return", "authz", ",", "nil", "\n", "}" ]
// createPendingAuthz checks that a name is allowed for issuance and creates the // necessary challenges for it and puts this and all of the relevant information // into a corepb.Authorization for transmission to the SA to be stored
[ "createPendingAuthz", "checks", "that", "a", "name", "is", "allowed", "for", "issuance", "and", "creates", "the", "necessary", "challenges", "for", "it", "and", "puts", "this", "and", "all", "of", "the", "relevant", "information", "into", "a", "corepb", ".", "Authorization", "for", "transmission", "to", "the", "SA", "to", "be", "stored" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1943-L1977
train
letsencrypt/boulder
ra/ra.go
authzValidChallengeEnabled
func (ra *RegistrationAuthorityImpl) authzValidChallengeEnabled(authz *core.Authorization) bool { for _, chall := range authz.Challenges { if chall.Status == core.StatusValid { return ra.PA.ChallengeTypeEnabled(chall.Type) } } return false }
go
func (ra *RegistrationAuthorityImpl) authzValidChallengeEnabled(authz *core.Authorization) bool { for _, chall := range authz.Challenges { if chall.Status == core.StatusValid { return ra.PA.ChallengeTypeEnabled(chall.Type) } } return false }
[ "func", "(", "ra", "*", "RegistrationAuthorityImpl", ")", "authzValidChallengeEnabled", "(", "authz", "*", "core", ".", "Authorization", ")", "bool", "{", "for", "_", ",", "chall", ":=", "range", "authz", ".", "Challenges", "{", "if", "chall", ".", "Status", "==", "core", ".", "StatusValid", "{", "return", "ra", ".", "PA", ".", "ChallengeTypeEnabled", "(", "chall", ".", "Type", ")", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// authzValidChallengeEnabled checks whether the valid challenge in an authorization uses a type // which is still enabled for given regID
[ "authzValidChallengeEnabled", "checks", "whether", "the", "valid", "challenge", "in", "an", "authorization", "uses", "a", "type", "which", "is", "still", "enabled", "for", "given", "regID" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1981-L1988
train
letsencrypt/boulder
ra/ra.go
wildcardOverlap
func wildcardOverlap(dnsNames []string) error { nameMap := make(map[string]bool, len(dnsNames)) for _, v := range dnsNames { nameMap[v] = true } for name := range nameMap { if name[0] == '*' { continue } labels := strings.Split(name, ".") labels[0] = "*" if nameMap[strings.Join(labels, ".")] { return berrors.MalformedError( "Domain name %q is redundant with a wildcard domain in the same request. Remove one or the other from the certificate request.", name) } } return nil }
go
func wildcardOverlap(dnsNames []string) error { nameMap := make(map[string]bool, len(dnsNames)) for _, v := range dnsNames { nameMap[v] = true } for name := range nameMap { if name[0] == '*' { continue } labels := strings.Split(name, ".") labels[0] = "*" if nameMap[strings.Join(labels, ".")] { return berrors.MalformedError( "Domain name %q is redundant with a wildcard domain in the same request. Remove one or the other from the certificate request.", name) } } return nil }
[ "func", "wildcardOverlap", "(", "dnsNames", "[", "]", "string", ")", "error", "{", "nameMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ",", "len", "(", "dnsNames", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "dnsNames", "{", "nameMap", "[", "v", "]", "=", "true", "\n", "}", "\n", "for", "name", ":=", "range", "nameMap", "{", "if", "name", "[", "0", "]", "==", "'*'", "{", "continue", "\n", "}", "\n", "labels", ":=", "strings", ".", "Split", "(", "name", ",", "\"", "\"", ")", "\n", "labels", "[", "0", "]", "=", "\"", "\"", "\n", "if", "nameMap", "[", "strings", ".", "Join", "(", "labels", ",", "\"", "\"", ")", "]", "{", "return", "berrors", ".", "MalformedError", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// wildcardOverlap takes a slice of domain names and returns an error if any of // them is a non-wildcard FQDN that overlaps with a wildcard domain in the map.
[ "wildcardOverlap", "takes", "a", "slice", "of", "domain", "names", "and", "returns", "an", "error", "if", "any", "of", "them", "is", "a", "non", "-", "wildcard", "FQDN", "that", "overlaps", "with", "a", "wildcard", "domain", "in", "the", "map", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ra/ra.go#L1992-L2009
train
letsencrypt/boulder
cmd/ocsp-responder/main.go
NewSourceFromDatabase
func NewSourceFromDatabase( dbMap dbSelector, caKeyHash []byte, reqSerialPrefixes []string, timeout time.Duration, log blog.Logger, ) (src *DBSource, err error) { src = &DBSource{ dbMap: dbMap, caKeyHash: caKeyHash, reqSerialPrefixes: reqSerialPrefixes, timeout: timeout, log: log, } return }
go
func NewSourceFromDatabase( dbMap dbSelector, caKeyHash []byte, reqSerialPrefixes []string, timeout time.Duration, log blog.Logger, ) (src *DBSource, err error) { src = &DBSource{ dbMap: dbMap, caKeyHash: caKeyHash, reqSerialPrefixes: reqSerialPrefixes, timeout: timeout, log: log, } return }
[ "func", "NewSourceFromDatabase", "(", "dbMap", "dbSelector", ",", "caKeyHash", "[", "]", "byte", ",", "reqSerialPrefixes", "[", "]", "string", ",", "timeout", "time", ".", "Duration", ",", "log", "blog", ".", "Logger", ",", ")", "(", "src", "*", "DBSource", ",", "err", "error", ")", "{", "src", "=", "&", "DBSource", "{", "dbMap", ":", "dbMap", ",", "caKeyHash", ":", "caKeyHash", ",", "reqSerialPrefixes", ":", "reqSerialPrefixes", ",", "timeout", ":", "timeout", ",", "log", ":", "log", ",", "}", "\n", "return", "\n", "}" ]
// NewSourceFromDatabase produces a DBSource representing the binding of a // given DB schema to a CA key.
[ "NewSourceFromDatabase", "produces", "a", "DBSource", "representing", "the", "binding", "of", "a", "given", "DB", "schema", "to", "a", "CA", "key", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/ocsp-responder/main.go#L87-L102
train
letsencrypt/boulder
cmd/ocsp-responder/main.go
Response
func (src *DBSource) Response(req *ocsp.Request) ([]byte, http.Header, error) { // Check that this request is for the proper CA if bytes.Compare(req.IssuerKeyHash, src.caKeyHash) != 0 { src.log.Debugf("Request intended for CA Cert ID: %s", hex.EncodeToString(req.IssuerKeyHash)) return nil, nil, cfocsp.ErrNotFound } serialString := core.SerialToString(req.SerialNumber) if len(src.reqSerialPrefixes) > 0 { match := false for _, prefix := range src.reqSerialPrefixes { if match = strings.HasPrefix(serialString, prefix); match { break } } if !match { return nil, nil, cfocsp.ErrNotFound } } src.log.Debugf("Searching for OCSP issued by us for serial %s", serialString) var response dbResponse defer func() { if len(response.OCSPResponse) != 0 { src.log.Debugf("OCSP Response sent for CA=%s, Serial=%s", hex.EncodeToString(src.caKeyHash), serialString) } }() ctx := context.Background() if src.timeout != 0 { var cancel func() ctx, cancel = context.WithTimeout(ctx, src.timeout) defer cancel() } err := src.dbMap.WithContext(ctx).SelectOne( &response, "SELECT ocspResponse, ocspLastUpdated FROM certificateStatus WHERE serial = :serial", map[string]interface{}{"serial": serialString}, ) if err == sql.ErrNoRows { return nil, nil, cfocsp.ErrNotFound } if err != nil { src.log.AuditErrf("Looking up OCSP response: %s", err) return nil, nil, err } if response.OCSPLastUpdated.IsZero() { src.log.Debugf("OCSP Response not sent (ocspLastUpdated is zero) for CA=%s, Serial=%s", hex.EncodeToString(src.caKeyHash), serialString) return nil, nil, cfocsp.ErrNotFound } return response.OCSPResponse, nil, nil }
go
func (src *DBSource) Response(req *ocsp.Request) ([]byte, http.Header, error) { // Check that this request is for the proper CA if bytes.Compare(req.IssuerKeyHash, src.caKeyHash) != 0 { src.log.Debugf("Request intended for CA Cert ID: %s", hex.EncodeToString(req.IssuerKeyHash)) return nil, nil, cfocsp.ErrNotFound } serialString := core.SerialToString(req.SerialNumber) if len(src.reqSerialPrefixes) > 0 { match := false for _, prefix := range src.reqSerialPrefixes { if match = strings.HasPrefix(serialString, prefix); match { break } } if !match { return nil, nil, cfocsp.ErrNotFound } } src.log.Debugf("Searching for OCSP issued by us for serial %s", serialString) var response dbResponse defer func() { if len(response.OCSPResponse) != 0 { src.log.Debugf("OCSP Response sent for CA=%s, Serial=%s", hex.EncodeToString(src.caKeyHash), serialString) } }() ctx := context.Background() if src.timeout != 0 { var cancel func() ctx, cancel = context.WithTimeout(ctx, src.timeout) defer cancel() } err := src.dbMap.WithContext(ctx).SelectOne( &response, "SELECT ocspResponse, ocspLastUpdated FROM certificateStatus WHERE serial = :serial", map[string]interface{}{"serial": serialString}, ) if err == sql.ErrNoRows { return nil, nil, cfocsp.ErrNotFound } if err != nil { src.log.AuditErrf("Looking up OCSP response: %s", err) return nil, nil, err } if response.OCSPLastUpdated.IsZero() { src.log.Debugf("OCSP Response not sent (ocspLastUpdated is zero) for CA=%s, Serial=%s", hex.EncodeToString(src.caKeyHash), serialString) return nil, nil, cfocsp.ErrNotFound } return response.OCSPResponse, nil, nil }
[ "func", "(", "src", "*", "DBSource", ")", "Response", "(", "req", "*", "ocsp", ".", "Request", ")", "(", "[", "]", "byte", ",", "http", ".", "Header", ",", "error", ")", "{", "// Check that this request is for the proper CA", "if", "bytes", ".", "Compare", "(", "req", ".", "IssuerKeyHash", ",", "src", ".", "caKeyHash", ")", "!=", "0", "{", "src", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "hex", ".", "EncodeToString", "(", "req", ".", "IssuerKeyHash", ")", ")", "\n", "return", "nil", ",", "nil", ",", "cfocsp", ".", "ErrNotFound", "\n", "}", "\n\n", "serialString", ":=", "core", ".", "SerialToString", "(", "req", ".", "SerialNumber", ")", "\n", "if", "len", "(", "src", ".", "reqSerialPrefixes", ")", ">", "0", "{", "match", ":=", "false", "\n", "for", "_", ",", "prefix", ":=", "range", "src", ".", "reqSerialPrefixes", "{", "if", "match", "=", "strings", ".", "HasPrefix", "(", "serialString", ",", "prefix", ")", ";", "match", "{", "break", "\n", "}", "\n", "}", "\n", "if", "!", "match", "{", "return", "nil", ",", "nil", ",", "cfocsp", ".", "ErrNotFound", "\n", "}", "\n", "}", "\n\n", "src", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "serialString", ")", "\n\n", "var", "response", "dbResponse", "\n", "defer", "func", "(", ")", "{", "if", "len", "(", "response", ".", "OCSPResponse", ")", "!=", "0", "{", "src", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "hex", ".", "EncodeToString", "(", "src", ".", "caKeyHash", ")", ",", "serialString", ")", "\n", "}", "\n", "}", "(", ")", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "if", "src", ".", "timeout", "!=", "0", "{", "var", "cancel", "func", "(", ")", "\n", "ctx", ",", "cancel", "=", "context", ".", "WithTimeout", "(", "ctx", ",", "src", ".", "timeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "}", "\n", "err", ":=", "src", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", "(", "&", "response", ",", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "serialString", "}", ",", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "nil", ",", "nil", ",", "cfocsp", ".", "ErrNotFound", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "src", ".", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "response", ".", "OCSPLastUpdated", ".", "IsZero", "(", ")", "{", "src", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "hex", ".", "EncodeToString", "(", "src", ".", "caKeyHash", ")", ",", "serialString", ")", "\n", "return", "nil", ",", "nil", ",", "cfocsp", ".", "ErrNotFound", "\n", "}", "\n\n", "return", "response", ".", "OCSPResponse", ",", "nil", ",", "nil", "\n", "}" ]
// Response is called by the HTTP server to handle a new OCSP request.
[ "Response", "is", "called", "by", "the", "HTTP", "server", "to", "handle", "a", "new", "OCSP", "request", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/ocsp-responder/main.go#L110-L162
train
letsencrypt/boulder
bdns/problem.go
Timeout
func (d DNSError) Timeout() bool { if netErr, ok := d.underlying.(*net.OpError); ok { return netErr.Timeout() } else if d.underlying == context.Canceled || d.underlying == context.DeadlineExceeded { return true } return false }
go
func (d DNSError) Timeout() bool { if netErr, ok := d.underlying.(*net.OpError); ok { return netErr.Timeout() } else if d.underlying == context.Canceled || d.underlying == context.DeadlineExceeded { return true } return false }
[ "func", "(", "d", "DNSError", ")", "Timeout", "(", ")", "bool", "{", "if", "netErr", ",", "ok", ":=", "d", ".", "underlying", ".", "(", "*", "net", ".", "OpError", ")", ";", "ok", "{", "return", "netErr", ".", "Timeout", "(", ")", "\n", "}", "else", "if", "d", ".", "underlying", "==", "context", ".", "Canceled", "||", "d", ".", "underlying", "==", "context", ".", "DeadlineExceeded", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Timeout returns true if the underlying error was a timeout
[ "Timeout", "returns", "true", "if", "the", "underlying", "error", "was", "a", "timeout" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/bdns/problem.go#L46-L53
train
letsencrypt/boulder
features/features.go
Set
func Set(featureSet map[string]bool) error { fMu.Lock() defer fMu.Unlock() for n, v := range featureSet { f, present := nameToFeature[n] if !present { return fmt.Errorf("feature '%s' doesn't exist", n) } features[f] = v } return nil }
go
func Set(featureSet map[string]bool) error { fMu.Lock() defer fMu.Unlock() for n, v := range featureSet { f, present := nameToFeature[n] if !present { return fmt.Errorf("feature '%s' doesn't exist", n) } features[f] = v } return nil }
[ "func", "Set", "(", "featureSet", "map", "[", "string", "]", "bool", ")", "error", "{", "fMu", ".", "Lock", "(", ")", "\n", "defer", "fMu", ".", "Unlock", "(", ")", "\n", "for", "n", ",", "v", ":=", "range", "featureSet", "{", "f", ",", "present", ":=", "nameToFeature", "[", "n", "]", "\n", "if", "!", "present", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n", "features", "[", "f", "]", "=", "v", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Set accepts a list of features and whether they should // be enabled or disabled, it will return a error if passed // a feature name that it doesn't know
[ "Set", "accepts", "a", "list", "of", "features", "and", "whether", "they", "should", "be", "enabled", "or", "disabled", "it", "will", "return", "a", "error", "if", "passed", "a", "feature", "name", "that", "it", "doesn", "t", "know" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/features/features.go#L96-L107
train
letsencrypt/boulder
features/features.go
Enabled
func Enabled(n FeatureFlag) bool { fMu.RLock() defer fMu.RUnlock() v, present := features[n] if !present { panic(fmt.Sprintf("feature '%s' doesn't exist", n.String())) } return v }
go
func Enabled(n FeatureFlag) bool { fMu.RLock() defer fMu.RUnlock() v, present := features[n] if !present { panic(fmt.Sprintf("feature '%s' doesn't exist", n.String())) } return v }
[ "func", "Enabled", "(", "n", "FeatureFlag", ")", "bool", "{", "fMu", ".", "RLock", "(", ")", "\n", "defer", "fMu", ".", "RUnlock", "(", ")", "\n", "v", ",", "present", ":=", "features", "[", "n", "]", "\n", "if", "!", "present", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "n", ".", "String", "(", ")", ")", ")", "\n", "}", "\n", "return", "v", "\n", "}" ]
// Enabled returns true if the feature is enabled or false // if it isn't, it will panic if passed a feature that it // doesn't know.
[ "Enabled", "returns", "true", "if", "the", "feature", "is", "enabled", "or", "false", "if", "it", "isn", "t", "it", "will", "panic", "if", "passed", "a", "feature", "that", "it", "doesn", "t", "know", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/features/features.go#L112-L120
train
letsencrypt/boulder
features/features.go
Reset
func Reset() { fMu.Lock() defer fMu.Unlock() for k, v := range initial { features[k] = v } }
go
func Reset() { fMu.Lock() defer fMu.Unlock() for k, v := range initial { features[k] = v } }
[ "func", "Reset", "(", ")", "{", "fMu", ".", "Lock", "(", ")", "\n", "defer", "fMu", ".", "Unlock", "(", ")", "\n", "for", "k", ",", "v", ":=", "range", "initial", "{", "features", "[", "k", "]", "=", "v", "\n", "}", "\n", "}" ]
// Reset resets the features to their initial state
[ "Reset", "resets", "the", "features", "to", "their", "initial", "state" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/features/features.go#L123-L129
train
letsencrypt/boulder
sa/database.go
NewDbMap
func NewDbMap(dbConnect string, maxOpenConns int) (*gorp.DbMap, error) { var err error var config *mysql.Config config, err = mysql.ParseDSN(dbConnect) if err != nil { return nil, err } return NewDbMapFromConfig(config, maxOpenConns) }
go
func NewDbMap(dbConnect string, maxOpenConns int) (*gorp.DbMap, error) { var err error var config *mysql.Config config, err = mysql.ParseDSN(dbConnect) if err != nil { return nil, err } return NewDbMapFromConfig(config, maxOpenConns) }
[ "func", "NewDbMap", "(", "dbConnect", "string", ",", "maxOpenConns", "int", ")", "(", "*", "gorp", ".", "DbMap", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "config", "*", "mysql", ".", "Config", "\n\n", "config", ",", "err", "=", "mysql", ".", "ParseDSN", "(", "dbConnect", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "NewDbMapFromConfig", "(", "config", ",", "maxOpenConns", ")", "\n", "}" ]
// NewDbMap creates the root gorp mapping object. Create one of these for each // database schema you wish to map. Each DbMap contains a list of mapped // tables. It automatically maps the tables for the primary parts of Boulder // around the Storage Authority.
[ "NewDbMap", "creates", "the", "root", "gorp", "mapping", "object", ".", "Create", "one", "of", "these", "for", "each", "database", "schema", "you", "wish", "to", "map", ".", "Each", "DbMap", "contains", "a", "list", "of", "mapped", "tables", ".", "It", "automatically", "maps", "the", "tables", "for", "the", "primary", "parts", "of", "Boulder", "around", "the", "Storage", "Authority", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/database.go#L18-L28
train
letsencrypt/boulder
sa/database.go
adjustMySQLConfig
func adjustMySQLConfig(conf *mysql.Config) *mysql.Config { // Required to turn DATETIME fields into time.Time conf.ParseTime = true // Required to make UPDATE return the number of rows matched, // instead of the number of rows changed by the UPDATE. conf.ClientFoundRows = true // Ensures that MySQL/MariaDB warnings are treated as errors. This // avoids a number of nasty edge conditions we could wander into. // Common things this discovers includes places where data being sent // had a different type than what is in the schema, strings being // truncated, writing null to a NOT NULL column, and so on. See // <https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sql-mode-strict>. conf.Params = make(map[string]string) conf.Params["sql_mode"] = "STRICT_ALL_TABLES" // If a read timeout is set, we set max_statement_time to 95% of that, and // long_query_time to 80% of that. That way we get logs of queries that are // close to timing out but not yet doing so, and our queries get stopped by // max_statement_time before timing out the read. This generates clearer // errors, and avoids unnecessary reconnects. if conf.ReadTimeout != 0 { // In MariaDB, max_statement_time and long_query_time are both seconds. // Note: in MySQL (which we don't use), max_statement_time is millis. readTimeout := conf.ReadTimeout.Seconds() conf.Params["max_statement_time"] = fmt.Sprintf("%g", readTimeout*0.95) conf.Params["long_query_time"] = fmt.Sprintf("%g", readTimeout*0.80) } return conf }
go
func adjustMySQLConfig(conf *mysql.Config) *mysql.Config { // Required to turn DATETIME fields into time.Time conf.ParseTime = true // Required to make UPDATE return the number of rows matched, // instead of the number of rows changed by the UPDATE. conf.ClientFoundRows = true // Ensures that MySQL/MariaDB warnings are treated as errors. This // avoids a number of nasty edge conditions we could wander into. // Common things this discovers includes places where data being sent // had a different type than what is in the schema, strings being // truncated, writing null to a NOT NULL column, and so on. See // <https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sql-mode-strict>. conf.Params = make(map[string]string) conf.Params["sql_mode"] = "STRICT_ALL_TABLES" // If a read timeout is set, we set max_statement_time to 95% of that, and // long_query_time to 80% of that. That way we get logs of queries that are // close to timing out but not yet doing so, and our queries get stopped by // max_statement_time before timing out the read. This generates clearer // errors, and avoids unnecessary reconnects. if conf.ReadTimeout != 0 { // In MariaDB, max_statement_time and long_query_time are both seconds. // Note: in MySQL (which we don't use), max_statement_time is millis. readTimeout := conf.ReadTimeout.Seconds() conf.Params["max_statement_time"] = fmt.Sprintf("%g", readTimeout*0.95) conf.Params["long_query_time"] = fmt.Sprintf("%g", readTimeout*0.80) } return conf }
[ "func", "adjustMySQLConfig", "(", "conf", "*", "mysql", ".", "Config", ")", "*", "mysql", ".", "Config", "{", "// Required to turn DATETIME fields into time.Time", "conf", ".", "ParseTime", "=", "true", "\n\n", "// Required to make UPDATE return the number of rows matched,", "// instead of the number of rows changed by the UPDATE.", "conf", ".", "ClientFoundRows", "=", "true", "\n\n", "// Ensures that MySQL/MariaDB warnings are treated as errors. This", "// avoids a number of nasty edge conditions we could wander into.", "// Common things this discovers includes places where data being sent", "// had a different type than what is in the schema, strings being", "// truncated, writing null to a NOT NULL column, and so on. See", "// <https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sql-mode-strict>.", "conf", ".", "Params", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "conf", ".", "Params", "[", "\"", "\"", "]", "=", "\"", "\"", "\n\n", "// If a read timeout is set, we set max_statement_time to 95% of that, and", "// long_query_time to 80% of that. That way we get logs of queries that are", "// close to timing out but not yet doing so, and our queries get stopped by", "// max_statement_time before timing out the read. This generates clearer", "// errors, and avoids unnecessary reconnects.", "if", "conf", ".", "ReadTimeout", "!=", "0", "{", "// In MariaDB, max_statement_time and long_query_time are both seconds.", "// Note: in MySQL (which we don't use), max_statement_time is millis.", "readTimeout", ":=", "conf", ".", "ReadTimeout", ".", "Seconds", "(", ")", "\n", "conf", ".", "Params", "[", "\"", "\"", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "readTimeout", "*", "0.95", ")", "\n", "conf", ".", "Params", "[", "\"", "\"", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "readTimeout", "*", "0.80", ")", "\n", "}", "\n\n", "return", "conf", "\n", "}" ]
// adjustMySQLConfig sets certain flags that we want on every connection.
[ "adjustMySQLConfig", "sets", "certain", "flags", "that", "we", "want", "on", "every", "connection", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/database.go#L64-L95
train
letsencrypt/boulder
sa/database.go
SetSQLDebug
func SetSQLDebug(dbMap *gorp.DbMap, log blog.Logger) { dbMap.TraceOn("SQL: ", &SQLLogger{log}) }
go
func SetSQLDebug(dbMap *gorp.DbMap, log blog.Logger) { dbMap.TraceOn("SQL: ", &SQLLogger{log}) }
[ "func", "SetSQLDebug", "(", "dbMap", "*", "gorp", ".", "DbMap", ",", "log", "blog", ".", "Logger", ")", "{", "dbMap", ".", "TraceOn", "(", "\"", "\"", ",", "&", "SQLLogger", "{", "log", "}", ")", "\n", "}" ]
// SetSQLDebug enables GORP SQL-level Debugging
[ "SetSQLDebug", "enables", "GORP", "SQL", "-", "level", "Debugging" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/database.go#L98-L100
train
letsencrypt/boulder
sa/database.go
Printf
func (log *SQLLogger) Printf(format string, v ...interface{}) { log.Debugf(format, v...) }
go
func (log *SQLLogger) Printf(format string, v ...interface{}) { log.Debugf(format, v...) }
[ "func", "(", "log", "*", "SQLLogger", ")", "Printf", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "log", ".", "Debugf", "(", "format", ",", "v", "...", ")", "\n", "}" ]
// Printf adapts the AuditLogger to GORP's interface
[ "Printf", "adapts", "the", "AuditLogger", "to", "GORP", "s", "interface" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/database.go#L108-L110
train
letsencrypt/boulder
bdns/mocks.go
LookupTXT
func (mock *MockDNSClient) LookupTXT(_ context.Context, hostname string) ([]string, []string, error) { if hostname == "_acme-challenge.servfail.com" { return nil, nil, fmt.Errorf("SERVFAIL") } if hostname == "_acme-challenge.good-dns01.com" { // base64(sha256("LoqXcYV8q5ONbJQxbmR7SCTNo3tiAXDfowyjxAjEuX0" // + "." + "9jg46WB3rR_AHD-EBXdN7cBkH1WOu0tA3M9fm21mqTI")) // expected token + test account jwk thumbprint return []string{"LPsIwTo7o8BoG0-vjCyGQGBWSVIPxI-i_X336eUOQZo"}, []string{"respect my authority!"}, nil } if hostname == "_acme-challenge.wrong-dns01.com" { return []string{"a"}, []string{"respect my authority!"}, nil } if hostname == "_acme-challenge.wrong-many-dns01.com" { return []string{"a", "b", "c", "d", "e"}, []string{"respect my authority!"}, nil } if hostname == "_acme-challenge.long-dns01.com" { return []string{"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, []string{"respect my authority!"}, nil } if hostname == "_acme-challenge.no-authority-dns01.com" { // base64(sha256("LoqXcYV8q5ONbJQxbmR7SCTNo3tiAXDfowyjxAjEuX0" // + "." + "9jg46WB3rR_AHD-EBXdN7cBkH1WOu0tA3M9fm21mqTI")) // expected token + test account jwk thumbprint return []string{"LPsIwTo7o8BoG0-vjCyGQGBWSVIPxI-i_X336eUOQZo"}, nil, nil } // empty-txts.com always returns zero TXT records if hostname == "_acme-challenge.empty-txts.com" { return []string{}, nil, nil } return []string{"hostname"}, []string{"respect my authority!"}, nil }
go
func (mock *MockDNSClient) LookupTXT(_ context.Context, hostname string) ([]string, []string, error) { if hostname == "_acme-challenge.servfail.com" { return nil, nil, fmt.Errorf("SERVFAIL") } if hostname == "_acme-challenge.good-dns01.com" { // base64(sha256("LoqXcYV8q5ONbJQxbmR7SCTNo3tiAXDfowyjxAjEuX0" // + "." + "9jg46WB3rR_AHD-EBXdN7cBkH1WOu0tA3M9fm21mqTI")) // expected token + test account jwk thumbprint return []string{"LPsIwTo7o8BoG0-vjCyGQGBWSVIPxI-i_X336eUOQZo"}, []string{"respect my authority!"}, nil } if hostname == "_acme-challenge.wrong-dns01.com" { return []string{"a"}, []string{"respect my authority!"}, nil } if hostname == "_acme-challenge.wrong-many-dns01.com" { return []string{"a", "b", "c", "d", "e"}, []string{"respect my authority!"}, nil } if hostname == "_acme-challenge.long-dns01.com" { return []string{"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, []string{"respect my authority!"}, nil } if hostname == "_acme-challenge.no-authority-dns01.com" { // base64(sha256("LoqXcYV8q5ONbJQxbmR7SCTNo3tiAXDfowyjxAjEuX0" // + "." + "9jg46WB3rR_AHD-EBXdN7cBkH1WOu0tA3M9fm21mqTI")) // expected token + test account jwk thumbprint return []string{"LPsIwTo7o8BoG0-vjCyGQGBWSVIPxI-i_X336eUOQZo"}, nil, nil } // empty-txts.com always returns zero TXT records if hostname == "_acme-challenge.empty-txts.com" { return []string{}, nil, nil } return []string{"hostname"}, []string{"respect my authority!"}, nil }
[ "func", "(", "mock", "*", "MockDNSClient", ")", "LookupTXT", "(", "_", "context", ".", "Context", ",", "hostname", "string", ")", "(", "[", "]", "string", ",", "[", "]", "string", ",", "error", ")", "{", "if", "hostname", "==", "\"", "\"", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "hostname", "==", "\"", "\"", "{", "// base64(sha256(\"LoqXcYV8q5ONbJQxbmR7SCTNo3tiAXDfowyjxAjEuX0\"", "// + \".\" + \"9jg46WB3rR_AHD-EBXdN7cBkH1WOu0tA3M9fm21mqTI\"))", "// expected token + test account jwk thumbprint", "return", "[", "]", "string", "{", "\"", "\"", "}", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "nil", "\n", "}", "\n", "if", "hostname", "==", "\"", "\"", "{", "return", "[", "]", "string", "{", "\"", "\"", "}", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "nil", "\n", "}", "\n", "if", "hostname", "==", "\"", "\"", "{", "return", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "nil", "\n", "}", "\n", "if", "hostname", "==", "\"", "\"", "{", "return", "[", "]", "string", "{", "\"", "\"", "}", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "nil", "\n", "}", "\n", "if", "hostname", "==", "\"", "\"", "{", "// base64(sha256(\"LoqXcYV8q5ONbJQxbmR7SCTNo3tiAXDfowyjxAjEuX0\"", "// + \".\" + \"9jg46WB3rR_AHD-EBXdN7cBkH1WOu0tA3M9fm21mqTI\"))", "// expected token + test account jwk thumbprint", "return", "[", "]", "string", "{", "\"", "\"", "}", ",", "nil", ",", "nil", "\n", "}", "\n", "// empty-txts.com always returns zero TXT records", "if", "hostname", "==", "\"", "\"", "{", "return", "[", "]", "string", "{", "}", ",", "nil", ",", "nil", "\n", "}", "\n", "return", "[", "]", "string", "{", "\"", "\"", "}", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "nil", "\n", "}" ]
// LookupTXT is a mock
[ "LookupTXT", "is", "a", "mock" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/bdns/mocks.go#L19-L49
train
letsencrypt/boulder
bdns/mocks.go
LookupCAA
func (mock *MockDNSClient) LookupCAA(_ context.Context, domain string) ([]*dns.CAA, error) { return nil, nil }
go
func (mock *MockDNSClient) LookupCAA(_ context.Context, domain string) ([]*dns.CAA, error) { return nil, nil }
[ "func", "(", "mock", "*", "MockDNSClient", ")", "LookupCAA", "(", "_", "context", ".", "Context", ",", "domain", "string", ")", "(", "[", "]", "*", "dns", ".", "CAA", ",", "error", ")", "{", "return", "nil", ",", "nil", "\n", "}" ]
// LookupCAA returns mock records for use in tests.
[ "LookupCAA", "returns", "mock", "records", "for", "use", "in", "tests", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/bdns/mocks.go#L102-L104
train
letsencrypt/boulder
sa/type-converter.go
ToDb
func (tc BoulderTypeConverter) ToDb(val interface{}) (interface{}, error) { switch t := val.(type) { case core.AcmeIdentifier, []core.Challenge, []string, [][]int: jsonBytes, err := json.Marshal(t) if err != nil { return nil, err } return string(jsonBytes), nil case jose.JSONWebKey: jsonBytes, err := t.MarshalJSON() if err != nil { return "", err } return string(jsonBytes), nil case core.AcmeStatus: return string(t), nil case core.OCSPStatus: return string(t), nil default: return val, nil } }
go
func (tc BoulderTypeConverter) ToDb(val interface{}) (interface{}, error) { switch t := val.(type) { case core.AcmeIdentifier, []core.Challenge, []string, [][]int: jsonBytes, err := json.Marshal(t) if err != nil { return nil, err } return string(jsonBytes), nil case jose.JSONWebKey: jsonBytes, err := t.MarshalJSON() if err != nil { return "", err } return string(jsonBytes), nil case core.AcmeStatus: return string(t), nil case core.OCSPStatus: return string(t), nil default: return val, nil } }
[ "func", "(", "tc", "BoulderTypeConverter", ")", "ToDb", "(", "val", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "switch", "t", ":=", "val", ".", "(", "type", ")", "{", "case", "core", ".", "AcmeIdentifier", ",", "[", "]", "core", ".", "Challenge", ",", "[", "]", "string", ",", "[", "]", "[", "]", "int", ":", "jsonBytes", ",", "err", ":=", "json", ".", "Marshal", "(", "t", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "string", "(", "jsonBytes", ")", ",", "nil", "\n", "case", "jose", ".", "JSONWebKey", ":", "jsonBytes", ",", "err", ":=", "t", ".", "MarshalJSON", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "jsonBytes", ")", ",", "nil", "\n", "case", "core", ".", "AcmeStatus", ":", "return", "string", "(", "t", ")", ",", "nil", "\n", "case", "core", ".", "OCSPStatus", ":", "return", "string", "(", "t", ")", ",", "nil", "\n", "default", ":", "return", "val", ",", "nil", "\n", "}", "\n", "}" ]
// ToDb converts a Boulder object to one suitable for the DB representation.
[ "ToDb", "converts", "a", "Boulder", "object", "to", "one", "suitable", "for", "the", "DB", "representation", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/type-converter.go#L18-L39
train
letsencrypt/boulder
metrics/scope.go
NewPromScope
func NewPromScope(registerer prometheus.Registerer, scopes ...string) Scope { return &promScope{ prefix: scopes, autoRegisterer: newAutoRegisterer(registerer), registerer: registerer, } }
go
func NewPromScope(registerer prometheus.Registerer, scopes ...string) Scope { return &promScope{ prefix: scopes, autoRegisterer: newAutoRegisterer(registerer), registerer: registerer, } }
[ "func", "NewPromScope", "(", "registerer", "prometheus", ".", "Registerer", ",", "scopes", "...", "string", ")", "Scope", "{", "return", "&", "promScope", "{", "prefix", ":", "scopes", ",", "autoRegisterer", ":", "newAutoRegisterer", "(", "registerer", ")", ",", "registerer", ":", "registerer", ",", "}", "\n", "}" ]
// NewPromScope returns a Scope that sends data to Prometheus
[ "NewPromScope", "returns", "a", "Scope", "that", "sends", "data", "to", "Prometheus" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/scope.go#L39-L45
train
letsencrypt/boulder
metrics/scope.go
NewScope
func (s *promScope) NewScope(scopes ...string) Scope { return &promScope{ prefix: append(s.prefix, scopes...), autoRegisterer: s.autoRegisterer, registerer: s.registerer, } }
go
func (s *promScope) NewScope(scopes ...string) Scope { return &promScope{ prefix: append(s.prefix, scopes...), autoRegisterer: s.autoRegisterer, registerer: s.registerer, } }
[ "func", "(", "s", "*", "promScope", ")", "NewScope", "(", "scopes", "...", "string", ")", "Scope", "{", "return", "&", "promScope", "{", "prefix", ":", "append", "(", "s", ".", "prefix", ",", "scopes", "...", ")", ",", "autoRegisterer", ":", "s", ".", "autoRegisterer", ",", "registerer", ":", "s", ".", "registerer", ",", "}", "\n", "}" ]
// NewScope generates a new Scope prefixed by this Scope's prefix plus the // prefixes given joined by periods
[ "NewScope", "generates", "a", "new", "Scope", "prefixed", "by", "this", "Scope", "s", "prefix", "plus", "the", "prefixes", "given", "joined", "by", "periods" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/scope.go#L53-L59
train
letsencrypt/boulder
metrics/scope.go
Inc
func (s *promScope) Inc(stat string, value int64) { s.autoCounter(s.statName(stat)).Add(float64(value)) }
go
func (s *promScope) Inc(stat string, value int64) { s.autoCounter(s.statName(stat)).Add(float64(value)) }
[ "func", "(", "s", "*", "promScope", ")", "Inc", "(", "stat", "string", ",", "value", "int64", ")", "{", "s", ".", "autoCounter", "(", "s", ".", "statName", "(", "stat", ")", ")", ".", "Add", "(", "float64", "(", "value", ")", ")", "\n", "}" ]
// Inc increments the given stat and adds the Scope's prefix to the name
[ "Inc", "increments", "the", "given", "stat", "and", "adds", "the", "Scope", "s", "prefix", "to", "the", "name" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/scope.go#L62-L64
train
letsencrypt/boulder
metrics/scope.go
GaugeDelta
func (s *promScope) GaugeDelta(stat string, value int64) { s.autoGauge(s.statName(stat)).Add(float64(value)) }
go
func (s *promScope) GaugeDelta(stat string, value int64) { s.autoGauge(s.statName(stat)).Add(float64(value)) }
[ "func", "(", "s", "*", "promScope", ")", "GaugeDelta", "(", "stat", "string", ",", "value", "int64", ")", "{", "s", ".", "autoGauge", "(", "s", ".", "statName", "(", "stat", ")", ")", ".", "Add", "(", "float64", "(", "value", ")", ")", "\n", "}" ]
// GaugeDelta sends the change in a gauge stat and adds the Scope's prefix to the name
[ "GaugeDelta", "sends", "the", "change", "in", "a", "gauge", "stat", "and", "adds", "the", "Scope", "s", "prefix", "to", "the", "name" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/scope.go#L72-L74
train
letsencrypt/boulder
metrics/scope.go
Timing
func (s *promScope) Timing(stat string, delta int64) { s.autoSummary(s.statName(stat) + "_seconds").Observe(float64(delta)) }
go
func (s *promScope) Timing(stat string, delta int64) { s.autoSummary(s.statName(stat) + "_seconds").Observe(float64(delta)) }
[ "func", "(", "s", "*", "promScope", ")", "Timing", "(", "stat", "string", ",", "delta", "int64", ")", "{", "s", ".", "autoSummary", "(", "s", ".", "statName", "(", "stat", ")", "+", "\"", "\"", ")", ".", "Observe", "(", "float64", "(", "delta", ")", ")", "\n", "}" ]
// Timing sends a latency stat and adds the Scope's prefix to the name
[ "Timing", "sends", "a", "latency", "stat", "and", "adds", "the", "Scope", "s", "prefix", "to", "the", "name" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/scope.go#L77-L79
train
letsencrypt/boulder
metrics/scope.go
TimingDuration
func (s *promScope) TimingDuration(stat string, delta time.Duration) { s.autoSummary(s.statName(stat) + "_seconds").Observe(delta.Seconds()) }
go
func (s *promScope) TimingDuration(stat string, delta time.Duration) { s.autoSummary(s.statName(stat) + "_seconds").Observe(delta.Seconds()) }
[ "func", "(", "s", "*", "promScope", ")", "TimingDuration", "(", "stat", "string", ",", "delta", "time", ".", "Duration", ")", "{", "s", ".", "autoSummary", "(", "s", ".", "statName", "(", "stat", ")", "+", "\"", "\"", ")", ".", "Observe", "(", "delta", ".", "Seconds", "(", ")", ")", "\n", "}" ]
// TimingDuration sends a latency stat as a time.Duration and adds the Scope's // prefix to the name
[ "TimingDuration", "sends", "a", "latency", "stat", "as", "a", "time", ".", "Duration", "and", "adds", "the", "Scope", "s", "prefix", "to", "the", "name" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/scope.go#L83-L85
train
letsencrypt/boulder
metrics/scope.go
SetInt
func (s *promScope) SetInt(stat string, value int64) { s.autoGauge(s.statName(stat)).Set(float64(value)) }
go
func (s *promScope) SetInt(stat string, value int64) { s.autoGauge(s.statName(stat)).Set(float64(value)) }
[ "func", "(", "s", "*", "promScope", ")", "SetInt", "(", "stat", "string", ",", "value", "int64", ")", "{", "s", ".", "autoGauge", "(", "s", ".", "statName", "(", "stat", ")", ")", ".", "Set", "(", "float64", "(", "value", ")", ")", "\n", "}" ]
// SetInt sets a stat's integer value and adds the Scope's prefix to the name
[ "SetInt", "sets", "a", "stat", "s", "integer", "value", "and", "adds", "the", "Scope", "s", "prefix", "to", "the", "name" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/scope.go#L88-L90
train
letsencrypt/boulder
metrics/scope.go
statName
func (s *promScope) statName(stat string) string { if len(s.prefix) > 0 { return strings.Join(s.prefix, "_") + "_" + stat } return stat }
go
func (s *promScope) statName(stat string) string { if len(s.prefix) > 0 { return strings.Join(s.prefix, "_") + "_" + stat } return stat }
[ "func", "(", "s", "*", "promScope", ")", "statName", "(", "stat", "string", ")", "string", "{", "if", "len", "(", "s", ".", "prefix", ")", ">", "0", "{", "return", "strings", ".", "Join", "(", "s", ".", "prefix", ",", "\"", "\"", ")", "+", "\"", "\"", "+", "stat", "\n", "}", "\n", "return", "stat", "\n", "}" ]
// statName construct a name for a stat based on the prefix of this scope, plus // the provided string.
[ "statName", "construct", "a", "name", "for", "a", "stat", "based", "on", "the", "prefix", "of", "this", "scope", "plus", "the", "provided", "string", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/scope.go#L94-L99
train
letsencrypt/boulder
akamai/cache-client.go
NewCachePurgeClient
func NewCachePurgeClient( endpoint, clientToken, clientSecret, accessToken string, v3Network string, retries int, retryBackoff time.Duration, log blog.Logger, stats metrics.Scope, ) (*CachePurgeClient, error) { stats = stats.NewScope("CCU") if strings.HasSuffix(endpoint, "/") { endpoint = endpoint[:len(endpoint)-1] } apiURL, err := url.Parse(endpoint) if err != nil { return nil, err } // The network string must be either "production" or "staging". if v3Network != "production" && v3Network != "staging" { return nil, fmt.Errorf( "Invalid CCU v3 network: %q. Must be \"staging\" or \"production\"", v3Network) } return &CachePurgeClient{ client: new(http.Client), apiEndpoint: endpoint, apiHost: apiURL.Host, apiScheme: strings.ToLower(apiURL.Scheme), clientToken: clientToken, clientSecret: clientSecret, accessToken: accessToken, v3Network: v3Network, retries: retries, retryBackoff: retryBackoff, log: log, stats: stats, clk: clock.Default(), }, nil }
go
func NewCachePurgeClient( endpoint, clientToken, clientSecret, accessToken string, v3Network string, retries int, retryBackoff time.Duration, log blog.Logger, stats metrics.Scope, ) (*CachePurgeClient, error) { stats = stats.NewScope("CCU") if strings.HasSuffix(endpoint, "/") { endpoint = endpoint[:len(endpoint)-1] } apiURL, err := url.Parse(endpoint) if err != nil { return nil, err } // The network string must be either "production" or "staging". if v3Network != "production" && v3Network != "staging" { return nil, fmt.Errorf( "Invalid CCU v3 network: %q. Must be \"staging\" or \"production\"", v3Network) } return &CachePurgeClient{ client: new(http.Client), apiEndpoint: endpoint, apiHost: apiURL.Host, apiScheme: strings.ToLower(apiURL.Scheme), clientToken: clientToken, clientSecret: clientSecret, accessToken: accessToken, v3Network: v3Network, retries: retries, retryBackoff: retryBackoff, log: log, stats: stats, clk: clock.Default(), }, nil }
[ "func", "NewCachePurgeClient", "(", "endpoint", ",", "clientToken", ",", "clientSecret", ",", "accessToken", "string", ",", "v3Network", "string", ",", "retries", "int", ",", "retryBackoff", "time", ".", "Duration", ",", "log", "blog", ".", "Logger", ",", "stats", "metrics", ".", "Scope", ",", ")", "(", "*", "CachePurgeClient", ",", "error", ")", "{", "stats", "=", "stats", ".", "NewScope", "(", "\"", "\"", ")", "\n", "if", "strings", ".", "HasSuffix", "(", "endpoint", ",", "\"", "\"", ")", "{", "endpoint", "=", "endpoint", "[", ":", "len", "(", "endpoint", ")", "-", "1", "]", "\n", "}", "\n", "apiURL", ",", "err", ":=", "url", ".", "Parse", "(", "endpoint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// The network string must be either \"production\" or \"staging\".", "if", "v3Network", "!=", "\"", "\"", "&&", "v3Network", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "v3Network", ")", "\n", "}", "\n", "return", "&", "CachePurgeClient", "{", "client", ":", "new", "(", "http", ".", "Client", ")", ",", "apiEndpoint", ":", "endpoint", ",", "apiHost", ":", "apiURL", ".", "Host", ",", "apiScheme", ":", "strings", ".", "ToLower", "(", "apiURL", ".", "Scheme", ")", ",", "clientToken", ":", "clientToken", ",", "clientSecret", ":", "clientSecret", ",", "accessToken", ":", "accessToken", ",", "v3Network", ":", "v3Network", ",", "retries", ":", "retries", ",", "retryBackoff", ":", "retryBackoff", ",", "log", ":", "log", ",", "stats", ":", "stats", ",", "clk", ":", "clock", ".", "Default", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewCachePurgeClient constructs a new CachePurgeClient
[ "NewCachePurgeClient", "constructs", "a", "new", "CachePurgeClient" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/akamai/cache-client.go#L73-L112
train
letsencrypt/boulder
akamai/cache-client.go
signingKey
func signingKey(clientSecret string, timestamp string) []byte { h := hmac.New(sha256.New, []byte(clientSecret)) h.Write([]byte(timestamp)) key := make([]byte, base64.StdEncoding.EncodedLen(32)) base64.StdEncoding.Encode(key, h.Sum(nil)) return key }
go
func signingKey(clientSecret string, timestamp string) []byte { h := hmac.New(sha256.New, []byte(clientSecret)) h.Write([]byte(timestamp)) key := make([]byte, base64.StdEncoding.EncodedLen(32)) base64.StdEncoding.Encode(key, h.Sum(nil)) return key }
[ "func", "signingKey", "(", "clientSecret", "string", ",", "timestamp", "string", ")", "[", "]", "byte", "{", "h", ":=", "hmac", ".", "New", "(", "sha256", ".", "New", ",", "[", "]", "byte", "(", "clientSecret", ")", ")", "\n", "h", ".", "Write", "(", "[", "]", "byte", "(", "timestamp", ")", ")", "\n", "key", ":=", "make", "(", "[", "]", "byte", ",", "base64", ".", "StdEncoding", ".", "EncodedLen", "(", "32", ")", ")", "\n", "base64", ".", "StdEncoding", ".", "Encode", "(", "key", ",", "h", ".", "Sum", "(", "nil", ")", ")", "\n", "return", "key", "\n", "}" ]
// signingKey makes a signing key by HMAC'ing the timestamp // using a client secret as the key.
[ "signingKey", "makes", "a", "signing", "key", "by", "HMAC", "ing", "the", "timestamp", "using", "a", "client", "secret", "as", "the", "key", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/akamai/cache-client.go#L154-L160
train
letsencrypt/boulder
akamai/cache-client.go
purge
func (cpc *CachePurgeClient) purge(urls []string) error { purgeReq := v3PurgeRequest{ Objects: urls, } endpoint := fmt.Sprintf("%s%s%s", cpc.apiEndpoint, v3PurgePath, cpc.v3Network) reqJSON, err := json.Marshal(purgeReq) if err != nil { return errFatal(err.Error()) } req, err := http.NewRequest( "POST", endpoint, bytes.NewBuffer(reqJSON), ) if err != nil { return errFatal(err.Error()) } // Create authorization header for request authHeader, err := cpc.constructAuthHeader( reqJSON, v3PurgePath+cpc.v3Network, core.RandomString(16), ) if err != nil { return errFatal(err.Error()) } req.Header.Set("Authorization", authHeader) req.Header.Set("Content-Type", "application/json") cpc.log.Debugf("POSTing to %s with Authorization %s: %s", endpoint, authHeader, reqJSON) rS := cpc.clk.Now() resp, err := cpc.client.Do(req) cpc.stats.TimingDuration("PurgeRequestLatency", time.Since(rS)) if err != nil { return err } if resp.Body == nil { return fmt.Errorf("No response body") } body, err := ioutil.ReadAll(resp.Body) if err != nil { _ = resp.Body.Close() return err } err = resp.Body.Close() if err != nil { return err } // Check purge was successful var purgeInfo purgeResponse err = json.Unmarshal(body, &purgeInfo) if err != nil { return fmt.Errorf("%s. Body was: %s", err, body) } if purgeInfo.HTTPStatus != http.StatusCreated || resp.StatusCode != http.StatusCreated { if purgeInfo.HTTPStatus == http.StatusForbidden { return errFatal(fmt.Sprintf("Unauthorized to purge URLs %q", urls)) } return fmt.Errorf("Unexpected HTTP status code '%d': %s", resp.StatusCode, string(body)) } cpc.log.Infof("Sent successful purge request purgeID: %s, purge expected in: %ds, for URLs: %s", purgeInfo.PurgeID, purgeInfo.EstimatedSeconds, urls) return nil }
go
func (cpc *CachePurgeClient) purge(urls []string) error { purgeReq := v3PurgeRequest{ Objects: urls, } endpoint := fmt.Sprintf("%s%s%s", cpc.apiEndpoint, v3PurgePath, cpc.v3Network) reqJSON, err := json.Marshal(purgeReq) if err != nil { return errFatal(err.Error()) } req, err := http.NewRequest( "POST", endpoint, bytes.NewBuffer(reqJSON), ) if err != nil { return errFatal(err.Error()) } // Create authorization header for request authHeader, err := cpc.constructAuthHeader( reqJSON, v3PurgePath+cpc.v3Network, core.RandomString(16), ) if err != nil { return errFatal(err.Error()) } req.Header.Set("Authorization", authHeader) req.Header.Set("Content-Type", "application/json") cpc.log.Debugf("POSTing to %s with Authorization %s: %s", endpoint, authHeader, reqJSON) rS := cpc.clk.Now() resp, err := cpc.client.Do(req) cpc.stats.TimingDuration("PurgeRequestLatency", time.Since(rS)) if err != nil { return err } if resp.Body == nil { return fmt.Errorf("No response body") } body, err := ioutil.ReadAll(resp.Body) if err != nil { _ = resp.Body.Close() return err } err = resp.Body.Close() if err != nil { return err } // Check purge was successful var purgeInfo purgeResponse err = json.Unmarshal(body, &purgeInfo) if err != nil { return fmt.Errorf("%s. Body was: %s", err, body) } if purgeInfo.HTTPStatus != http.StatusCreated || resp.StatusCode != http.StatusCreated { if purgeInfo.HTTPStatus == http.StatusForbidden { return errFatal(fmt.Sprintf("Unauthorized to purge URLs %q", urls)) } return fmt.Errorf("Unexpected HTTP status code '%d': %s", resp.StatusCode, string(body)) } cpc.log.Infof("Sent successful purge request purgeID: %s, purge expected in: %ds, for URLs: %s", purgeInfo.PurgeID, purgeInfo.EstimatedSeconds, urls) return nil }
[ "func", "(", "cpc", "*", "CachePurgeClient", ")", "purge", "(", "urls", "[", "]", "string", ")", "error", "{", "purgeReq", ":=", "v3PurgeRequest", "{", "Objects", ":", "urls", ",", "}", "\n", "endpoint", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cpc", ".", "apiEndpoint", ",", "v3PurgePath", ",", "cpc", ".", "v3Network", ")", "\n\n", "reqJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "purgeReq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errFatal", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "endpoint", ",", "bytes", ".", "NewBuffer", "(", "reqJSON", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errFatal", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "// Create authorization header for request", "authHeader", ",", "err", ":=", "cpc", ".", "constructAuthHeader", "(", "reqJSON", ",", "v3PurgePath", "+", "cpc", ".", "v3Network", ",", "core", ".", "RandomString", "(", "16", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errFatal", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "authHeader", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "cpc", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "endpoint", ",", "authHeader", ",", "reqJSON", ")", "\n\n", "rS", ":=", "cpc", ".", "clk", ".", "Now", "(", ")", "\n", "resp", ",", "err", ":=", "cpc", ".", "client", ".", "Do", "(", "req", ")", "\n", "cpc", ".", "stats", ".", "TimingDuration", "(", "\"", "\"", ",", "time", ".", "Since", "(", "rS", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "resp", ".", "Body", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "_", "=", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}", "\n", "err", "=", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check purge was successful", "var", "purgeInfo", "purgeResponse", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "purgeInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "body", ")", "\n", "}", "\n", "if", "purgeInfo", ".", "HTTPStatus", "!=", "http", ".", "StatusCreated", "||", "resp", ".", "StatusCode", "!=", "http", ".", "StatusCreated", "{", "if", "purgeInfo", ".", "HTTPStatus", "==", "http", ".", "StatusForbidden", "{", "return", "errFatal", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "urls", ")", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resp", ".", "StatusCode", ",", "string", "(", "body", ")", ")", "\n", "}", "\n\n", "cpc", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "purgeInfo", ".", "PurgeID", ",", "purgeInfo", ".", "EstimatedSeconds", ",", "urls", ")", "\n\n", "return", "nil", "\n", "}" ]
// purge actually sends the individual requests to the Akamai endpoint and checks // if they are successful
[ "purge", "actually", "sends", "the", "individual", "requests", "to", "the", "Akamai", "endpoint", "and", "checks", "if", "they", "are", "successful" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/akamai/cache-client.go#L164-L234
train
letsencrypt/boulder
akamai/cache-client.go
Purge
func (cpc *CachePurgeClient) Purge(urls []string) error { for i := 0; i < len(urls); { sliceEnd := i + akamaiBatchSize if sliceEnd > len(urls) { sliceEnd = len(urls) } err := cpc.purgeBatch(urls[i:sliceEnd]) if err != nil { return err } i += akamaiBatchSize } return nil }
go
func (cpc *CachePurgeClient) Purge(urls []string) error { for i := 0; i < len(urls); { sliceEnd := i + akamaiBatchSize if sliceEnd > len(urls) { sliceEnd = len(urls) } err := cpc.purgeBatch(urls[i:sliceEnd]) if err != nil { return err } i += akamaiBatchSize } return nil }
[ "func", "(", "cpc", "*", "CachePurgeClient", ")", "Purge", "(", "urls", "[", "]", "string", ")", "error", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "urls", ")", ";", "{", "sliceEnd", ":=", "i", "+", "akamaiBatchSize", "\n", "if", "sliceEnd", ">", "len", "(", "urls", ")", "{", "sliceEnd", "=", "len", "(", "urls", ")", "\n", "}", "\n", "err", ":=", "cpc", ".", "purgeBatch", "(", "urls", "[", "i", ":", "sliceEnd", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "i", "+=", "akamaiBatchSize", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Purge attempts to send a purge request to the Akamai CCU API cpc.retries number // of times before giving up and returning ErrAllRetriesFailed
[ "Purge", "attempts", "to", "send", "a", "purge", "request", "to", "the", "Akamai", "CCU", "API", "cpc", ".", "retries", "number", "of", "times", "before", "giving", "up", "and", "returning", "ErrAllRetriesFailed" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/akamai/cache-client.go#L268-L281
train
letsencrypt/boulder
akamai/cache-client.go
CheckSignature
func CheckSignature(secret string, url string, r *http.Request, body []byte) error { bodyHash := sha256.Sum256(body) bodyHashB64 := base64.StdEncoding.EncodeToString(bodyHash[:]) authorization := r.Header.Get("Authorization") authValues := make(map[string]string) for _, v := range strings.Split(authorization, ";") { splitValue := strings.Split(v, "=") authValues[splitValue[0]] = splitValue[1] } headerTimestamp := authValues["timestamp"] splitHeader := strings.Split(authorization, "signature=") shortenedHeader, signature := splitHeader[0], splitHeader[1] hostPort := strings.Split(url, "://")[1] h := hmac.New(sha256.New, signingKey(secret, headerTimestamp)) input := []byte(fmt.Sprintf("POST\thttp\t%s\t%s\t\t%s\t%s", hostPort, r.URL.Path, bodyHashB64, shortenedHeader, )) h.Write(input) expectedSignature := base64.StdEncoding.EncodeToString(h.Sum(nil)) if signature != expectedSignature { return fmt.Errorf("Wrong signature %q in %q. Expected %q\n", signature, authorization, expectedSignature) } return nil }
go
func CheckSignature(secret string, url string, r *http.Request, body []byte) error { bodyHash := sha256.Sum256(body) bodyHashB64 := base64.StdEncoding.EncodeToString(bodyHash[:]) authorization := r.Header.Get("Authorization") authValues := make(map[string]string) for _, v := range strings.Split(authorization, ";") { splitValue := strings.Split(v, "=") authValues[splitValue[0]] = splitValue[1] } headerTimestamp := authValues["timestamp"] splitHeader := strings.Split(authorization, "signature=") shortenedHeader, signature := splitHeader[0], splitHeader[1] hostPort := strings.Split(url, "://")[1] h := hmac.New(sha256.New, signingKey(secret, headerTimestamp)) input := []byte(fmt.Sprintf("POST\thttp\t%s\t%s\t\t%s\t%s", hostPort, r.URL.Path, bodyHashB64, shortenedHeader, )) h.Write(input) expectedSignature := base64.StdEncoding.EncodeToString(h.Sum(nil)) if signature != expectedSignature { return fmt.Errorf("Wrong signature %q in %q. Expected %q\n", signature, authorization, expectedSignature) } return nil }
[ "func", "CheckSignature", "(", "secret", "string", ",", "url", "string", ",", "r", "*", "http", ".", "Request", ",", "body", "[", "]", "byte", ")", "error", "{", "bodyHash", ":=", "sha256", ".", "Sum256", "(", "body", ")", "\n", "bodyHashB64", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "bodyHash", "[", ":", "]", ")", "\n\n", "authorization", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "authValues", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "v", ":=", "range", "strings", ".", "Split", "(", "authorization", ",", "\"", "\"", ")", "{", "splitValue", ":=", "strings", ".", "Split", "(", "v", ",", "\"", "\"", ")", "\n", "authValues", "[", "splitValue", "[", "0", "]", "]", "=", "splitValue", "[", "1", "]", "\n", "}", "\n", "headerTimestamp", ":=", "authValues", "[", "\"", "\"", "]", "\n", "splitHeader", ":=", "strings", ".", "Split", "(", "authorization", ",", "\"", "\"", ")", "\n", "shortenedHeader", ",", "signature", ":=", "splitHeader", "[", "0", "]", ",", "splitHeader", "[", "1", "]", "\n", "hostPort", ":=", "strings", ".", "Split", "(", "url", ",", "\"", "\"", ")", "[", "1", "]", "\n", "h", ":=", "hmac", ".", "New", "(", "sha256", ".", "New", ",", "signingKey", "(", "secret", ",", "headerTimestamp", ")", ")", "\n", "input", ":=", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\\t", "\\t", "\\t", "\\t", "\\t", "\\t", "\"", ",", "hostPort", ",", "r", ".", "URL", ".", "Path", ",", "bodyHashB64", ",", "shortenedHeader", ",", ")", ")", "\n", "h", ".", "Write", "(", "input", ")", "\n", "expectedSignature", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "h", ".", "Sum", "(", "nil", ")", ")", "\n", "if", "signature", "!=", "expectedSignature", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "signature", ",", "authorization", ",", "expectedSignature", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckSignature is used for tests, it exported so that it can be used in akamai-test-srv
[ "CheckSignature", "is", "used", "for", "tests", "it", "exported", "so", "that", "it", "can", "be", "used", "in", "akamai", "-", "test", "-", "srv" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/akamai/cache-client.go#L284-L312
train
letsencrypt/boulder
cmd/id-exporter/main.go
findIDs
func (c idExporter) findIDs() ([]id, error) { var idsList []id _, err := c.dbMap.Select( &idsList, `SELECT id FROM registrations WHERE contact != 'null' AND id IN ( SELECT registrationID FROM certificates WHERE expires >= :expireCutoff );`, map[string]interface{}{ "expireCutoff": c.clk.Now().Add(-c.grace), }) if err != nil { c.log.AuditErrf("Error finding IDs: %s", err) return nil, err } return idsList, nil }
go
func (c idExporter) findIDs() ([]id, error) { var idsList []id _, err := c.dbMap.Select( &idsList, `SELECT id FROM registrations WHERE contact != 'null' AND id IN ( SELECT registrationID FROM certificates WHERE expires >= :expireCutoff );`, map[string]interface{}{ "expireCutoff": c.clk.Now().Add(-c.grace), }) if err != nil { c.log.AuditErrf("Error finding IDs: %s", err) return nil, err } return idsList, nil }
[ "func", "(", "c", "idExporter", ")", "findIDs", "(", ")", "(", "[", "]", "id", ",", "error", ")", "{", "var", "idsList", "[", "]", "id", "\n", "_", ",", "err", ":=", "c", ".", "dbMap", ".", "Select", "(", "&", "idsList", ",", "`SELECT id\n\t\tFROM registrations\n\t\tWHERE contact != 'null' AND\n\t\t\tid IN (\n\t\t\t\tSELECT registrationID\n\t\t\t\tFROM certificates\n\t\t\t\tWHERE expires >= :expireCutoff\n\t\t\t);`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "c", ".", "clk", ".", "Now", "(", ")", ".", "Add", "(", "-", "c", ".", "grace", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "idsList", ",", "nil", "\n", "}" ]
// Find all registration IDs with unexpired certificates.
[ "Find", "all", "registration", "IDs", "with", "unexpired", "certificates", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/id-exporter/main.go#L34-L55
train
letsencrypt/boulder
cmd/id-exporter/main.go
writeIDs
func writeIDs(idsList []id, outfile string) error { data, err := json.Marshal(idsList) if err != nil { return err } data = append(data, '\n') if outfile != "" { return ioutil.WriteFile(outfile, data, 0644) } fmt.Printf("%s", data) return nil }
go
func writeIDs(idsList []id, outfile string) error { data, err := json.Marshal(idsList) if err != nil { return err } data = append(data, '\n') if outfile != "" { return ioutil.WriteFile(outfile, data, 0644) } fmt.Printf("%s", data) return nil }
[ "func", "writeIDs", "(", "idsList", "[", "]", "id", ",", "outfile", "string", ")", "error", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "idsList", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "data", "=", "append", "(", "data", ",", "'\\n'", ")", "\n\n", "if", "outfile", "!=", "\"", "\"", "{", "return", "ioutil", ".", "WriteFile", "(", "outfile", ",", "data", ",", "0644", ")", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "data", ")", "\n", "return", "nil", "\n", "}" ]
// The `writeIDs` function produces a file containing JSON serialized // contact objects
[ "The", "writeIDs", "function", "produces", "a", "file", "containing", "JSON", "serialized", "contact", "objects" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/id-exporter/main.go#L89-L102
train
letsencrypt/boulder
grpc/creds/creds.go
ClientHandshake
func (tc *clientTransportCredentials) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { var err error host := tc.hostOverride if host == "" { // IMPORTANT: Don't wrap the errors returned from this method. gRPC expects to be // able to check err.Temporary to spot temporary errors and reconnect when they happen. host, _, err = net.SplitHostPort(addr) if err != nil { return nil, nil, err } } conn := tls.Client(rawConn, &tls.Config{ ServerName: host, RootCAs: tc.roots, Certificates: tc.clients, MinVersion: tls.VersionTLS12, // Override default of tls.VersionTLS10 MaxVersion: tls.VersionTLS12, // Same as default in golang <= 1.6 }) errChan := make(chan error, 1) go func() { errChan <- conn.Handshake() }() select { case <-ctx.Done(): return nil, nil, ctx.Err() case err := <-errChan: if err != nil { _ = rawConn.Close() return nil, nil, err } return conn, nil, nil } }
go
func (tc *clientTransportCredentials) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { var err error host := tc.hostOverride if host == "" { // IMPORTANT: Don't wrap the errors returned from this method. gRPC expects to be // able to check err.Temporary to spot temporary errors and reconnect when they happen. host, _, err = net.SplitHostPort(addr) if err != nil { return nil, nil, err } } conn := tls.Client(rawConn, &tls.Config{ ServerName: host, RootCAs: tc.roots, Certificates: tc.clients, MinVersion: tls.VersionTLS12, // Override default of tls.VersionTLS10 MaxVersion: tls.VersionTLS12, // Same as default in golang <= 1.6 }) errChan := make(chan error, 1) go func() { errChan <- conn.Handshake() }() select { case <-ctx.Done(): return nil, nil, ctx.Err() case err := <-errChan: if err != nil { _ = rawConn.Close() return nil, nil, err } return conn, nil, nil } }
[ "func", "(", "tc", "*", "clientTransportCredentials", ")", "ClientHandshake", "(", "ctx", "context", ".", "Context", ",", "addr", "string", ",", "rawConn", "net", ".", "Conn", ")", "(", "net", ".", "Conn", ",", "credentials", ".", "AuthInfo", ",", "error", ")", "{", "var", "err", "error", "\n", "host", ":=", "tc", ".", "hostOverride", "\n", "if", "host", "==", "\"", "\"", "{", "// IMPORTANT: Don't wrap the errors returned from this method. gRPC expects to be", "// able to check err.Temporary to spot temporary errors and reconnect when they happen.", "host", ",", "_", ",", "err", "=", "net", ".", "SplitHostPort", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "conn", ":=", "tls", ".", "Client", "(", "rawConn", ",", "&", "tls", ".", "Config", "{", "ServerName", ":", "host", ",", "RootCAs", ":", "tc", ".", "roots", ",", "Certificates", ":", "tc", ".", "clients", ",", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "// Override default of tls.VersionTLS10", "MaxVersion", ":", "tls", ".", "VersionTLS12", ",", "// Same as default in golang <= 1.6", "}", ")", "\n", "errChan", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "errChan", "<-", "conn", ".", "Handshake", "(", ")", "\n", "}", "(", ")", "\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", ",", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "case", "err", ":=", "<-", "errChan", ":", "if", "err", "!=", "nil", "{", "_", "=", "rawConn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "conn", ",", "nil", ",", "nil", "\n", "}", "\n", "}" ]
// ClientHandshake does the authentication handshake specified by the corresponding // authentication protocol on rawConn for clients. It returns the authenticated // connection and the corresponding auth information about the connection. // Implementations must use the provided context to implement timely cancellation.
[ "ClientHandshake", "does", "the", "authentication", "handshake", "specified", "by", "the", "corresponding", "authentication", "protocol", "on", "rawConn", "for", "clients", ".", "It", "returns", "the", "authenticated", "connection", "and", "the", "corresponding", "auth", "information", "about", "the", "connection", ".", "Implementations", "must", "use", "the", "provided", "context", "to", "implement", "timely", "cancellation", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/creds/creds.go#L57-L89
train
letsencrypt/boulder
grpc/creds/creds.go
ServerHandshake
func (tc *clientTransportCredentials) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { return nil, nil, ServerHandshakeNopErr }
go
func (tc *clientTransportCredentials) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { return nil, nil, ServerHandshakeNopErr }
[ "func", "(", "tc", "*", "clientTransportCredentials", ")", "ServerHandshake", "(", "rawConn", "net", ".", "Conn", ")", "(", "net", ".", "Conn", ",", "credentials", ".", "AuthInfo", ",", "error", ")", "{", "return", "nil", ",", "nil", ",", "ServerHandshakeNopErr", "\n", "}" ]
// ServerHandshake is not implemented for a `clientTransportCredentials`, use // a `serverTransportCredentials` if you require `ServerHandshake`.
[ "ServerHandshake", "is", "not", "implemented", "for", "a", "clientTransportCredentials", "use", "a", "serverTransportCredentials", "if", "you", "require", "ServerHandshake", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/creds/creds.go#L93-L95
train
letsencrypt/boulder
grpc/creds/creds.go
Clone
func (tc *clientTransportCredentials) Clone() credentials.TransportCredentials { return NewClientCredentials(tc.roots, tc.clients, tc.hostOverride) }
go
func (tc *clientTransportCredentials) Clone() credentials.TransportCredentials { return NewClientCredentials(tc.roots, tc.clients, tc.hostOverride) }
[ "func", "(", "tc", "*", "clientTransportCredentials", ")", "Clone", "(", ")", "credentials", ".", "TransportCredentials", "{", "return", "NewClientCredentials", "(", "tc", ".", "roots", ",", "tc", ".", "clients", ",", "tc", ".", "hostOverride", ")", "\n", "}" ]
// Clone returns a copy of the clientTransportCredentials
[ "Clone", "returns", "a", "copy", "of", "the", "clientTransportCredentials" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/creds/creds.go#L116-L118
train
letsencrypt/boulder
grpc/creds/creds.go
ServerHandshake
func (tc *serverTransportCredentials) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { // Perform the server <- client TLS handshake. This will validate the peer's // client certificate. conn := tls.Server(rawConn, tc.serverConfig) if err := conn.Handshake(); err != nil { return nil, nil, err } // In addition to the validation from `conn.Handshake()` we apply further // constraints on what constitutes a valid peer if err := tc.validateClient(conn.ConnectionState()); err != nil { return nil, nil, err } return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil }
go
func (tc *serverTransportCredentials) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { // Perform the server <- client TLS handshake. This will validate the peer's // client certificate. conn := tls.Server(rawConn, tc.serverConfig) if err := conn.Handshake(); err != nil { return nil, nil, err } // In addition to the validation from `conn.Handshake()` we apply further // constraints on what constitutes a valid peer if err := tc.validateClient(conn.ConnectionState()); err != nil { return nil, nil, err } return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil }
[ "func", "(", "tc", "*", "serverTransportCredentials", ")", "ServerHandshake", "(", "rawConn", "net", ".", "Conn", ")", "(", "net", ".", "Conn", ",", "credentials", ".", "AuthInfo", ",", "error", ")", "{", "// Perform the server <- client TLS handshake. This will validate the peer's", "// client certificate.", "conn", ":=", "tls", ".", "Server", "(", "rawConn", ",", "tc", ".", "serverConfig", ")", "\n", "if", "err", ":=", "conn", ".", "Handshake", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// In addition to the validation from `conn.Handshake()` we apply further", "// constraints on what constitutes a valid peer", "if", "err", ":=", "tc", ".", "validateClient", "(", "conn", ".", "ConnectionState", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "conn", ",", "credentials", ".", "TLSInfo", "{", "State", ":", "conn", ".", "ConnectionState", "(", ")", "}", ",", "nil", "\n", "}" ]
// ServerHandshake does the authentication handshake for servers. It returns // the authenticated connection and the corresponding auth information about // the connection.
[ "ServerHandshake", "does", "the", "authentication", "handshake", "for", "servers", ".", "It", "returns", "the", "authenticated", "connection", "and", "the", "corresponding", "auth", "information", "about", "the", "connection", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/creds/creds.go#L205-L220
train
letsencrypt/boulder
grpc/creds/creds.go
ClientHandshake
func (tc *serverTransportCredentials) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { return nil, nil, ClientHandshakeNopErr }
go
func (tc *serverTransportCredentials) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { return nil, nil, ClientHandshakeNopErr }
[ "func", "(", "tc", "*", "serverTransportCredentials", ")", "ClientHandshake", "(", "ctx", "context", ".", "Context", ",", "addr", "string", ",", "rawConn", "net", ".", "Conn", ")", "(", "net", ".", "Conn", ",", "credentials", ".", "AuthInfo", ",", "error", ")", "{", "return", "nil", ",", "nil", ",", "ClientHandshakeNopErr", "\n", "}" ]
// ClientHandshake is not implemented for a `serverTransportCredentials`, use // a `clientTransportCredentials` if you require `ClientHandshake`.
[ "ClientHandshake", "is", "not", "implemented", "for", "a", "serverTransportCredentials", "use", "a", "clientTransportCredentials", "if", "you", "require", "ClientHandshake", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/creds/creds.go#L224-L226
train
letsencrypt/boulder
grpc/creds/creds.go
GetRequestMetadata
func (tc *serverTransportCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil }
go
func (tc *serverTransportCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil }
[ "func", "(", "tc", "*", "serverTransportCredentials", ")", "GetRequestMetadata", "(", "ctx", "context", ".", "Context", ",", "uri", "...", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "nil", ",", "nil", "\n", "}" ]
// GetRequestMetadata returns nil, nil since TLS credentials do not have metadata.
[ "GetRequestMetadata", "returns", "nil", "nil", "since", "TLS", "credentials", "do", "not", "have", "metadata", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/creds/creds.go#L237-L239
train
letsencrypt/boulder
grpc/creds/creds.go
Clone
func (tc *serverTransportCredentials) Clone() credentials.TransportCredentials { clone, _ := NewServerCredentials(tc.serverConfig, tc.acceptedSANs) return clone }
go
func (tc *serverTransportCredentials) Clone() credentials.TransportCredentials { clone, _ := NewServerCredentials(tc.serverConfig, tc.acceptedSANs) return clone }
[ "func", "(", "tc", "*", "serverTransportCredentials", ")", "Clone", "(", ")", "credentials", ".", "TransportCredentials", "{", "clone", ",", "_", ":=", "NewServerCredentials", "(", "tc", ".", "serverConfig", ",", "tc", ".", "acceptedSANs", ")", "\n", "return", "clone", "\n", "}" ]
// Clone returns a copy of the serverTransportCredentials
[ "Clone", "returns", "a", "copy", "of", "the", "serverTransportCredentials" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/creds/creds.go#L247-L250
train
letsencrypt/boulder
core/objects.go
ValidChallenge
func ValidChallenge(name string) bool { switch name { case ChallengeTypeHTTP01, ChallengeTypeDNS01, ChallengeTypeTLSALPN01: return true default: return false } }
go
func ValidChallenge(name string) bool { switch name { case ChallengeTypeHTTP01, ChallengeTypeDNS01, ChallengeTypeTLSALPN01: return true default: return false } }
[ "func", "ValidChallenge", "(", "name", "string", ")", "bool", "{", "switch", "name", "{", "case", "ChallengeTypeHTTP01", ",", "ChallengeTypeDNS01", ",", "ChallengeTypeTLSALPN01", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// ValidChallenge tests whether the provided string names a known challenge
[ "ValidChallenge", "tests", "whether", "the", "provided", "string", "names", "a", "known", "challenge" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/objects.go#L75-L84
train
letsencrypt/boulder
core/objects.go
UnmarshalJSON
func (cr *CertificateRequest) UnmarshalJSON(data []byte) error { var raw RawCertificateRequest if err := json.Unmarshal(data, &raw); err != nil { return err } csr, err := x509.ParseCertificateRequest(raw.CSR) if err != nil { return err } cr.CSR = csr cr.Bytes = raw.CSR return nil }
go
func (cr *CertificateRequest) UnmarshalJSON(data []byte) error { var raw RawCertificateRequest if err := json.Unmarshal(data, &raw); err != nil { return err } csr, err := x509.ParseCertificateRequest(raw.CSR) if err != nil { return err } cr.CSR = csr cr.Bytes = raw.CSR return nil }
[ "func", "(", "cr", "*", "CertificateRequest", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "raw", "RawCertificateRequest", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "raw", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "csr", ",", "err", ":=", "x509", ".", "ParseCertificateRequest", "(", "raw", ".", "CSR", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cr", ".", "CSR", "=", "csr", "\n", "cr", ".", "Bytes", "=", "raw", ".", "CSR", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON provides an implementation for decoding CertificateRequest objects.
[ "UnmarshalJSON", "provides", "an", "implementation", "for", "decoding", "CertificateRequest", "objects", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/objects.go#L113-L127
train
letsencrypt/boulder
core/objects.go
MarshalJSON
func (cr CertificateRequest) MarshalJSON() ([]byte, error) { return json.Marshal(RawCertificateRequest{ CSR: cr.CSR.Raw, }) }
go
func (cr CertificateRequest) MarshalJSON() ([]byte, error) { return json.Marshal(RawCertificateRequest{ CSR: cr.CSR.Raw, }) }
[ "func", "(", "cr", "CertificateRequest", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "RawCertificateRequest", "{", "CSR", ":", "cr", ".", "CSR", ".", "Raw", ",", "}", ")", "\n", "}" ]
// MarshalJSON provides an implementation for encoding CertificateRequest objects.
[ "MarshalJSON", "provides", "an", "implementation", "for", "encoding", "CertificateRequest", "objects", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/objects.go#L130-L134
train