repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
letsencrypt/boulder | wfe2/wfe.go | BuildID | func (wfe *WebFrontEndImpl) BuildID(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "text/plain")
response.WriteHeader(http.StatusOK)
detailsString := fmt.Sprintf("Boulder=(%s %s)", core.GetBuildID(), core.GetBuildTime())
if _, err := fmt.Fprintln(response, detailsString); err != nil {
wfe.log.Warningf("Could not write response: %s", err)
}
} | go | func (wfe *WebFrontEndImpl) BuildID(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "text/plain")
response.WriteHeader(http.StatusOK)
detailsString := fmt.Sprintf("Boulder=(%s %s)", core.GetBuildID(), core.GetBuildTime())
if _, err := fmt.Fprintln(response, detailsString); err != nil {
wfe.log.Warningf("Could not write response: %s", err)
}
} | [
"func",
"(",
"wfe",
"*",
"WebFrontEndImpl",
")",
"BuildID",
"(",
"ctx",
"context",
".",
"Context",
",",
"logEvent",
"*",
"web",
".",
"RequestEvent",
",",
"response",
"http",
".",
"ResponseWriter",
",",
"request",
"*",
"http",
".",
"Request",
")",
"{",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"text/plain\"",
")",
"\n",
"response",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"detailsString",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"Boulder=(%s %s)\"",
",",
"core",
".",
"GetBuildID",
"(",
")",
",",
"core",
".",
"GetBuildTime",
"(",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"fmt",
".",
"Fprintln",
"(",
"response",
",",
"detailsString",
")",
";",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"log",
".",
"Warningf",
"(",
"\"Could not write response: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // BuildID tells the requestor what build we're running. | [
"BuildID",
"tells",
"the",
"requestor",
"what",
"build",
"we",
"re",
"running",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L1508-L1515 | train |
letsencrypt/boulder | wfe2/wfe.go | Options | func (wfe *WebFrontEndImpl) Options(response http.ResponseWriter, request *http.Request, methodsStr string, methodsMap map[string]bool) {
// Every OPTIONS request gets an Allow header with a list of supported methods.
response.Header().Set("Allow", methodsStr)
// CORS preflight requests get additional headers. See
// http://www.w3.org/TR/cors/#resource-preflight-requests
reqMethod := request.Header.Get("Access-Control-Request-Method")
if reqMethod == "" {
reqMethod = "GET"
}
if methodsMap[reqMethod] {
wfe.setCORSHeaders(response, request, methodsStr)
}
} | go | func (wfe *WebFrontEndImpl) Options(response http.ResponseWriter, request *http.Request, methodsStr string, methodsMap map[string]bool) {
// Every OPTIONS request gets an Allow header with a list of supported methods.
response.Header().Set("Allow", methodsStr)
// CORS preflight requests get additional headers. See
// http://www.w3.org/TR/cors/#resource-preflight-requests
reqMethod := request.Header.Get("Access-Control-Request-Method")
if reqMethod == "" {
reqMethod = "GET"
}
if methodsMap[reqMethod] {
wfe.setCORSHeaders(response, request, methodsStr)
}
} | [
"func",
"(",
"wfe",
"*",
"WebFrontEndImpl",
")",
"Options",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"request",
"*",
"http",
".",
"Request",
",",
"methodsStr",
"string",
",",
"methodsMap",
"map",
"[",
"string",
"]",
"bool",
")",
"{",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Allow\"",
",",
"methodsStr",
")",
"\n",
"reqMethod",
":=",
"request",
".",
"Header",
".",
"Get",
"(",
"\"Access-Control-Request-Method\"",
")",
"\n",
"if",
"reqMethod",
"==",
"\"\"",
"{",
"reqMethod",
"=",
"\"GET\"",
"\n",
"}",
"\n",
"if",
"methodsMap",
"[",
"reqMethod",
"]",
"{",
"wfe",
".",
"setCORSHeaders",
"(",
"response",
",",
"request",
",",
"methodsStr",
")",
"\n",
"}",
"\n",
"}"
] | // Options responds to an HTTP OPTIONS request. | [
"Options",
"responds",
"to",
"an",
"HTTP",
"OPTIONS",
"request",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L1518-L1531 | train |
letsencrypt/boulder | wfe2/wfe.go | NewOrder | func (wfe *WebFrontEndImpl) NewOrder(
ctx context.Context,
logEvent *web.RequestEvent,
response http.ResponseWriter,
request *http.Request) {
body, _, acct, prob := wfe.validPOSTForAccount(request, ctx, logEvent)
addRequesterHeader(response, logEvent.Requester)
if prob != nil {
// validPOSTForAccount handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
return
}
// We only allow specifying Identifiers in a new order request - if the
// `notBefore` and/or `notAfter` fields described in Section 7.4 of acme-08
// are sent we return a probs.Malformed as we do not support them
var newOrderRequest struct {
Identifiers []core.AcmeIdentifier `json:"identifiers"`
NotBefore, NotAfter string
}
err := json.Unmarshal(body, &newOrderRequest)
if err != nil {
wfe.sendError(response, logEvent,
probs.Malformed("Unable to unmarshal NewOrder request body"), err)
return
}
if len(newOrderRequest.Identifiers) == 0 {
wfe.sendError(response, logEvent,
probs.Malformed("NewOrder request did not specify any identifiers"), nil)
return
}
if newOrderRequest.NotBefore != "" || newOrderRequest.NotAfter != "" {
wfe.sendError(response, logEvent, probs.Malformed("NotBefore and NotAfter are not supported"), nil)
return
}
// Collect up all of the DNS identifier values into a []string for subsequent
// layers to process. We reject anything with a non-DNS type identifier here.
names := make([]string, len(newOrderRequest.Identifiers))
for i, ident := range newOrderRequest.Identifiers {
if ident.Type != core.IdentifierDNS {
wfe.sendError(response, logEvent,
probs.Malformed("NewOrder request included invalid non-DNS type identifier: type %q, value %q",
ident.Type, ident.Value),
nil)
return
}
names[i] = ident.Value
}
order, err := wfe.RA.NewOrder(ctx, &rapb.NewOrderRequest{
RegistrationID: &acct.ID,
Names: names,
})
if err != nil {
wfe.sendError(response, logEvent, web.ProblemDetailsForError(err, "Error creating new order"), err)
return
}
logEvent.Created = fmt.Sprintf("%d", *order.Id)
orderURL := web.RelativeEndpoint(request,
fmt.Sprintf("%s%d/%d", orderPath, acct.ID, *order.Id))
response.Header().Set("Location", orderURL)
respObj := wfe.orderToOrderJSON(request, order)
err = wfe.writeJsonResponse(response, logEvent, http.StatusCreated, respObj)
if err != nil {
wfe.sendError(response, logEvent, probs.ServerInternal("Error marshaling order"), err)
return
}
} | go | func (wfe *WebFrontEndImpl) NewOrder(
ctx context.Context,
logEvent *web.RequestEvent,
response http.ResponseWriter,
request *http.Request) {
body, _, acct, prob := wfe.validPOSTForAccount(request, ctx, logEvent)
addRequesterHeader(response, logEvent.Requester)
if prob != nil {
// validPOSTForAccount handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
return
}
// We only allow specifying Identifiers in a new order request - if the
// `notBefore` and/or `notAfter` fields described in Section 7.4 of acme-08
// are sent we return a probs.Malformed as we do not support them
var newOrderRequest struct {
Identifiers []core.AcmeIdentifier `json:"identifiers"`
NotBefore, NotAfter string
}
err := json.Unmarshal(body, &newOrderRequest)
if err != nil {
wfe.sendError(response, logEvent,
probs.Malformed("Unable to unmarshal NewOrder request body"), err)
return
}
if len(newOrderRequest.Identifiers) == 0 {
wfe.sendError(response, logEvent,
probs.Malformed("NewOrder request did not specify any identifiers"), nil)
return
}
if newOrderRequest.NotBefore != "" || newOrderRequest.NotAfter != "" {
wfe.sendError(response, logEvent, probs.Malformed("NotBefore and NotAfter are not supported"), nil)
return
}
// Collect up all of the DNS identifier values into a []string for subsequent
// layers to process. We reject anything with a non-DNS type identifier here.
names := make([]string, len(newOrderRequest.Identifiers))
for i, ident := range newOrderRequest.Identifiers {
if ident.Type != core.IdentifierDNS {
wfe.sendError(response, logEvent,
probs.Malformed("NewOrder request included invalid non-DNS type identifier: type %q, value %q",
ident.Type, ident.Value),
nil)
return
}
names[i] = ident.Value
}
order, err := wfe.RA.NewOrder(ctx, &rapb.NewOrderRequest{
RegistrationID: &acct.ID,
Names: names,
})
if err != nil {
wfe.sendError(response, logEvent, web.ProblemDetailsForError(err, "Error creating new order"), err)
return
}
logEvent.Created = fmt.Sprintf("%d", *order.Id)
orderURL := web.RelativeEndpoint(request,
fmt.Sprintf("%s%d/%d", orderPath, acct.ID, *order.Id))
response.Header().Set("Location", orderURL)
respObj := wfe.orderToOrderJSON(request, order)
err = wfe.writeJsonResponse(response, logEvent, http.StatusCreated, respObj)
if err != nil {
wfe.sendError(response, logEvent, probs.ServerInternal("Error marshaling order"), err)
return
}
} | [
"func",
"(",
"wfe",
"*",
"WebFrontEndImpl",
")",
"NewOrder",
"(",
"ctx",
"context",
".",
"Context",
",",
"logEvent",
"*",
"web",
".",
"RequestEvent",
",",
"response",
"http",
".",
"ResponseWriter",
",",
"request",
"*",
"http",
".",
"Request",
")",
"{",
"body",
",",
"_",
",",
"acct",
",",
"prob",
":=",
"wfe",
".",
"validPOSTForAccount",
"(",
"request",
",",
"ctx",
",",
"logEvent",
")",
"\n",
"addRequesterHeader",
"(",
"response",
",",
"logEvent",
".",
"Requester",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"prob",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"newOrderRequest",
"struct",
"{",
"Identifiers",
"[",
"]",
"core",
".",
"AcmeIdentifier",
"`json:\"identifiers\"`",
"\n",
"NotBefore",
",",
"NotAfter",
"string",
"\n",
"}",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"newOrderRequest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Malformed",
"(",
"\"Unable to unmarshal NewOrder request body\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"len",
"(",
"newOrderRequest",
".",
"Identifiers",
")",
"==",
"0",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Malformed",
"(",
"\"NewOrder request did not specify any identifiers\"",
")",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"newOrderRequest",
".",
"NotBefore",
"!=",
"\"\"",
"||",
"newOrderRequest",
".",
"NotAfter",
"!=",
"\"\"",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Malformed",
"(",
"\"NotBefore and NotAfter are not supported\"",
")",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"newOrderRequest",
".",
"Identifiers",
")",
")",
"\n",
"for",
"i",
",",
"ident",
":=",
"range",
"newOrderRequest",
".",
"Identifiers",
"{",
"if",
"ident",
".",
"Type",
"!=",
"core",
".",
"IdentifierDNS",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Malformed",
"(",
"\"NewOrder request included invalid non-DNS type identifier: type %q, value %q\"",
",",
"ident",
".",
"Type",
",",
"ident",
".",
"Value",
")",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"names",
"[",
"i",
"]",
"=",
"ident",
".",
"Value",
"\n",
"}",
"\n",
"order",
",",
"err",
":=",
"wfe",
".",
"RA",
".",
"NewOrder",
"(",
"ctx",
",",
"&",
"rapb",
".",
"NewOrderRequest",
"{",
"RegistrationID",
":",
"&",
"acct",
".",
"ID",
",",
"Names",
":",
"names",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"web",
".",
"ProblemDetailsForError",
"(",
"err",
",",
"\"Error creating new order\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"logEvent",
".",
"Created",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%d\"",
",",
"*",
"order",
".",
"Id",
")",
"\n",
"orderURL",
":=",
"web",
".",
"RelativeEndpoint",
"(",
"request",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s%d/%d\"",
",",
"orderPath",
",",
"acct",
".",
"ID",
",",
"*",
"order",
".",
"Id",
")",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Location\"",
",",
"orderURL",
")",
"\n",
"respObj",
":=",
"wfe",
".",
"orderToOrderJSON",
"(",
"request",
",",
"order",
")",
"\n",
"err",
"=",
"wfe",
".",
"writeJsonResponse",
"(",
"response",
",",
"logEvent",
",",
"http",
".",
"StatusCreated",
",",
"respObj",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"ServerInternal",
"(",
"\"Error marshaling order\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // NewOrder is used by clients to create a new order object from a CSR | [
"NewOrder",
"is",
"used",
"by",
"clients",
"to",
"create",
"a",
"new",
"order",
"object",
"from",
"a",
"CSR"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L1718-L1789 | train |
letsencrypt/boulder | wfe2/wfe.go | GetOrder | func (wfe *WebFrontEndImpl) GetOrder(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
var requesterAccount *core.Registration
// Any POSTs to the Order endpoint should be POST-as-GET requests. There are
// no POSTs with a body allowed for this endpoint.
if request.Method == "POST" {
acct, prob := wfe.validPOSTAsGETForAccount(request, ctx, logEvent)
if prob != nil {
wfe.sendError(response, logEvent, prob, nil)
return
}
requesterAccount = acct
}
// Path prefix is stripped, so this should be like "<account ID>/<order ID>"
fields := strings.SplitN(request.URL.Path, "/", 2)
if len(fields) != 2 {
wfe.sendError(response, logEvent, probs.NotFound("Invalid request path"), nil)
return
}
acctID, err := strconv.ParseInt(fields[0], 10, 64)
if err != nil {
wfe.sendError(response, logEvent, probs.Malformed("Invalid account ID"), err)
return
}
orderID, err := strconv.ParseInt(fields[1], 10, 64)
if err != nil {
wfe.sendError(response, logEvent, probs.Malformed("Invalid order ID"), err)
return
}
useV2Authzs := features.Enabled(features.NewAuthorizationSchema)
order, err := wfe.SA.GetOrder(ctx, &sapb.OrderRequest{Id: &orderID, UseV2Authorizations: &useV2Authzs})
if err != nil {
if berrors.Is(err, berrors.NotFound) {
wfe.sendError(response, logEvent, probs.NotFound("No order for ID %d", orderID), err)
return
}
wfe.sendError(response, logEvent, probs.ServerInternal("Failed to retrieve order for ID %d", orderID), err)
return
}
if *order.RegistrationID != acctID {
wfe.sendError(response, logEvent, probs.NotFound("No order found for account ID %d", acctID), nil)
return
}
// If the requesterAccount is not nil then this was an authenticated
// POST-as-GET request and we need to verify the requesterAccount is the
// order's owner.
if requesterAccount != nil && *order.RegistrationID != requesterAccount.ID {
wfe.sendError(response, logEvent, probs.NotFound("No order found for account ID %d", acctID), nil)
return
}
respObj := wfe.orderToOrderJSON(request, order)
err = wfe.writeJsonResponse(response, logEvent, http.StatusOK, respObj)
if err != nil {
wfe.sendError(response, logEvent, probs.ServerInternal("Error marshaling order"), err)
return
}
} | go | func (wfe *WebFrontEndImpl) GetOrder(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
var requesterAccount *core.Registration
// Any POSTs to the Order endpoint should be POST-as-GET requests. There are
// no POSTs with a body allowed for this endpoint.
if request.Method == "POST" {
acct, prob := wfe.validPOSTAsGETForAccount(request, ctx, logEvent)
if prob != nil {
wfe.sendError(response, logEvent, prob, nil)
return
}
requesterAccount = acct
}
// Path prefix is stripped, so this should be like "<account ID>/<order ID>"
fields := strings.SplitN(request.URL.Path, "/", 2)
if len(fields) != 2 {
wfe.sendError(response, logEvent, probs.NotFound("Invalid request path"), nil)
return
}
acctID, err := strconv.ParseInt(fields[0], 10, 64)
if err != nil {
wfe.sendError(response, logEvent, probs.Malformed("Invalid account ID"), err)
return
}
orderID, err := strconv.ParseInt(fields[1], 10, 64)
if err != nil {
wfe.sendError(response, logEvent, probs.Malformed("Invalid order ID"), err)
return
}
useV2Authzs := features.Enabled(features.NewAuthorizationSchema)
order, err := wfe.SA.GetOrder(ctx, &sapb.OrderRequest{Id: &orderID, UseV2Authorizations: &useV2Authzs})
if err != nil {
if berrors.Is(err, berrors.NotFound) {
wfe.sendError(response, logEvent, probs.NotFound("No order for ID %d", orderID), err)
return
}
wfe.sendError(response, logEvent, probs.ServerInternal("Failed to retrieve order for ID %d", orderID), err)
return
}
if *order.RegistrationID != acctID {
wfe.sendError(response, logEvent, probs.NotFound("No order found for account ID %d", acctID), nil)
return
}
// If the requesterAccount is not nil then this was an authenticated
// POST-as-GET request and we need to verify the requesterAccount is the
// order's owner.
if requesterAccount != nil && *order.RegistrationID != requesterAccount.ID {
wfe.sendError(response, logEvent, probs.NotFound("No order found for account ID %d", acctID), nil)
return
}
respObj := wfe.orderToOrderJSON(request, order)
err = wfe.writeJsonResponse(response, logEvent, http.StatusOK, respObj)
if err != nil {
wfe.sendError(response, logEvent, probs.ServerInternal("Error marshaling order"), err)
return
}
} | [
"func",
"(",
"wfe",
"*",
"WebFrontEndImpl",
")",
"GetOrder",
"(",
"ctx",
"context",
".",
"Context",
",",
"logEvent",
"*",
"web",
".",
"RequestEvent",
",",
"response",
"http",
".",
"ResponseWriter",
",",
"request",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"requesterAccount",
"*",
"core",
".",
"Registration",
"\n",
"if",
"request",
".",
"Method",
"==",
"\"POST\"",
"{",
"acct",
",",
"prob",
":=",
"wfe",
".",
"validPOSTAsGETForAccount",
"(",
"request",
",",
"ctx",
",",
"logEvent",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"prob",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"requesterAccount",
"=",
"acct",
"\n",
"}",
"\n",
"fields",
":=",
"strings",
".",
"SplitN",
"(",
"request",
".",
"URL",
".",
"Path",
",",
"\"/\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"fields",
")",
"!=",
"2",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"NotFound",
"(",
"\"Invalid request path\"",
")",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"acctID",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"fields",
"[",
"0",
"]",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Malformed",
"(",
"\"Invalid account ID\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"orderID",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"fields",
"[",
"1",
"]",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Malformed",
"(",
"\"Invalid order ID\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"useV2Authzs",
":=",
"features",
".",
"Enabled",
"(",
"features",
".",
"NewAuthorizationSchema",
")",
"\n",
"order",
",",
"err",
":=",
"wfe",
".",
"SA",
".",
"GetOrder",
"(",
"ctx",
",",
"&",
"sapb",
".",
"OrderRequest",
"{",
"Id",
":",
"&",
"orderID",
",",
"UseV2Authorizations",
":",
"&",
"useV2Authzs",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"berrors",
".",
"Is",
"(",
"err",
",",
"berrors",
".",
"NotFound",
")",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"NotFound",
"(",
"\"No order for ID %d\"",
",",
"orderID",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"ServerInternal",
"(",
"\"Failed to retrieve order for ID %d\"",
",",
"orderID",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"*",
"order",
".",
"RegistrationID",
"!=",
"acctID",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"NotFound",
"(",
"\"No order found for account ID %d\"",
",",
"acctID",
")",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"requesterAccount",
"!=",
"nil",
"&&",
"*",
"order",
".",
"RegistrationID",
"!=",
"requesterAccount",
".",
"ID",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"NotFound",
"(",
"\"No order found for account ID %d\"",
",",
"acctID",
")",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"respObj",
":=",
"wfe",
".",
"orderToOrderJSON",
"(",
"request",
",",
"order",
")",
"\n",
"err",
"=",
"wfe",
".",
"writeJsonResponse",
"(",
"response",
",",
"logEvent",
",",
"http",
".",
"StatusOK",
",",
"respObj",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"ServerInternal",
"(",
"\"Error marshaling order\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // GetOrder is used to retrieve a existing order object | [
"GetOrder",
"is",
"used",
"to",
"retrieve",
"a",
"existing",
"order",
"object"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L1792-L1852 | train |
letsencrypt/boulder | cmd/notify-mailer/main.go | resolveEmailAddresses | func (m *mailer) resolveEmailAddresses() (emailToRecipientMap, error) {
result := make(emailToRecipientMap, len(m.destinations))
for _, r := range m.destinations {
// Get the email address for the reg ID
emails, err := emailsForReg(r.id, m.dbMap)
if err != nil {
return nil, err
}
for _, email := range emails {
parsedEmail, err := mail.ParseAddress(email)
if err != nil {
m.log.Errf("unparseable email for reg ID %d : %q", r.id, email)
continue
}
addr := parsedEmail.Address
result[addr] = append(result[addr], r)
}
}
return result, nil
} | go | func (m *mailer) resolveEmailAddresses() (emailToRecipientMap, error) {
result := make(emailToRecipientMap, len(m.destinations))
for _, r := range m.destinations {
// Get the email address for the reg ID
emails, err := emailsForReg(r.id, m.dbMap)
if err != nil {
return nil, err
}
for _, email := range emails {
parsedEmail, err := mail.ParseAddress(email)
if err != nil {
m.log.Errf("unparseable email for reg ID %d : %q", r.id, email)
continue
}
addr := parsedEmail.Address
result[addr] = append(result[addr], r)
}
}
return result, nil
} | [
"func",
"(",
"m",
"*",
"mailer",
")",
"resolveEmailAddresses",
"(",
")",
"(",
"emailToRecipientMap",
",",
"error",
")",
"{",
"result",
":=",
"make",
"(",
"emailToRecipientMap",
",",
"len",
"(",
"m",
".",
"destinations",
")",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"m",
".",
"destinations",
"{",
"emails",
",",
"err",
":=",
"emailsForReg",
"(",
"r",
".",
"id",
",",
"m",
".",
"dbMap",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"email",
":=",
"range",
"emails",
"{",
"parsedEmail",
",",
"err",
":=",
"mail",
".",
"ParseAddress",
"(",
"email",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"log",
".",
"Errf",
"(",
"\"unparseable email for reg ID %d : %q\"",
",",
"r",
".",
"id",
",",
"email",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"addr",
":=",
"parsedEmail",
".",
"Address",
"\n",
"result",
"[",
"addr",
"]",
"=",
"append",
"(",
"result",
"[",
"addr",
"]",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // resolveEmailAddresses looks up the id of each recipient to find that
// account's email addresses, then adds that recipient to a map from address to
// recipient struct. | [
"resolveEmailAddresses",
"looks",
"up",
"the",
"id",
"of",
"each",
"recipient",
"to",
"find",
"that",
"account",
"s",
"email",
"addresses",
"then",
"adds",
"that",
"recipient",
"to",
"a",
"map",
"from",
"address",
"to",
"recipient",
"struct",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/notify-mailer/main.go#L184-L205 | train |
letsencrypt/boulder | cmd/notify-mailer/main.go | emailsForReg | func emailsForReg(id int, dbMap dbSelector) ([]string, error) {
var contact contactJSON
err := dbMap.SelectOne(&contact,
`SELECT id, contact
FROM registrations
WHERE contact != 'null' AND id = :id;`,
map[string]interface{}{
"id": id,
})
if err == sql.ErrNoRows {
return []string{}, nil
}
if err != nil {
return nil, err
}
var contactFields []string
var addresses []string
err = json.Unmarshal(contact.Contact, &contactFields)
if err != nil {
return nil, err
}
for _, entry := range contactFields {
if strings.HasPrefix(entry, "mailto:") {
addresses = append(addresses, strings.TrimPrefix(entry, "mailto:"))
}
}
return addresses, nil
} | go | func emailsForReg(id int, dbMap dbSelector) ([]string, error) {
var contact contactJSON
err := dbMap.SelectOne(&contact,
`SELECT id, contact
FROM registrations
WHERE contact != 'null' AND id = :id;`,
map[string]interface{}{
"id": id,
})
if err == sql.ErrNoRows {
return []string{}, nil
}
if err != nil {
return nil, err
}
var contactFields []string
var addresses []string
err = json.Unmarshal(contact.Contact, &contactFields)
if err != nil {
return nil, err
}
for _, entry := range contactFields {
if strings.HasPrefix(entry, "mailto:") {
addresses = append(addresses, strings.TrimPrefix(entry, "mailto:"))
}
}
return addresses, nil
} | [
"func",
"emailsForReg",
"(",
"id",
"int",
",",
"dbMap",
"dbSelector",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"contact",
"contactJSON",
"\n",
"err",
":=",
"dbMap",
".",
"SelectOne",
"(",
"&",
"contact",
",",
"`SELECT id, contact\t\tFROM registrations\t\tWHERE contact != 'null' AND id = :id;`",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"id\"",
":",
"id",
",",
"}",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"contactFields",
"[",
"]",
"string",
"\n",
"var",
"addresses",
"[",
"]",
"string",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"contact",
".",
"Contact",
",",
"&",
"contactFields",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"entry",
":=",
"range",
"contactFields",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"entry",
",",
"\"mailto:\"",
")",
"{",
"addresses",
"=",
"append",
"(",
"addresses",
",",
"strings",
".",
"TrimPrefix",
"(",
"entry",
",",
"\"mailto:\"",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"addresses",
",",
"nil",
"\n",
"}"
] | // Finds the email addresses associated with a reg ID | [
"Finds",
"the",
"email",
"addresses",
"associated",
"with",
"a",
"reg",
"ID"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/notify-mailer/main.go#L216-L244 | train |
letsencrypt/boulder | cmd/notify-mailer/main.go | readRecipientsList | func readRecipientsList(filename string) ([]recipient, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
reader := csv.NewReader(f)
record, err := reader.Read()
if err != nil {
return nil, err
}
if len(record) == 0 {
return nil, fmt.Errorf("no entries in CSV")
}
if record[0] != "id" {
return nil, fmt.Errorf("first field of CSV input must be an ID.")
}
var columnNames []string
for _, v := range record[1:] {
columnNames = append(columnNames, strings.TrimSpace(v))
}
results := []recipient{}
for {
record, err := reader.Read()
if err == io.EOF {
if len(results) == 0 {
return nil, fmt.Errorf("no entries after the header in CSV")
}
return results, nil
}
if err != nil {
return nil, err
}
if len(record) == 0 {
return nil, fmt.Errorf("empty line in CSV")
}
if len(record) != len(columnNames)+1 {
return nil, fmt.Errorf("Number of columns in CSV line didn't match header columns."+
" Got %d, expected %d. Line: %v", len(record), len(columnNames)+1, record)
}
id, err := strconv.Atoi(record[0])
if err != nil {
return nil, err
}
recip := recipient{
id: id,
Extra: make(map[string]string),
}
for i, v := range record[1:] {
recip.Extra[columnNames[i]] = v
}
results = append(results, recip)
}
} | go | func readRecipientsList(filename string) ([]recipient, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
reader := csv.NewReader(f)
record, err := reader.Read()
if err != nil {
return nil, err
}
if len(record) == 0 {
return nil, fmt.Errorf("no entries in CSV")
}
if record[0] != "id" {
return nil, fmt.Errorf("first field of CSV input must be an ID.")
}
var columnNames []string
for _, v := range record[1:] {
columnNames = append(columnNames, strings.TrimSpace(v))
}
results := []recipient{}
for {
record, err := reader.Read()
if err == io.EOF {
if len(results) == 0 {
return nil, fmt.Errorf("no entries after the header in CSV")
}
return results, nil
}
if err != nil {
return nil, err
}
if len(record) == 0 {
return nil, fmt.Errorf("empty line in CSV")
}
if len(record) != len(columnNames)+1 {
return nil, fmt.Errorf("Number of columns in CSV line didn't match header columns."+
" Got %d, expected %d. Line: %v", len(record), len(columnNames)+1, record)
}
id, err := strconv.Atoi(record[0])
if err != nil {
return nil, err
}
recip := recipient{
id: id,
Extra: make(map[string]string),
}
for i, v := range record[1:] {
recip.Extra[columnNames[i]] = v
}
results = append(results, recip)
}
} | [
"func",
"readRecipientsList",
"(",
"filename",
"string",
")",
"(",
"[",
"]",
"recipient",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"reader",
":=",
"csv",
".",
"NewReader",
"(",
"f",
")",
"\n",
"record",
",",
"err",
":=",
"reader",
".",
"Read",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"record",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"no entries in CSV\"",
")",
"\n",
"}",
"\n",
"if",
"record",
"[",
"0",
"]",
"!=",
"\"id\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"first field of CSV input must be an ID.\"",
")",
"\n",
"}",
"\n",
"var",
"columnNames",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"record",
"[",
"1",
":",
"]",
"{",
"columnNames",
"=",
"append",
"(",
"columnNames",
",",
"strings",
".",
"TrimSpace",
"(",
"v",
")",
")",
"\n",
"}",
"\n",
"results",
":=",
"[",
"]",
"recipient",
"{",
"}",
"\n",
"for",
"{",
"record",
",",
"err",
":=",
"reader",
".",
"Read",
"(",
")",
"\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"if",
"len",
"(",
"results",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"no entries after the header in CSV\"",
")",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"record",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"empty line in CSV\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"record",
")",
"!=",
"len",
"(",
"columnNames",
")",
"+",
"1",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Number of columns in CSV line didn't match header columns.\"",
"+",
"\" Got %d, expected %d. Line: %v\"",
",",
"len",
"(",
"record",
")",
",",
"len",
"(",
"columnNames",
")",
"+",
"1",
",",
"record",
")",
"\n",
"}",
"\n",
"id",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"record",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"recip",
":=",
"recipient",
"{",
"id",
":",
"id",
",",
"Extra",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"}",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"record",
"[",
"1",
":",
"]",
"{",
"recip",
".",
"Extra",
"[",
"columnNames",
"[",
"i",
"]",
"]",
"=",
"v",
"\n",
"}",
"\n",
"results",
"=",
"append",
"(",
"results",
",",
"recip",
")",
"\n",
"}",
"\n",
"}"
] | // readRecipientsList reads a CSV filename and parses that file into a list of
// recipient structs. It puts any columns after the first into a per-recipient
// map from column name -> value. | [
"readRecipientsList",
"reads",
"a",
"CSV",
"filename",
"and",
"parses",
"that",
"file",
"into",
"a",
"list",
"of",
"recipient",
"structs",
".",
"It",
"puts",
"any",
"columns",
"after",
"the",
"first",
"into",
"a",
"per",
"-",
"recipient",
"map",
"from",
"column",
"name",
"-",
">",
"value",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/notify-mailer/main.go#L260-L313 | train |
letsencrypt/boulder | log/mock.go | newMockWriter | func newMockWriter() *mockWriter {
msgChan := make(chan string)
getChan := make(chan []string)
clearChan := make(chan struct{})
closeChan := make(chan struct{})
w := &mockWriter{
logged: []string{},
msgChan: msgChan,
getChan: getChan,
clearChan: clearChan,
closeChan: closeChan,
}
go func() {
for {
select {
case logMsg := <-msgChan:
w.logged = append(w.logged, logMsg)
case getChan <- w.logged:
case <-clearChan:
w.logged = []string{}
case <-closeChan:
close(getChan)
return
}
}
}()
return w
} | go | func newMockWriter() *mockWriter {
msgChan := make(chan string)
getChan := make(chan []string)
clearChan := make(chan struct{})
closeChan := make(chan struct{})
w := &mockWriter{
logged: []string{},
msgChan: msgChan,
getChan: getChan,
clearChan: clearChan,
closeChan: closeChan,
}
go func() {
for {
select {
case logMsg := <-msgChan:
w.logged = append(w.logged, logMsg)
case getChan <- w.logged:
case <-clearChan:
w.logged = []string{}
case <-closeChan:
close(getChan)
return
}
}
}()
return w
} | [
"func",
"newMockWriter",
"(",
")",
"*",
"mockWriter",
"{",
"msgChan",
":=",
"make",
"(",
"chan",
"string",
")",
"\n",
"getChan",
":=",
"make",
"(",
"chan",
"[",
"]",
"string",
")",
"\n",
"clearChan",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"closeChan",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"w",
":=",
"&",
"mockWriter",
"{",
"logged",
":",
"[",
"]",
"string",
"{",
"}",
",",
"msgChan",
":",
"msgChan",
",",
"getChan",
":",
"getChan",
",",
"clearChan",
":",
"clearChan",
",",
"closeChan",
":",
"closeChan",
",",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"logMsg",
":=",
"<-",
"msgChan",
":",
"w",
".",
"logged",
"=",
"append",
"(",
"w",
".",
"logged",
",",
"logMsg",
")",
"\n",
"case",
"getChan",
"<-",
"w",
".",
"logged",
":",
"case",
"<-",
"clearChan",
":",
"w",
".",
"logged",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"case",
"<-",
"closeChan",
":",
"close",
"(",
"getChan",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"w",
"\n",
"}"
] | // newMockWriter returns a new mockWriter | [
"newMockWriter",
"returns",
"a",
"new",
"mockWriter"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/mock.go#L50-L77 | train |
letsencrypt/boulder | cmd/config.go | Pass | func (pc *PasswordConfig) Pass() (string, error) {
if pc.PasswordFile != "" {
contents, err := ioutil.ReadFile(pc.PasswordFile)
if err != nil {
return "", err
}
return strings.TrimRight(string(contents), "\n"), nil
}
return pc.Password, nil
} | go | func (pc *PasswordConfig) Pass() (string, error) {
if pc.PasswordFile != "" {
contents, err := ioutil.ReadFile(pc.PasswordFile)
if err != nil {
return "", err
}
return strings.TrimRight(string(contents), "\n"), nil
}
return pc.Password, nil
} | [
"func",
"(",
"pc",
"*",
"PasswordConfig",
")",
"Pass",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"pc",
".",
"PasswordFile",
"!=",
"\"\"",
"{",
"contents",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"pc",
".",
"PasswordFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"strings",
".",
"TrimRight",
"(",
"string",
"(",
"contents",
")",
",",
"\"\\n\"",
")",
",",
"nil",
"\n",
"}",
"\n",
"\\n",
"\n",
"}"
] | // Pass returns a password, either directly from the configuration
// struct or by reading from a specified file | [
"Pass",
"returns",
"a",
"password",
"either",
"directly",
"from",
"the",
"configuration",
"struct",
"or",
"by",
"reading",
"from",
"a",
"specified",
"file"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/config.go#L25-L34 | train |
letsencrypt/boulder | cmd/config.go | URL | func (d *DBConfig) URL() (string, error) {
if d.DBConnectFile != "" {
url, err := ioutil.ReadFile(d.DBConnectFile)
return strings.TrimSpace(string(url)), err
}
return d.DBConnect, nil
} | go | func (d *DBConfig) URL() (string, error) {
if d.DBConnectFile != "" {
url, err := ioutil.ReadFile(d.DBConnectFile)
return strings.TrimSpace(string(url)), err
}
return d.DBConnect, nil
} | [
"func",
"(",
"d",
"*",
"DBConfig",
")",
"URL",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"d",
".",
"DBConnectFile",
"!=",
"\"\"",
"{",
"url",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"d",
".",
"DBConnectFile",
")",
"\n",
"return",
"strings",
".",
"TrimSpace",
"(",
"string",
"(",
"url",
")",
")",
",",
"err",
"\n",
"}",
"\n",
"return",
"d",
".",
"DBConnect",
",",
"nil",
"\n",
"}"
] | // URL returns the DBConnect URL represented by this DBConfig object, either
// loading it from disk or returning a default value. Leading and trailing
// whitespace is stripped. | [
"URL",
"returns",
"the",
"DBConnect",
"URL",
"represented",
"by",
"this",
"DBConfig",
"object",
"either",
"loading",
"it",
"from",
"disk",
"or",
"returning",
"a",
"default",
"value",
".",
"Leading",
"and",
"trailing",
"whitespace",
"is",
"stripped",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/config.go#L58-L64 | train |
letsencrypt/boulder | cmd/config.go | CheckChallenges | func (pc PAConfig) CheckChallenges() error {
if len(pc.Challenges) == 0 {
return errors.New("empty challenges map in the Policy Authority config is not allowed")
}
for name := range pc.Challenges {
if !core.ValidChallenge(name) {
return fmt.Errorf("Invalid challenge in PA config: %s", name)
}
}
return nil
} | go | func (pc PAConfig) CheckChallenges() error {
if len(pc.Challenges) == 0 {
return errors.New("empty challenges map in the Policy Authority config is not allowed")
}
for name := range pc.Challenges {
if !core.ValidChallenge(name) {
return fmt.Errorf("Invalid challenge in PA config: %s", name)
}
}
return nil
} | [
"func",
"(",
"pc",
"PAConfig",
")",
"CheckChallenges",
"(",
")",
"error",
"{",
"if",
"len",
"(",
"pc",
".",
"Challenges",
")",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"empty challenges map in the Policy Authority config is not allowed\"",
")",
"\n",
"}",
"\n",
"for",
"name",
":=",
"range",
"pc",
".",
"Challenges",
"{",
"if",
"!",
"core",
".",
"ValidChallenge",
"(",
"name",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Invalid challenge in PA config: %s\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CheckChallenges checks whether the list of challenges in the PA config
// actually contains valid challenge names | [
"CheckChallenges",
"checks",
"whether",
"the",
"list",
"of",
"challenges",
"in",
"the",
"PA",
"config",
"actually",
"contains",
"valid",
"challenge",
"names"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/config.go#L89-L99 | train |
letsencrypt/boulder | cmd/config.go | UnmarshalJSON | func (d *ConfigDuration) UnmarshalJSON(b []byte) error {
s := ""
err := json.Unmarshal(b, &s)
if err != nil {
if _, ok := err.(*json.UnmarshalTypeError); ok {
return ErrDurationMustBeString
}
return err
}
dd, err := time.ParseDuration(s)
d.Duration = dd
return err
} | go | func (d *ConfigDuration) UnmarshalJSON(b []byte) error {
s := ""
err := json.Unmarshal(b, &s)
if err != nil {
if _, ok := err.(*json.UnmarshalTypeError); ok {
return ErrDurationMustBeString
}
return err
}
dd, err := time.ParseDuration(s)
d.Duration = dd
return err
} | [
"func",
"(",
"d",
"*",
"ConfigDuration",
")",
"UnmarshalJSON",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"s",
":=",
"\"\"",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"json",
".",
"UnmarshalTypeError",
")",
";",
"ok",
"{",
"return",
"ErrDurationMustBeString",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"dd",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"s",
")",
"\n",
"d",
".",
"Duration",
"=",
"dd",
"\n",
"return",
"err",
"\n",
"}"
] | // UnmarshalJSON parses a string into a ConfigDuration using
// time.ParseDuration. If the input does not unmarshal as a
// string, then UnmarshalJSON returns ErrDurationMustBeString. | [
"UnmarshalJSON",
"parses",
"a",
"string",
"into",
"a",
"ConfigDuration",
"using",
"time",
".",
"ParseDuration",
".",
"If",
"the",
"input",
"does",
"not",
"unmarshal",
"as",
"a",
"string",
"then",
"UnmarshalJSON",
"returns",
"ErrDurationMustBeString",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/config.go#L210-L222 | train |
letsencrypt/boulder | cmd/config.go | MarshalJSON | func (d ConfigDuration) MarshalJSON() ([]byte, error) {
return []byte(d.Duration.String()), nil
} | go | func (d ConfigDuration) MarshalJSON() ([]byte, error) {
return []byte(d.Duration.String()), nil
} | [
"func",
"(",
"d",
"ConfigDuration",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"[",
"]",
"byte",
"(",
"d",
".",
"Duration",
".",
"String",
"(",
")",
")",
",",
"nil",
"\n",
"}"
] | // MarshalJSON returns the string form of the duration, as a byte array. | [
"MarshalJSON",
"returns",
"the",
"string",
"form",
"of",
"the",
"duration",
"as",
"a",
"byte",
"array",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/config.go#L225-L227 | train |
letsencrypt/boulder | cmd/config.go | Setup | func (ts *TemporalSet) Setup() error {
if ts.Name == "" {
return errors.New("Name cannot be empty")
}
if len(ts.Shards) == 0 {
return errors.New("temporal set contains no shards")
}
for i := range ts.Shards {
if ts.Shards[i].WindowEnd.Before(ts.Shards[i].WindowStart) ||
ts.Shards[i].WindowEnd.Equal(ts.Shards[i].WindowStart) {
return errors.New("WindowStart must be before WindowEnd")
}
}
return nil
} | go | func (ts *TemporalSet) Setup() error {
if ts.Name == "" {
return errors.New("Name cannot be empty")
}
if len(ts.Shards) == 0 {
return errors.New("temporal set contains no shards")
}
for i := range ts.Shards {
if ts.Shards[i].WindowEnd.Before(ts.Shards[i].WindowStart) ||
ts.Shards[i].WindowEnd.Equal(ts.Shards[i].WindowStart) {
return errors.New("WindowStart must be before WindowEnd")
}
}
return nil
} | [
"func",
"(",
"ts",
"*",
"TemporalSet",
")",
"Setup",
"(",
")",
"error",
"{",
"if",
"ts",
".",
"Name",
"==",
"\"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"Name cannot be empty\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ts",
".",
"Shards",
")",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"temporal set contains no shards\"",
")",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"ts",
".",
"Shards",
"{",
"if",
"ts",
".",
"Shards",
"[",
"i",
"]",
".",
"WindowEnd",
".",
"Before",
"(",
"ts",
".",
"Shards",
"[",
"i",
"]",
".",
"WindowStart",
")",
"||",
"ts",
".",
"Shards",
"[",
"i",
"]",
".",
"WindowEnd",
".",
"Equal",
"(",
"ts",
".",
"Shards",
"[",
"i",
"]",
".",
"WindowStart",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"WindowStart must be before WindowEnd\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Setup initializes the TemporalSet by parsing the start and end dates
// and verifying WindowEnd > WindowStart | [
"Setup",
"initializes",
"the",
"TemporalSet",
"by",
"parsing",
"the",
"start",
"and",
"end",
"dates",
"and",
"verifying",
"WindowEnd",
">",
"WindowStart"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/config.go#L299-L313 | train |
letsencrypt/boulder | cmd/config.go | pick | func (ts *TemporalSet) pick(exp time.Time) (*LogShard, error) {
for _, shard := range ts.Shards {
if exp.Before(shard.WindowStart) {
continue
}
if !exp.Before(shard.WindowEnd) {
continue
}
return &shard, nil
}
return nil, fmt.Errorf("no valid shard available for temporal set %q for expiration date %q", ts.Name, exp)
} | go | func (ts *TemporalSet) pick(exp time.Time) (*LogShard, error) {
for _, shard := range ts.Shards {
if exp.Before(shard.WindowStart) {
continue
}
if !exp.Before(shard.WindowEnd) {
continue
}
return &shard, nil
}
return nil, fmt.Errorf("no valid shard available for temporal set %q for expiration date %q", ts.Name, exp)
} | [
"func",
"(",
"ts",
"*",
"TemporalSet",
")",
"pick",
"(",
"exp",
"time",
".",
"Time",
")",
"(",
"*",
"LogShard",
",",
"error",
")",
"{",
"for",
"_",
",",
"shard",
":=",
"range",
"ts",
".",
"Shards",
"{",
"if",
"exp",
".",
"Before",
"(",
"shard",
".",
"WindowStart",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"exp",
".",
"Before",
"(",
"shard",
".",
"WindowEnd",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"&",
"shard",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"no valid shard available for temporal set %q for expiration date %q\"",
",",
"ts",
".",
"Name",
",",
"exp",
")",
"\n",
"}"
] | // pick chooses the correct shard from a TemporalSet to use for the given
// expiration time. In the case where two shards have overlapping windows
// the earlier of the two shards will be chosen. | [
"pick",
"chooses",
"the",
"correct",
"shard",
"from",
"a",
"TemporalSet",
"to",
"use",
"for",
"the",
"given",
"expiration",
"time",
".",
"In",
"the",
"case",
"where",
"two",
"shards",
"have",
"overlapping",
"windows",
"the",
"earlier",
"of",
"the",
"two",
"shards",
"will",
"be",
"chosen",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/config.go#L318-L329 | train |
letsencrypt/boulder | cmd/config.go | Info | func (ld LogDescription) Info(exp time.Time) (string, string, error) {
if ld.TemporalSet == nil {
return ld.URI, ld.Key, nil
}
shard, err := ld.TemporalSet.pick(exp)
if err != nil {
return "", "", err
}
return shard.URI, shard.Key, nil
} | go | func (ld LogDescription) Info(exp time.Time) (string, string, error) {
if ld.TemporalSet == nil {
return ld.URI, ld.Key, nil
}
shard, err := ld.TemporalSet.pick(exp)
if err != nil {
return "", "", err
}
return shard.URI, shard.Key, nil
} | [
"func",
"(",
"ld",
"LogDescription",
")",
"Info",
"(",
"exp",
"time",
".",
"Time",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"if",
"ld",
".",
"TemporalSet",
"==",
"nil",
"{",
"return",
"ld",
".",
"URI",
",",
"ld",
".",
"Key",
",",
"nil",
"\n",
"}",
"\n",
"shard",
",",
"err",
":=",
"ld",
".",
"TemporalSet",
".",
"pick",
"(",
"exp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"shard",
".",
"URI",
",",
"shard",
".",
"Key",
",",
"nil",
"\n",
"}"
] | // Info returns the URI and key of the log, either from a plain log description
// or from the earliest valid shard from a temporal log set | [
"Info",
"returns",
"the",
"URI",
"and",
"key",
"of",
"the",
"log",
"either",
"from",
"a",
"plain",
"log",
"description",
"or",
"from",
"the",
"earliest",
"valid",
"shard",
"from",
"a",
"temporal",
"log",
"set"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/config.go#L344-L353 | train |
letsencrypt/boulder | grpc/balancer.go | Resolve | func (sr *staticResolver) Resolve(target string) (naming.Watcher, error) {
return sr, nil
} | go | func (sr *staticResolver) Resolve(target string) (naming.Watcher, error) {
return sr, nil
} | [
"func",
"(",
"sr",
"*",
"staticResolver",
")",
"Resolve",
"(",
"target",
"string",
")",
"(",
"naming",
".",
"Watcher",
",",
"error",
")",
"{",
"return",
"sr",
",",
"nil",
"\n",
"}"
] | // Resolve just returns the staticResolver it was called from as it satisfies
// both the naming.Resolver and naming.Watcher interfaces | [
"Resolve",
"just",
"returns",
"the",
"staticResolver",
"it",
"was",
"called",
"from",
"as",
"it",
"satisfies",
"both",
"the",
"naming",
".",
"Resolver",
"and",
"naming",
".",
"Watcher",
"interfaces"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/balancer.go#L26-L28 | train |
letsencrypt/boulder | grpc/balancer.go | Next | func (sr *staticResolver) Next() ([]*naming.Update, error) {
if sr.addresses != nil {
addrs := sr.addresses
sr.addresses = nil
return addrs, nil
}
// Since staticResolver.Next is called in a tight loop block forever
// after returning the initial set of addresses
forever := make(chan struct{})
<-forever
return nil, nil
} | go | func (sr *staticResolver) Next() ([]*naming.Update, error) {
if sr.addresses != nil {
addrs := sr.addresses
sr.addresses = nil
return addrs, nil
}
// Since staticResolver.Next is called in a tight loop block forever
// after returning the initial set of addresses
forever := make(chan struct{})
<-forever
return nil, nil
} | [
"func",
"(",
"sr",
"*",
"staticResolver",
")",
"Next",
"(",
")",
"(",
"[",
"]",
"*",
"naming",
".",
"Update",
",",
"error",
")",
"{",
"if",
"sr",
".",
"addresses",
"!=",
"nil",
"{",
"addrs",
":=",
"sr",
".",
"addresses",
"\n",
"sr",
".",
"addresses",
"=",
"nil",
"\n",
"return",
"addrs",
",",
"nil",
"\n",
"}",
"\n",
"forever",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"<-",
"forever",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // Next is called in a loop by grpc.RoundRobin expecting updates to which addresses are
// appropriate. Since we just want to return a static list once return a list on the first
// call then block forever on the second instead of sitting in a tight loop | [
"Next",
"is",
"called",
"in",
"a",
"loop",
"by",
"grpc",
".",
"RoundRobin",
"expecting",
"updates",
"to",
"which",
"addresses",
"are",
"appropriate",
".",
"Since",
"we",
"just",
"want",
"to",
"return",
"a",
"static",
"list",
"once",
"return",
"a",
"list",
"on",
"the",
"first",
"call",
"then",
"block",
"forever",
"on",
"the",
"second",
"instead",
"of",
"sitting",
"in",
"a",
"tight",
"loop"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/balancer.go#L33-L44 | train |
letsencrypt/boulder | wfe/wfe.go | NewAuthorization | func (wfe *WebFrontEndImpl) NewAuthorization(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
body, _, currReg, prob := wfe.verifyPOST(ctx, logEvent, request, true, core.ResourceNewAuthz)
addRequesterHeader(response, logEvent.Requester)
if prob != nil {
// verifyPOST handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
return
}
// Any version of the agreement is acceptable here. Version match is enforced in
// wfe.Registration when agreeing the first time. Agreement updates happen
// by mailing subscribers and don't require a registration update.
if currReg.Agreement == "" {
wfe.sendError(response, logEvent, probs.Unauthorized("Must agree to subscriber agreement before any further actions"), nil)
return
}
var init core.Authorization
if err := json.Unmarshal(body, &init); err != nil {
wfe.sendError(response, logEvent, probs.Malformed("Error unmarshaling JSON"), err)
return
}
if init.Identifier.Type == core.IdentifierDNS {
logEvent.DNSName = init.Identifier.Value
}
// Create new authz and return
authz, err := wfe.RA.NewAuthorization(ctx, init, currReg.ID)
if err != nil {
wfe.sendError(response, logEvent, web.ProblemDetailsForError(err, "Error creating new authz"), err)
return
}
logEvent.Created = authz.ID
// Make a URL for this authz, then blow away the ID and RegID before serializing
authzURL := web.RelativeEndpoint(request, authzPath+string(authz.ID))
wfe.prepAuthorizationForDisplay(request, &authz)
response.Header().Add("Location", authzURL)
response.Header().Add("Link", link(web.RelativeEndpoint(request, newCertPath), "next"))
err = wfe.writeJsonResponse(response, logEvent, http.StatusCreated, authz)
if err != nil {
// ServerInternal because we generated the authz, it should be OK
wfe.sendError(response, logEvent, probs.ServerInternal("Error marshaling authz"), err)
return
}
} | go | func (wfe *WebFrontEndImpl) NewAuthorization(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
body, _, currReg, prob := wfe.verifyPOST(ctx, logEvent, request, true, core.ResourceNewAuthz)
addRequesterHeader(response, logEvent.Requester)
if prob != nil {
// verifyPOST handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
return
}
// Any version of the agreement is acceptable here. Version match is enforced in
// wfe.Registration when agreeing the first time. Agreement updates happen
// by mailing subscribers and don't require a registration update.
if currReg.Agreement == "" {
wfe.sendError(response, logEvent, probs.Unauthorized("Must agree to subscriber agreement before any further actions"), nil)
return
}
var init core.Authorization
if err := json.Unmarshal(body, &init); err != nil {
wfe.sendError(response, logEvent, probs.Malformed("Error unmarshaling JSON"), err)
return
}
if init.Identifier.Type == core.IdentifierDNS {
logEvent.DNSName = init.Identifier.Value
}
// Create new authz and return
authz, err := wfe.RA.NewAuthorization(ctx, init, currReg.ID)
if err != nil {
wfe.sendError(response, logEvent, web.ProblemDetailsForError(err, "Error creating new authz"), err)
return
}
logEvent.Created = authz.ID
// Make a URL for this authz, then blow away the ID and RegID before serializing
authzURL := web.RelativeEndpoint(request, authzPath+string(authz.ID))
wfe.prepAuthorizationForDisplay(request, &authz)
response.Header().Add("Location", authzURL)
response.Header().Add("Link", link(web.RelativeEndpoint(request, newCertPath), "next"))
err = wfe.writeJsonResponse(response, logEvent, http.StatusCreated, authz)
if err != nil {
// ServerInternal because we generated the authz, it should be OK
wfe.sendError(response, logEvent, probs.ServerInternal("Error marshaling authz"), err)
return
}
} | [
"func",
"(",
"wfe",
"*",
"WebFrontEndImpl",
")",
"NewAuthorization",
"(",
"ctx",
"context",
".",
"Context",
",",
"logEvent",
"*",
"web",
".",
"RequestEvent",
",",
"response",
"http",
".",
"ResponseWriter",
",",
"request",
"*",
"http",
".",
"Request",
")",
"{",
"body",
",",
"_",
",",
"currReg",
",",
"prob",
":=",
"wfe",
".",
"verifyPOST",
"(",
"ctx",
",",
"logEvent",
",",
"request",
",",
"true",
",",
"core",
".",
"ResourceNewAuthz",
")",
"\n",
"addRequesterHeader",
"(",
"response",
",",
"logEvent",
".",
"Requester",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"prob",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"currReg",
".",
"Agreement",
"==",
"\"\"",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Unauthorized",
"(",
"\"Must agree to subscriber agreement before any further actions\"",
")",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"init",
"core",
".",
"Authorization",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"init",
")",
";",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Malformed",
"(",
"\"Error unmarshaling JSON\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"init",
".",
"Identifier",
".",
"Type",
"==",
"core",
".",
"IdentifierDNS",
"{",
"logEvent",
".",
"DNSName",
"=",
"init",
".",
"Identifier",
".",
"Value",
"\n",
"}",
"\n",
"authz",
",",
"err",
":=",
"wfe",
".",
"RA",
".",
"NewAuthorization",
"(",
"ctx",
",",
"init",
",",
"currReg",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"web",
".",
"ProblemDetailsForError",
"(",
"err",
",",
"\"Error creating new authz\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"logEvent",
".",
"Created",
"=",
"authz",
".",
"ID",
"\n",
"authzURL",
":=",
"web",
".",
"RelativeEndpoint",
"(",
"request",
",",
"authzPath",
"+",
"string",
"(",
"authz",
".",
"ID",
")",
")",
"\n",
"wfe",
".",
"prepAuthorizationForDisplay",
"(",
"request",
",",
"&",
"authz",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"Location\"",
",",
"authzURL",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"Link\"",
",",
"link",
"(",
"web",
".",
"RelativeEndpoint",
"(",
"request",
",",
"newCertPath",
")",
",",
"\"next\"",
")",
")",
"\n",
"err",
"=",
"wfe",
".",
"writeJsonResponse",
"(",
"response",
",",
"logEvent",
",",
"http",
".",
"StatusCreated",
",",
"authz",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"ServerInternal",
"(",
"\"Error marshaling authz\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // NewAuthorization is used by clients to submit a new ID Authorization | [
"NewAuthorization",
"is",
"used",
"by",
"clients",
"to",
"submit",
"a",
"new",
"ID",
"Authorization"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe/wfe.go#L656-L702 | train |
letsencrypt/boulder | iana/iana.go | ExtractSuffix | func ExtractSuffix(name string) (string, error) {
if name == "" {
return "", fmt.Errorf("Blank name argument passed to ExtractSuffix")
}
rule := publicsuffix.DefaultList.Find(name, &publicsuffix.FindOptions{IgnorePrivate: true, DefaultRule: nil})
if rule == nil {
return "", fmt.Errorf("Domain %s has no IANA TLD", name)
}
suffix := rule.Decompose(name)[1]
// If the TLD is empty, it means name is actually a suffix.
// In fact, decompose returns an array of empty strings in this case.
if suffix == "" {
suffix = name
}
return suffix, nil
} | go | func ExtractSuffix(name string) (string, error) {
if name == "" {
return "", fmt.Errorf("Blank name argument passed to ExtractSuffix")
}
rule := publicsuffix.DefaultList.Find(name, &publicsuffix.FindOptions{IgnorePrivate: true, DefaultRule: nil})
if rule == nil {
return "", fmt.Errorf("Domain %s has no IANA TLD", name)
}
suffix := rule.Decompose(name)[1]
// If the TLD is empty, it means name is actually a suffix.
// In fact, decompose returns an array of empty strings in this case.
if suffix == "" {
suffix = name
}
return suffix, nil
} | [
"func",
"ExtractSuffix",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"name",
"==",
"\"\"",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Blank name argument passed to ExtractSuffix\"",
")",
"\n",
"}",
"\n",
"rule",
":=",
"publicsuffix",
".",
"DefaultList",
".",
"Find",
"(",
"name",
",",
"&",
"publicsuffix",
".",
"FindOptions",
"{",
"IgnorePrivate",
":",
"true",
",",
"DefaultRule",
":",
"nil",
"}",
")",
"\n",
"if",
"rule",
"==",
"nil",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Domain %s has no IANA TLD\"",
",",
"name",
")",
"\n",
"}",
"\n",
"suffix",
":=",
"rule",
".",
"Decompose",
"(",
"name",
")",
"[",
"1",
"]",
"\n",
"if",
"suffix",
"==",
"\"\"",
"{",
"suffix",
"=",
"name",
"\n",
"}",
"\n",
"return",
"suffix",
",",
"nil",
"\n",
"}"
] | // ExtractSuffix returns the public suffix of the domain using only the "ICANN"
// section of the Public Suffix List database.
// If the domain does not end in a suffix that belongs to an IANA-assigned
// domain, ExtractSuffix returns an error. | [
"ExtractSuffix",
"returns",
"the",
"public",
"suffix",
"of",
"the",
"domain",
"using",
"only",
"the",
"ICANN",
"section",
"of",
"the",
"Public",
"Suffix",
"List",
"database",
".",
"If",
"the",
"domain",
"does",
"not",
"end",
"in",
"a",
"suffix",
"that",
"belongs",
"to",
"an",
"IANA",
"-",
"assigned",
"domain",
"ExtractSuffix",
"returns",
"an",
"error",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/iana/iana.go#L13-L32 | train |
letsencrypt/boulder | web/probs.go | ProblemDetailsForError | func ProblemDetailsForError(err error, msg string) *probs.ProblemDetails {
switch e := err.(type) {
case *probs.ProblemDetails:
return e
case *berrors.BoulderError:
return problemDetailsForBoulderError(e, msg)
default:
// Internal server error messages may include sensitive data, so we do
// not include it.
return probs.ServerInternal(msg)
}
} | go | func ProblemDetailsForError(err error, msg string) *probs.ProblemDetails {
switch e := err.(type) {
case *probs.ProblemDetails:
return e
case *berrors.BoulderError:
return problemDetailsForBoulderError(e, msg)
default:
// Internal server error messages may include sensitive data, so we do
// not include it.
return probs.ServerInternal(msg)
}
} | [
"func",
"ProblemDetailsForError",
"(",
"err",
"error",
",",
"msg",
"string",
")",
"*",
"probs",
".",
"ProblemDetails",
"{",
"switch",
"e",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"probs",
".",
"ProblemDetails",
":",
"return",
"e",
"\n",
"case",
"*",
"berrors",
".",
"BoulderError",
":",
"return",
"problemDetailsForBoulderError",
"(",
"e",
",",
"msg",
")",
"\n",
"default",
":",
"return",
"probs",
".",
"ServerInternal",
"(",
"msg",
")",
"\n",
"}",
"\n",
"}"
] | // problemDetailsForError turns an error into a ProblemDetails with the special
// case of returning the same error back if its already a ProblemDetails. If the
// error is of an type unknown to ProblemDetailsForError, it will return a
// ServerInternal ProblemDetails. | [
"problemDetailsForError",
"turns",
"an",
"error",
"into",
"a",
"ProblemDetails",
"with",
"the",
"special",
"case",
"of",
"returning",
"the",
"same",
"error",
"back",
"if",
"its",
"already",
"a",
"ProblemDetails",
".",
"If",
"the",
"error",
"is",
"of",
"an",
"type",
"unknown",
"to",
"ProblemDetailsForError",
"it",
"will",
"return",
"a",
"ServerInternal",
"ProblemDetails",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/web/probs.go#L47-L58 | train |
letsencrypt/boulder | ratelimit/rate-limits.go | GetThreshold | func (rlp *RateLimitPolicy) GetThreshold(key string, regID int64) int {
regOverride, regOverrideExists := rlp.RegistrationOverrides[regID]
keyOverride, keyOverrideExists := rlp.Overrides[key]
if regOverrideExists && !keyOverrideExists {
// If there is a regOverride and no keyOverride use the regOverride
return regOverride
} else if !regOverrideExists && keyOverrideExists {
// If there is a keyOverride and no regOverride use the keyOverride
return keyOverride
} else if regOverrideExists && keyOverrideExists {
// If there is both a regOverride and a keyOverride use whichever is larger.
if regOverride > keyOverride {
return regOverride
} else {
return keyOverride
}
}
// Otherwise there was no regOverride and no keyOverride, use the base
// Threshold
return rlp.Threshold
} | go | func (rlp *RateLimitPolicy) GetThreshold(key string, regID int64) int {
regOverride, regOverrideExists := rlp.RegistrationOverrides[regID]
keyOverride, keyOverrideExists := rlp.Overrides[key]
if regOverrideExists && !keyOverrideExists {
// If there is a regOverride and no keyOverride use the regOverride
return regOverride
} else if !regOverrideExists && keyOverrideExists {
// If there is a keyOverride and no regOverride use the keyOverride
return keyOverride
} else if regOverrideExists && keyOverrideExists {
// If there is both a regOverride and a keyOverride use whichever is larger.
if regOverride > keyOverride {
return regOverride
} else {
return keyOverride
}
}
// Otherwise there was no regOverride and no keyOverride, use the base
// Threshold
return rlp.Threshold
} | [
"func",
"(",
"rlp",
"*",
"RateLimitPolicy",
")",
"GetThreshold",
"(",
"key",
"string",
",",
"regID",
"int64",
")",
"int",
"{",
"regOverride",
",",
"regOverrideExists",
":=",
"rlp",
".",
"RegistrationOverrides",
"[",
"regID",
"]",
"\n",
"keyOverride",
",",
"keyOverrideExists",
":=",
"rlp",
".",
"Overrides",
"[",
"key",
"]",
"\n",
"if",
"regOverrideExists",
"&&",
"!",
"keyOverrideExists",
"{",
"return",
"regOverride",
"\n",
"}",
"else",
"if",
"!",
"regOverrideExists",
"&&",
"keyOverrideExists",
"{",
"return",
"keyOverride",
"\n",
"}",
"else",
"if",
"regOverrideExists",
"&&",
"keyOverrideExists",
"{",
"if",
"regOverride",
">",
"keyOverride",
"{",
"return",
"regOverride",
"\n",
"}",
"else",
"{",
"return",
"keyOverride",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"rlp",
".",
"Threshold",
"\n",
"}"
] | // GetThreshold returns the threshold for this rate limit, taking into account
// any overrides for `key` or `regID`. If both `key` and `regID` have an
// override the largest of the two will be used. | [
"GetThreshold",
"returns",
"the",
"threshold",
"for",
"this",
"rate",
"limit",
"taking",
"into",
"account",
"any",
"overrides",
"for",
"key",
"or",
"regID",
".",
"If",
"both",
"key",
"and",
"regID",
"have",
"an",
"override",
"the",
"largest",
"of",
"the",
"two",
"will",
"be",
"used",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ratelimit/rate-limits.go#L192-L214 | train |
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",
"(",
"\"%s: error unmarshaling JSON %q: %s\"",
",",
"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",
",",
"\"SELECT \"",
"+",
"regFields",
"+",
"\" FROM registrations \"",
"+",
"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",
",",
"\"SELECT id, identifier, registrationID, status, expires, LockCol FROM pendingAuthorizations \"",
"+",
"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",
",",
"\"SELECT \"",
"+",
"authzFields",
"+",
"\" FROM authz \"",
"+",
"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",
",",
"\"SELECT id, sctVersion, logID, timestamp, extensions, signature, certificateSerial, LockCol FROM sctReceipts \"",
"+",
"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",
",",
"\"SELECT \"",
"+",
"certFields",
"+",
"\" FROM certificates \"",
"+",
"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",
",",
"\"SELECT \"",
"+",
"certFields",
"+",
"\" FROM certificates \"",
"+",
"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",
",",
"\"SELECT \"",
"+",
"certStatusFields",
"+",
"\" FROM certificateStatus \"",
"+",
"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",
",",
"\"SELECT \"",
"+",
"certStatusFields",
"+",
"\" FROM certificateStatus \"",
"+",
"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",
"sha",
",",
"err",
":=",
"core",
".",
"KeyDigest",
"(",
"r",
".",
"Key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"r",
".",
"InitialIP",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"initialIP was nil\"",
")",
"\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",
"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",
"{",
"reqTimeUnixNanos",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"clientReqTime",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"berrors",
".",
"InternalServerError",
"(",
"\"grpc metadata had illegal %s value: %q - %s\"",
",",
"clientRequestTimeKey",
",",
"clientReqTime",
",",
"err",
")",
"\n",
"}",
"\n",
"reqTime",
":=",
"time",
".",
"Unix",
"(",
"0",
",",
"reqTimeUnixNanos",
")",
"\n",
"elapsed",
":=",
"si",
".",
"clk",
".",
"Since",
"(",
"reqTime",
")",
"\n",
"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",
"(",
"\"\\tEncoded curve parameters for %s: %X\\n\"",
",",
"\\t",
",",
"\\n",
")",
"\n",
"curve",
".",
"Params",
"(",
")",
".",
"Name",
"\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",
"(",
"\"Returned EC parameters doesn't match expected curve\"",
")",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"\\tX: %X\\n\"",
",",
"\\t",
")",
"\n",
"\\n",
"\n",
"pubKey",
".",
"X",
".",
"Bytes",
"(",
")",
"\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",
"(",
"\"failed to construct nonce: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"\\tConstructed nonce: %d (%X)\\n\"",
",",
"\\t",
",",
"\\n",
")",
"\n",
"big",
".",
"NewInt",
"(",
"0",
")",
".",
"SetBytes",
"(",
"nonce",
")",
"\n",
"nonce",
"\n",
"hashFunc",
":=",
"curveToHash",
"[",
"pub",
".",
"Curve",
".",
"Params",
"(",
")",
"]",
".",
"New",
"(",
")",
"\n",
"hashFunc",
".",
"Write",
"(",
"nonce",
")",
"\n",
"digest",
":=",
"hashFunc",
".",
"Sum",
"(",
"nil",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"\\tMessage %s hash: %X\\n\"",
",",
"\\t",
",",
"\\n",
")",
"\n",
"hashToString",
"[",
"curveToHash",
"[",
"pub",
".",
"Curve",
".",
"Params",
"(",
")",
"]",
"]",
"\n",
"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",
"(",
"\"\\tMessage signature: %X\\n\"",
",",
"\\t",
")",
"\n",
"\\n",
"\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",
"(",
"\"curve %q not supported\"",
",",
"curveStr",
")",
"\n",
"}",
"\n",
"keyID",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"keyID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"Generating ECDSA key with curve %s and ID %x\\n\"",
",",
"\\n",
",",
"curveStr",
")",
"\n",
"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",
"(",
"\"Key generated\"",
")",
"\n",
"log",
".",
"Println",
"(",
"\"Extracting public key\"",
")",
"\n",
"pk",
",",
"err",
":=",
"ecPub",
"(",
"ctx",
",",
"session",
",",
"pub",
",",
"curve",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"\"Extracted public key\"",
")",
"\n",
"log",
".",
"Println",
"(",
"\"Verifying public key\"",
")",
"\n",
"err",
"=",
"ecVerify",
"(",
"ctx",
",",
"session",
",",
"priv",
",",
"pk",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"\"Key verified\"",
")",
"\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",
"{",
"deadline",
"=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"100",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"else",
"{",
"deadline",
"=",
"deadline",
".",
"Add",
"(",
"-",
"10",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"}",
"\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithDeadline",
"(",
"ctx",
",",
"deadline",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"origHost",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"origAddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"origHost",
"!=",
"d",
".",
"hostname",
"{",
"return",
"nil",
",",
"&",
"dialerMismatchError",
"{",
"dialerHost",
":",
"d",
".",
"hostname",
",",
"dialerIP",
":",
"d",
".",
"ip",
".",
"String",
"(",
")",
",",
"dialerPort",
":",
"d",
".",
"port",
",",
"host",
":",
"origHost",
",",
"}",
"\n",
"}",
"\n",
"targetAddr",
":=",
"net",
".",
"JoinHostPort",
"(",
"d",
".",
"ip",
".",
"String",
"(",
")",
",",
"strconv",
".",
"Itoa",
"(",
"d",
".",
"port",
")",
")",
"\n",
"throwAwayDialer",
":=",
"&",
"net",
".",
"Dialer",
"{",
"Timeout",
":",
"d",
".",
"timeout",
",",
"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",
",",
"TLSClientConfig",
":",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"true",
"}",
",",
"DisableKeepAlives",
":",
"true",
",",
"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",
")",
"{",
"addrs",
",",
"err",
":=",
"va",
".",
"getAddrs",
"(",
"ctx",
",",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"berrors",
".",
"ConnectionFailureError",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"target",
":=",
"&",
"httpValidationTarget",
"{",
"host",
":",
"host",
",",
"port",
":",
"port",
",",
"path",
":",
"path",
",",
"query",
":",
"query",
",",
"available",
":",
"addrs",
",",
"}",
"\n",
"v4Addrs",
",",
"v6Addrs",
":=",
"availableAddresses",
"(",
"addrs",
")",
"\n",
"hasV6Addrs",
":=",
"len",
"(",
"v6Addrs",
")",
">",
"0",
"\n",
"hasV4Addrs",
":=",
"len",
"(",
"v4Addrs",
")",
">",
"0",
"\n",
"if",
"!",
"hasV6Addrs",
"&&",
"!",
"hasV4Addrs",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"host %q has no IPv4 or IPv6 addresses\"",
",",
"host",
")",
"\n",
"}",
"else",
"if",
"!",
"hasV6Addrs",
"&&",
"hasV4Addrs",
"{",
"target",
".",
"next",
"=",
"[",
"]",
"net",
".",
"IP",
"{",
"v4Addrs",
"[",
"0",
"]",
"}",
"\n",
"}",
"else",
"if",
"hasV6Addrs",
"&&",
"hasV4Addrs",
"{",
"target",
".",
"next",
"=",
"[",
"]",
"net",
".",
"IP",
"{",
"v6Addrs",
"[",
"0",
"]",
",",
"v4Addrs",
"[",
"0",
"]",
"}",
"\n",
"}",
"else",
"if",
"hasV6Addrs",
"&&",
"!",
"hasV4Addrs",
"{",
"target",
".",
"next",
"=",
"[",
"]",
"net",
".",
"IP",
"{",
"v6Addrs",
"[",
"0",
"]",
"}",
"\n",
"}",
"\n",
"_",
"=",
"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",
")",
"{",
"if",
"req",
"==",
"nil",
"{",
"return",
"\"\"",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"redirect HTTP request was nil\"",
")",
"\n",
"}",
"\n",
"reqScheme",
":=",
"req",
".",
"URL",
".",
"Scheme",
"\n",
"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",
")",
"\n",
"}",
"\n",
"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",
"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",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"reqScheme",
"==",
"\"http\"",
"{",
"reqPort",
"=",
"va",
".",
"httpPort",
"\n",
"}",
"else",
"if",
"reqScheme",
"==",
"\"https\"",
"{",
"reqPort",
"=",
"va",
".",
"httpsPort",
"\n",
"}",
"else",
"{",
"return",
"\"\"",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"unable to determine redirect HTTP request port\"",
")",
"\n",
"}",
"\n",
"if",
"reqHost",
"==",
"\"\"",
"{",
"return",
"\"\"",
",",
"0",
",",
"berrors",
".",
"ConnectionFailureError",
"(",
"\"Invalid empty hostname in redirect target\"",
")",
"\n",
"}",
"\n",
"if",
"net",
".",
"ParseIP",
"(",
"reqHost",
")",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"0",
",",
"berrors",
".",
"ConnectionFailureError",
"(",
"\"Invalid host in redirect target %q. \"",
"+",
"\"Only domain names are supported, not IP addresses\"",
",",
"reqHost",
")",
"\n",
"}",
"\n",
"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",
",",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"iana",
".",
"ExtractSuffix",
"(",
"reqHost",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"0",
",",
"berrors",
".",
"ConnectionFailureError",
"(",
"\"Invalid hostname in redirect target, must end in IANA registered TLD\"",
")",
"\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",
"(",
"\"reqURL can not be nil\"",
")",
"\n",
"}",
"\n",
"if",
"target",
"==",
"nil",
"{",
"return",
"nil",
",",
"core",
".",
"ValidationRecord",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"httpValidationTarget can not be nil\"",
")",
"\n",
"}",
"\n",
"record",
":=",
"core",
".",
"ValidationRecord",
"{",
"Hostname",
":",
"target",
".",
"host",
",",
"Port",
":",
"strconv",
".",
"Itoa",
"(",
"target",
".",
"port",
")",
",",
"AddressesResolved",
":",
"target",
".",
"available",
",",
"URL",
":",
"reqURL",
",",
"}",
"\n",
"targetIP",
":=",
"target",
".",
"ip",
"(",
")",
"\n",
"if",
"targetIP",
"==",
"nil",
"{",
"return",
"nil",
",",
"record",
",",
"fmt",
".",
"Errorf",
"(",
"\"host %q has no IP addresses remaining to use\"",
",",
"target",
".",
"host",
")",
"\n",
"}",
"\n",
"record",
".",
"AddressUsed",
"=",
"targetIP",
"\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",
"{",
"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",
"(",
"\"%s: %s\"",
",",
"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",
"(",
"\"Issuer certificate was not provided in config.\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"pemBytes",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"pemBytes",
")",
"\n",
"if",
"block",
"==",
"nil",
"||",
"block",
".",
"Type",
"!=",
"\"CERTIFICATE\"",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"Invalid certificate value returned\"",
")",
"\n",
"return",
"\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",
"(",
"\"Versions: %s=(%s %s) Golang=(%s) BuildHost=(%s)\"",
",",
"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",
"sig",
":=",
"<-",
"sigChan",
"\n",
"if",
"logger",
"!=",
"nil",
"{",
"logger",
".",
"Infof",
"(",
"\"Caught %s\"",
",",
"signalToName",
"[",
"sig",
"]",
")",
"\n",
"}",
"\n",
"if",
"callback",
"!=",
"nil",
"{",
"callback",
"(",
")",
"\n",
"}",
"\n",
"if",
"logger",
"!=",
"nil",
"{",
"logger",
".",
"Info",
"(",
"\"Exiting\"",
")",
"\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",
"(",
"\"\"",
",",
"\"checkpoint-tmp\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"_",
"=",
"os",
".",
"RemoveAll",
"(",
"tmpDir",
")",
"}",
"(",
")",
"\n",
"tmp",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"tmpDir",
",",
"\"checkpoint-atomic\"",
")",
"\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",
"{",
"}",
"{",
"\"id\"",
":",
"initialID",
",",
"\"expires\"",
":",
"purgeBefore",
",",
"\"limit\"",
":",
"batchSize",
",",
"}",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"sql",
".",
"ErrNoRows",
"{",
"return",
"\"\"",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"Getting a batch: %s\"",
",",
"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",
"(",
"\"Deleting %s: %s\"",
",",
"id",
",",
"err",
")",
"\n",
"}",
"\n",
"numDeleted",
":=",
"atomic",
".",
"AddInt64",
"(",
"&",
"deleted",
",",
"1",
")",
"\n",
"if",
"checkpointFile",
"!=",
"\"\"",
"&&",
"numDeleted",
"%",
"1000",
"==",
"0",
"{",
"err",
"=",
"saveCheckpoint",
"(",
"checkpointFile",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"log",
".",
"AuditErrf",
"(",
"\"failed to checkpoint %q table at ID %q: %s\"",
",",
"table",
",",
"id",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"p",
".",
"log",
".",
"Infof",
"(",
"\"Deleted a total of %d expired authorizations from %s\"",
",",
"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",
":",
"\"ctpolicy_results\"",
",",
"Help",
":",
"\"Histogram of latencies of ctpolicy.GetSCTs calls with success/failure/deadlineExceeded labels\"",
",",
"Buckets",
":",
"metrics",
".",
"InternetFacingBuckets",
",",
"}",
",",
"[",
"]",
"string",
"{",
"\"result\"",
"}",
",",
")",
"\n",
"stats",
".",
"MustRegister",
"(",
"ctpolicyResults",
")",
"\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",
"(",
"\"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",
",",
"}",
"\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",
"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",
"if",
"count",
">=",
"limit",
".",
"GetThreshold",
"(",
"ip",
".",
"String",
"(",
")",
",",
"noRegistrationID",
")",
"{",
"return",
"berrors",
".",
"RateLimitError",
"(",
"\"too many registrations for this IP\"",
")",
"\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",
"{",
"exactRegLimit",
":=",
"ra",
".",
"rlPolicies",
".",
"RegistrationsPerIP",
"(",
")",
"\n",
"err",
":=",
"ra",
".",
"checkRegistrationIPLimit",
"(",
"ctx",
",",
"exactRegLimit",
",",
"ip",
",",
"ra",
".",
"SA",
".",
"CountRegistrationsByIP",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ra",
".",
"regByIPStats",
".",
"Inc",
"(",
"\"Exceeded\"",
",",
"1",
")",
"\n",
"ra",
".",
"log",
".",
"Infof",
"(",
"\"Rate limit exceeded, RegistrationsByIP, IP: %s\"",
",",
"ip",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"ra",
".",
"regByIPStats",
".",
"Inc",
"(",
"\"Pass\"",
",",
"1",
")",
"\n",
"if",
"ip",
".",
"To4",
"(",
")",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"fuzzyRegLimit",
":=",
"ra",
".",
"rlPolicies",
".",
"RegistrationsPerIPRange",
"(",
")",
"\n",
"err",
"=",
"ra",
".",
"checkRegistrationIPLimit",
"(",
"ctx",
",",
"fuzzyRegLimit",
",",
"ip",
",",
"ra",
".",
"SA",
".",
"CountRegistrationsByIPRange",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ra",
".",
"regByIPRangeStats",
".",
"Inc",
"(",
"\"Exceeded\"",
",",
"1",
")",
"\n",
"ra",
".",
"log",
".",
"Infof",
"(",
"\"Rate limit exceeded, RegistrationsByIPRange, IP: %s\"",
",",
"ip",
")",
"\n",
"return",
"berrors",
".",
"RateLimitError",
"(",
"\"too many registrations for this IP range\"",
")",
"\n",
"}",
"\n",
"ra",
".",
"regByIPRangeStats",
".",
"Inc",
"(",
"\"Pass\"",
",",
"1",
")",
"\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(®, 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(®, 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",
"(",
"\"invalid public key: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"ra",
".",
"checkRegistrationLimits",
"(",
"ctx",
",",
"init",
".",
"InitialIP",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"core",
".",
"Registration",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"reg",
":=",
"core",
".",
"Registration",
"{",
"Key",
":",
"init",
".",
"Key",
",",
"Status",
":",
"core",
".",
"StatusValid",
",",
"}",
"\n",
"_",
"=",
"mergeUpdate",
"(",
"&",
"reg",
",",
"init",
")",
"\n",
"reg",
".",
"InitialIP",
"=",
"init",
".",
"InitialIP",
"\n",
"if",
"err",
":=",
"ra",
".",
"validateContacts",
"(",
"ctx",
",",
"reg",
".",
"Contact",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"core",
".",
"Registration",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"reg",
",",
"err",
":=",
"ra",
".",
"SA",
".",
"NewRegistration",
"(",
"ctx",
",",
"reg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"core",
".",
"Registration",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"ra",
".",
"stats",
".",
"Inc",
"(",
"\"NewRegistrations\"",
",",
"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",
"(",
"\"invalid contact domain. Contact emails @%s are forbidden\"",
",",
"domain",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"iana",
".",
"ExtractSuffix",
"(",
"domain",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"berrors",
".",
"InvalidEmailError",
"(",
"\"email domain name does not end in a IANA suffix\"",
")",
"\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",
"noKey",
":=",
"\"\"",
"\n",
"if",
"count",
">=",
"limit",
".",
"GetThreshold",
"(",
"noKey",
",",
"acctID",
")",
"{",
"ra",
".",
"newOrderByRegIDStats",
".",
"Inc",
"(",
"\"Exceeded\"",
",",
"1",
")",
"\n",
"return",
"berrors",
".",
"RateLimitError",
"(",
"\"too many new orders recently\"",
")",
"\n",
"}",
"\n",
"ra",
".",
"newOrderByRegIDStats",
".",
"Inc",
"(",
"\"Pass\"",
",",
"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",
"authzs",
",",
"err",
":=",
"ra",
".",
"SA",
".",
"GetValidOrderAuthorizations",
"(",
"ctx",
",",
"&",
"sapb",
".",
"GetValidOrderAuthorizationsRequest",
"{",
"Id",
":",
"&",
"orderIDInt",
",",
"AcctID",
":",
"&",
"acctIDInt",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"berrors",
".",
"InternalServerError",
"(",
"\"error in GetValidOrderAuthorizations: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"names",
"=",
"core",
".",
"UniqueLowerNames",
"(",
"names",
")",
"\n",
"if",
"err",
"=",
"ra",
".",
"checkAuthorizationsCAA",
"(",
"ctx",
",",
"names",
",",
"authzs",
",",
"acctIDInt",
",",
"ra",
".",
"clk",
".",
"Now",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\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",
"(",
"\"error in GetValidAuthorizations: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
"=",
"ra",
".",
"checkAuthorizationsCAA",
"(",
"ctx",
",",
"names",
",",
"auths",
",",
"regID",
",",
"now",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\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",
"{",
"var",
"badNames",
"[",
"]",
"string",
"\n",
"var",
"recheckAuthzs",
"[",
"]",
"*",
"core",
".",
"Authorization",
"\n",
"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",
"(",
"\"found an authorization with a nil Expires field: id %s\"",
",",
"authz",
".",
"ID",
")",
"\n",
"}",
"else",
"if",
"authz",
".",
"Expires",
".",
"Before",
"(",
"now",
")",
"{",
"badNames",
"=",
"append",
"(",
"badNames",
",",
"name",
")",
"\n",
"}",
"else",
"if",
"authz",
".",
"Expires",
".",
"Before",
"(",
"caaRecheckTime",
")",
"{",
"recheckAuthzs",
"=",
"append",
"(",
"recheckAuthzs",
",",
"authz",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"recheckAuthzs",
")",
">",
"0",
"{",
"if",
"err",
":=",
"ra",
".",
"recheckCAA",
"(",
"ctx",
",",
"recheckAuthzs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"badNames",
")",
">",
"0",
"{",
"return",
"berrors",
".",
"UnauthorizedError",
"(",
"\"authorizations for these names not found or expired: %s\"",
",",
"strings",
".",
"Join",
"(",
"badNames",
",",
"\", \"",
")",
",",
")",
"\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",
"(",
"\"recheck_caa\"",
",",
"1",
")",
"\n",
"ra",
".",
"stats",
".",
"Inc",
"(",
"\"recheck_caa_authzs\"",
",",
"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",
"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",
"(",
"\"Internal error determining validation method for authorization ID %v (%v)\"",
",",
"authz",
".",
"ID",
",",
"name",
",",
")",
"\n",
"return",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"ra",
".",
"caa",
".",
"IsCAAValid",
"(",
"ctx",
",",
"&",
"vaPB",
".",
"IsCAAValidRequest",
"{",
"Domain",
":",
"&",
"name",
",",
"ValidationMethod",
":",
"&",
"method",
",",
"AccountURIID",
":",
"&",
"authz",
".",
"RegistrationID",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ra",
".",
"log",
".",
"AuditErrf",
"(",
"\"Rechecking CAA: %s\"",
",",
"err",
")",
"\n",
"err",
"=",
"berrors",
".",
"InternalServerError",
"(",
"\"Internal error rechecking CAA for authorization ID %v (%v)\"",
",",
"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",
"(",
"\"Rechecking CAA: %v\"",
",",
"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",
"{",
"pbProb",
",",
"err",
":=",
"bgrpc",
".",
"ProblemDetailsToPB",
"(",
"prob",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ra",
".",
"log",
".",
"AuditErrf",
"(",
"\"Could not convert order error problem to PB: %q\"",
",",
"err",
")",
"\n",
"return",
"order",
"\n",
"}",
"\n",
"order",
".",
"Error",
"=",
"pbProb",
"\n",
"if",
"err",
":=",
"ra",
".",
"SA",
".",
"SetOrderError",
"(",
"ctx",
",",
"order",
")",
";",
"err",
"!=",
"nil",
"{",
"ra",
".",
"log",
".",
"AuditErrf",
"(",
"\"Could not persist order error: %q\"",
",",
"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",
"if",
"*",
"order",
".",
"Status",
"!=",
"string",
"(",
"core",
".",
"StatusReady",
")",
"{",
"return",
"nil",
",",
"berrors",
".",
"OrderNotReadyError",
"(",
"\"Order's status (%q) is not acceptable for finalization\"",
",",
"*",
"order",
".",
"Status",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"order",
".",
"Names",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"berrors",
".",
"InternalServerError",
"(",
"\"Order has no associated names\"",
")",
"\n",
"}",
"\n",
"csrOb",
",",
"err",
":=",
"x509",
".",
"ParseCertificateRequest",
"(",
"req",
".",
"Csr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\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",
"csrNames",
":=",
"core",
".",
"UniqueLowerNames",
"(",
"csrOb",
".",
"DNSNames",
")",
"\n",
"orderNames",
":=",
"core",
".",
"UniqueLowerNames",
"(",
"order",
".",
"Names",
")",
"\n",
"if",
"len",
"(",
"orderNames",
")",
"!=",
"len",
"(",
"csrNames",
")",
"{",
"return",
"nil",
",",
"berrors",
".",
"UnauthorizedError",
"(",
"\"Order includes different number of names than CSR specifies\"",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"name",
":=",
"range",
"orderNames",
"{",
"if",
"name",
"!=",
"csrNames",
"[",
"i",
"]",
"{",
"return",
"nil",
",",
"berrors",
".",
"UnauthorizedError",
"(",
"\"CSR is missing Order domain %q\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"ra",
".",
"SA",
".",
"SetOrderProcessing",
"(",
"ctx",
",",
"order",
")",
";",
"err",
"!=",
"nil",
"{",
"ra",
".",
"failOrder",
"(",
"ctx",
",",
"order",
",",
"probs",
".",
"ServerInternal",
"(",
"\"Error setting order processing\"",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"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",
"{",
"ra",
".",
"failOrder",
"(",
"ctx",
",",
"order",
",",
"web",
".",
"ProblemDetailsForError",
"(",
"err",
",",
"\"Error finalizing order\"",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"parsedCertificate",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"[",
"]",
"byte",
"(",
"cert",
".",
"DER",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ra",
".",
"failOrder",
"(",
"ctx",
",",
"order",
",",
"probs",
".",
"ServerInternal",
"(",
"\"Error parsing certificate DER\"",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"serial",
":=",
"core",
".",
"SerialToString",
"(",
"parsedCertificate",
".",
"SerialNumber",
")",
"\n",
"order",
".",
"CertificateSerial",
"=",
"&",
"serial",
"\n",
"if",
"err",
":=",
"ra",
".",
"SA",
".",
"FinalizeOrder",
"(",
"ctx",
",",
"order",
")",
";",
"err",
"!=",
"nil",
"{",
"ra",
".",
"failOrder",
"(",
"ctx",
",",
"order",
",",
"probs",
".",
"ServerInternal",
"(",
"\"Error persisting finalized order\"",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"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",
")",
"{",
"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",
"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",
")",
"{",
"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",
"=",
"\"error\"",
"\n",
"}",
"else",
"{",
"result",
"=",
"\"successful\"",
"\n",
"}",
"\n",
"logEvent",
".",
"ResponseTime",
"=",
"ra",
".",
"clk",
".",
"Now",
"(",
")",
"\n",
"ra",
".",
"log",
".",
"AuditObject",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Certificate request - %s\"",
",",
"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",
"{",
"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",
"{",
"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",
"var",
"badNames",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"entry",
":=",
"range",
"counts",
"{",
"if",
"entry",
".",
"Count",
"==",
"nil",
"||",
"entry",
".",
"Name",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"CountByNames_MapElement had nil Count or Name\"",
")",
"\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",
"{",
"return",
"base",
",",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"ra",
".",
"validateContacts",
"(",
"ctx",
",",
"base",
".",
"Contact",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"core",
".",
"Registration",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"ra",
".",
"SA",
".",
"UpdateRegistration",
"(",
"ctx",
",",
"base",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"berrors",
".",
"InternalServerError",
"(",
"\"Could not update registration: %s\"",
",",
"err",
")",
"\n",
"return",
"core",
".",
"Registration",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"ra",
".",
"stats",
".",
"Inc",
"(",
"\"UpdatedRegistrations\"",
",",
"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",
"if",
"input",
".",
"Contact",
"!=",
"nil",
"&&",
"!",
"contactsEqual",
"(",
"r",
",",
"input",
")",
"{",
"r",
".",
"Contact",
"=",
"input",
".",
"Contact",
"\n",
"changed",
"=",
"true",
"\n",
"}",
"\n",
"if",
"len",
"(",
"input",
".",
"Agreement",
")",
">",
"0",
"&&",
"input",
".",
"Agreement",
"!=",
"r",
".",
"Agreement",
"{",
"r",
".",
"Agreement",
"=",
"input",
".",
"Agreement",
"\n",
"changed",
"=",
"true",
"\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",
"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",
"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",
"state",
":=",
"\"Failure\"",
"\n",
"defer",
"func",
"(",
")",
"{",
"ra",
".",
"log",
".",
"AuditInfof",
"(",
"\"%s, Request by registration ID: %d\"",
",",
"revokeEvent",
"(",
"state",
",",
"serialString",
",",
"cert",
".",
"Subject",
".",
"CommonName",
",",
"cert",
".",
"DNSNames",
",",
"revocationCode",
")",
",",
"regID",
")",
"\n",
"}",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"state",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"Failure -- %s\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"state",
"=",
"\"Success\"",
"\n",
"ra",
".",
"stats",
".",
"Inc",
"(",
"\"RevokedCertificates\"",
",",
"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",
"{",
"for",
"_",
",",
"ch",
":=",
"range",
"authz",
".",
"Challenges",
"{",
"if",
"ch",
".",
"Status",
"==",
"core",
".",
"StatusValid",
"{",
"authz",
".",
"Status",
"=",
"core",
".",
"StatusValid",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"authz",
".",
"Status",
"!=",
"core",
".",
"StatusValid",
"{",
"authz",
".",
"Status",
"=",
"core",
".",
"StatusInvalid",
"\n",
"}",
"else",
"{",
"exp",
":=",
"ra",
".",
"clk",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"ra",
".",
"authorizationLifetime",
")",
"\n",
"authz",
".",
"Expires",
"=",
"&",
"exp",
"\n",
"}",
"\n",
"err",
":=",
"ra",
".",
"SA",
".",
"FinalizeAuthorization",
"(",
"ctx",
",",
"authz",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ra",
".",
"stats",
".",
"Inc",
"(",
"\"FinalizedAuthorizations\"",
",",
"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",
"(",
"\"only valid registrations can be deactivated\"",
")",
"\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",
"(",
"\"only valid and pending authorizations can be deactivated\"",
")",
"\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: ®,
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: ®,
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",
"challenges",
",",
"err",
":=",
"ra",
".",
"PA",
".",
"ChallengesFor",
"(",
"identifier",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"berrors",
".",
"InternalServerError",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"challenge",
":=",
"range",
"challenges",
"{",
"if",
"err",
":=",
"challenge",
".",
"CheckConsistencyForClientOffer",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"berrors",
".",
"InternalServerError",
"(",
"\"challenge didn't pass sanity check: %+v\"",
",",
"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",
"(",
"\"Domain name %q is redundant with a wildcard domain in the same request. Remove one or the other from the certificate request.\"",
",",
"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",
")",
"{",
"if",
"bytes",
".",
"Compare",
"(",
"req",
".",
"IssuerKeyHash",
",",
"src",
".",
"caKeyHash",
")",
"!=",
"0",
"{",
"src",
".",
"log",
".",
"Debugf",
"(",
"\"Request intended for CA Cert ID: %s\"",
",",
"hex",
".",
"EncodeToString",
"(",
"req",
".",
"IssuerKeyHash",
")",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"cfocsp",
".",
"ErrNotFound",
"\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",
"src",
".",
"log",
".",
"Debugf",
"(",
"\"Searching for OCSP issued by us for serial %s\"",
",",
"serialString",
")",
"\n",
"var",
"response",
"dbResponse",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"len",
"(",
"response",
".",
"OCSPResponse",
")",
"!=",
"0",
"{",
"src",
".",
"log",
".",
"Debugf",
"(",
"\"OCSP Response sent for CA=%s, Serial=%s\"",
",",
"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",
",",
"\"SELECT ocspResponse, ocspLastUpdated FROM certificateStatus WHERE serial = :serial\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"serial\"",
":",
"serialString",
"}",
",",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"nil",
",",
"nil",
",",
"cfocsp",
".",
"ErrNotFound",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"src",
".",
"log",
".",
"AuditErrf",
"(",
"\"Looking up OCSP response: %s\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"response",
".",
"OCSPLastUpdated",
".",
"IsZero",
"(",
")",
"{",
"src",
".",
"log",
".",
"Debugf",
"(",
"\"OCSP Response not sent (ocspLastUpdated is zero) for CA=%s, Serial=%s\"",
",",
"hex",
".",
"EncodeToString",
"(",
"src",
".",
"caKeyHash",
")",
",",
"serialString",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"cfocsp",
".",
"ErrNotFound",
"\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",
"(",
"\"feature '%s' doesn't exist\"",
",",
"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",
"(",
"\"feature '%s' doesn't exist\"",
",",
"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",
"config",
",",
"err",
"=",
"mysql",
".",
"ParseDSN",
"(",
"dbConnect",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\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",
"{",
"conf",
".",
"ParseTime",
"=",
"true",
"\n",
"conf",
".",
"ClientFoundRows",
"=",
"true",
"\n",
"conf",
".",
"Params",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"conf",
".",
"Params",
"[",
"\"sql_mode\"",
"]",
"=",
"\"STRICT_ALL_TABLES\"",
"\n",
"if",
"conf",
".",
"ReadTimeout",
"!=",
"0",
"{",
"readTimeout",
":=",
"conf",
".",
"ReadTimeout",
".",
"Seconds",
"(",
")",
"\n",
"conf",
".",
"Params",
"[",
"\"max_statement_time\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%g\"",
",",
"readTimeout",
"*",
"0.95",
")",
"\n",
"conf",
".",
"Params",
"[",
"\"long_query_time\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%g\"",
",",
"readTimeout",
"*",
"0.80",
")",
"\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",
"(",
"\"SQL: \"",
",",
"&",
"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",
"==",
"\"_acme-challenge.servfail.com\"",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"SERVFAIL\"",
")",
"\n",
"}",
"\n",
"if",
"hostname",
"==",
"\"_acme-challenge.good-dns01.com\"",
"{",
"return",
"[",
"]",
"string",
"{",
"\"LPsIwTo7o8BoG0-vjCyGQGBWSVIPxI-i_X336eUOQZo\"",
"}",
",",
"[",
"]",
"string",
"{",
"\"respect my authority!\"",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"hostname",
"==",
"\"_acme-challenge.wrong-dns01.com\"",
"{",
"return",
"[",
"]",
"string",
"{",
"\"a\"",
"}",
",",
"[",
"]",
"string",
"{",
"\"respect my authority!\"",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"hostname",
"==",
"\"_acme-challenge.wrong-many-dns01.com\"",
"{",
"return",
"[",
"]",
"string",
"{",
"\"a\"",
",",
"\"b\"",
",",
"\"c\"",
",",
"\"d\"",
",",
"\"e\"",
"}",
",",
"[",
"]",
"string",
"{",
"\"respect my authority!\"",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"hostname",
"==",
"\"_acme-challenge.long-dns01.com\"",
"{",
"return",
"[",
"]",
"string",
"{",
"\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"",
"}",
",",
"[",
"]",
"string",
"{",
"\"respect my authority!\"",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"hostname",
"==",
"\"_acme-challenge.no-authority-dns01.com\"",
"{",
"return",
"[",
"]",
"string",
"{",
"\"LPsIwTo7o8BoG0-vjCyGQGBWSVIPxI-i_X336eUOQZo\"",
"}",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"hostname",
"==",
"\"_acme-challenge.empty-txts.com\"",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"[",
"]",
"string",
"{",
"\"hostname\"",
"}",
",",
"[",
"]",
"string",
"{",
"\"respect my authority!\"",
"}",
",",
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.