repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
letsencrypt/boulder
ca/ca.go
integrateOrphan
func (ca *CertificateAuthorityImpl) integrateOrphan() error { item, err := ca.orphanQueue.Peek() if err != nil { if err == goque.ErrEmpty { return goque.ErrEmpty } return fmt.Errorf("failed to peek into orphan queue: %s", err) } var orphan orphanedCert if err = item.ToObject(&orphan); err != nil { return fmt.Errorf("failed to marshal orphan: %s", err) } cert, err := x509.ParseCertificate(orphan.DER) if err != nil { return fmt.Errorf("failed to parse orphan: %s", err) } issued := cert.NotBefore.Add(-ca.backdate) _, err = ca.sa.AddCertificate(context.Background(), orphan.DER, orphan.RegID, orphan.OCSPResp, &issued) if err != nil && !berrors.Is(err, berrors.Duplicate) { return fmt.Errorf("failed to store orphaned certificate: %s", err) } if _, err = ca.orphanQueue.Dequeue(); err != nil { return fmt.Errorf("failed to dequeue integrated orphaned certificate: %s", err) } return nil }
go
func (ca *CertificateAuthorityImpl) integrateOrphan() error { item, err := ca.orphanQueue.Peek() if err != nil { if err == goque.ErrEmpty { return goque.ErrEmpty } return fmt.Errorf("failed to peek into orphan queue: %s", err) } var orphan orphanedCert if err = item.ToObject(&orphan); err != nil { return fmt.Errorf("failed to marshal orphan: %s", err) } cert, err := x509.ParseCertificate(orphan.DER) if err != nil { return fmt.Errorf("failed to parse orphan: %s", err) } issued := cert.NotBefore.Add(-ca.backdate) _, err = ca.sa.AddCertificate(context.Background(), orphan.DER, orphan.RegID, orphan.OCSPResp, &issued) if err != nil && !berrors.Is(err, berrors.Duplicate) { return fmt.Errorf("failed to store orphaned certificate: %s", err) } if _, err = ca.orphanQueue.Dequeue(); err != nil { return fmt.Errorf("failed to dequeue integrated orphaned certificate: %s", err) } return nil }
[ "func", "(", "ca", "*", "CertificateAuthorityImpl", ")", "integrateOrphan", "(", ")", "error", "{", "item", ",", "err", ":=", "ca", ".", "orphanQueue", ".", "Peek", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "goque", ".", "ErrEmpty", "{", "return", "goque", ".", "ErrEmpty", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "var", "orphan", "orphanedCert", "\n", "if", "err", "=", "item", ".", "ToObject", "(", "&", "orphan", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "orphan", ".", "DER", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "issued", ":=", "cert", ".", "NotBefore", ".", "Add", "(", "-", "ca", ".", "backdate", ")", "\n", "_", ",", "err", "=", "ca", ".", "sa", ".", "AddCertificate", "(", "context", ".", "Background", "(", ")", ",", "orphan", ".", "DER", ",", "orphan", ".", "RegID", ",", "orphan", ".", "OCSPResp", ",", "&", "issued", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "berrors", ".", "Is", "(", "err", ",", "berrors", ".", "Duplicate", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", "=", "ca", ".", "orphanQueue", ".", "Dequeue", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// integrateOrpan removes an orphan from the queue and adds it to the database. The // item isn't dequeued until it is actually added to the database to prevent items from // being lost if the CA is restarted between the item being dequeued and being added to // the database. It calculates the issuance time by subtracting the backdate period from // the notBefore time.
[ "integrateOrpan", "removes", "an", "orphan", "from", "the", "queue", "and", "adds", "it", "to", "the", "database", ".", "The", "item", "isn", "t", "dequeued", "until", "it", "is", "actually", "added", "to", "the", "database", "to", "prevent", "items", "from", "being", "lost", "if", "the", "CA", "is", "restarted", "between", "the", "item", "being", "dequeued", "and", "being", "added", "to", "the", "database", ".", "It", "calculates", "the", "issuance", "time", "by", "subtracting", "the", "backdate", "period", "from", "the", "notBefore", "time", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ca/ca.go#L711-L736
train
letsencrypt/boulder
wfe2/verify.go
enforceJWSAuthType
func (wfe *WebFrontEndImpl) enforceJWSAuthType( jws *jose.JSONWebSignature, expectedAuthType jwsAuthType) *probs.ProblemDetails { // Check the auth type for the provided JWS authType, prob := checkJWSAuthType(jws) if prob != nil { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSAuthTypeInvalid"}).Inc() return prob } // If the auth type isn't the one expected return a sensible problem based on // what was expected if authType != expectedAuthType { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSAuthTypeWrong"}).Inc() switch expectedAuthType { case embeddedKeyID: return probs.Malformed("No Key ID in JWS header") case embeddedJWK: return probs.Malformed("No embedded JWK in JWS header") } } return nil }
go
func (wfe *WebFrontEndImpl) enforceJWSAuthType( jws *jose.JSONWebSignature, expectedAuthType jwsAuthType) *probs.ProblemDetails { // Check the auth type for the provided JWS authType, prob := checkJWSAuthType(jws) if prob != nil { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSAuthTypeInvalid"}).Inc() return prob } // If the auth type isn't the one expected return a sensible problem based on // what was expected if authType != expectedAuthType { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSAuthTypeWrong"}).Inc() switch expectedAuthType { case embeddedKeyID: return probs.Malformed("No Key ID in JWS header") case embeddedJWK: return probs.Malformed("No embedded JWK in JWS header") } } return nil }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "enforceJWSAuthType", "(", "jws", "*", "jose", ".", "JSONWebSignature", ",", "expectedAuthType", "jwsAuthType", ")", "*", "probs", ".", "ProblemDetails", "{", "// Check the auth type for the provided JWS", "authType", ",", "prob", ":=", "checkJWSAuthType", "(", "jws", ")", "\n", "if", "prob", "!=", "nil", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "prob", "\n", "}", "\n", "// If the auth type isn't the one expected return a sensible problem based on", "// what was expected", "if", "authType", "!=", "expectedAuthType", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "switch", "expectedAuthType", "{", "case", "embeddedKeyID", ":", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "case", "embeddedJWK", ":", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// enforceJWSAuthType enforces a provided JWS has the provided auth type. If there // is an error determining the auth type or if it is not the expected auth type // then a problem is returned.
[ "enforceJWSAuthType", "enforces", "a", "provided", "JWS", "has", "the", "provided", "auth", "type", ".", "If", "there", "is", "an", "error", "determining", "the", "auth", "type", "or", "if", "it", "is", "not", "the", "expected", "auth", "type", "then", "a", "problem", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/verify.go#L114-L135
train
letsencrypt/boulder
wfe2/verify.go
validPOSTURL
func (wfe *WebFrontEndImpl) validPOSTURL( request *http.Request, jws *jose.JSONWebSignature) *probs.ProblemDetails { // validPOSTURL is called after parseJWS() which defends against the incorrect // number of signatures. header := jws.Signatures[0].Header extraHeaders := header.ExtraHeaders // Check that there is at least one Extra Header if len(extraHeaders) == 0 { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSNoExtraHeaders"}).Inc() return probs.Malformed("JWS header parameter 'url' required") } // Try to read a 'url' Extra Header as a string headerURL, ok := extraHeaders[jose.HeaderKey("url")].(string) if !ok || len(headerURL) == 0 { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSMissingURL"}).Inc() return probs.Malformed("JWS header parameter 'url' required") } // Compute the URL we expect to be in the JWS based on the HTTP request expectedURL := url.URL{ Scheme: requestProto(request), Host: request.Host, Path: request.RequestURI, } // Check that the URL we expect is the one that was found in the signed JWS // header if expectedURL.String() != headerURL { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSMismatchedURL"}).Inc() return probs.Malformed("JWS header parameter 'url' incorrect. Expected %q got %q", expectedURL.String(), headerURL) } return nil }
go
func (wfe *WebFrontEndImpl) validPOSTURL( request *http.Request, jws *jose.JSONWebSignature) *probs.ProblemDetails { // validPOSTURL is called after parseJWS() which defends against the incorrect // number of signatures. header := jws.Signatures[0].Header extraHeaders := header.ExtraHeaders // Check that there is at least one Extra Header if len(extraHeaders) == 0 { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSNoExtraHeaders"}).Inc() return probs.Malformed("JWS header parameter 'url' required") } // Try to read a 'url' Extra Header as a string headerURL, ok := extraHeaders[jose.HeaderKey("url")].(string) if !ok || len(headerURL) == 0 { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSMissingURL"}).Inc() return probs.Malformed("JWS header parameter 'url' required") } // Compute the URL we expect to be in the JWS based on the HTTP request expectedURL := url.URL{ Scheme: requestProto(request), Host: request.Host, Path: request.RequestURI, } // Check that the URL we expect is the one that was found in the signed JWS // header if expectedURL.String() != headerURL { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSMismatchedURL"}).Inc() return probs.Malformed("JWS header parameter 'url' incorrect. Expected %q got %q", expectedURL.String(), headerURL) } return nil }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "validPOSTURL", "(", "request", "*", "http", ".", "Request", ",", "jws", "*", "jose", ".", "JSONWebSignature", ")", "*", "probs", ".", "ProblemDetails", "{", "// validPOSTURL is called after parseJWS() which defends against the incorrect", "// number of signatures.", "header", ":=", "jws", ".", "Signatures", "[", "0", "]", ".", "Header", "\n", "extraHeaders", ":=", "header", ".", "ExtraHeaders", "\n", "// Check that there is at least one Extra Header", "if", "len", "(", "extraHeaders", ")", "==", "0", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n", "// Try to read a 'url' Extra Header as a string", "headerURL", ",", "ok", ":=", "extraHeaders", "[", "jose", ".", "HeaderKey", "(", "\"", "\"", ")", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "||", "len", "(", "headerURL", ")", "==", "0", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n", "// Compute the URL we expect to be in the JWS based on the HTTP request", "expectedURL", ":=", "url", ".", "URL", "{", "Scheme", ":", "requestProto", "(", "request", ")", ",", "Host", ":", "request", ".", "Host", ",", "Path", ":", "request", ".", "RequestURI", ",", "}", "\n", "// Check that the URL we expect is the one that was found in the signed JWS", "// header", "if", "expectedURL", ".", "String", "(", ")", "!=", "headerURL", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "probs", ".", "Malformed", "(", "\"", "\"", ",", "expectedURL", ".", "String", "(", ")", ",", "headerURL", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validPOSTURL checks the JWS' URL header against the expected URL based on the // HTTP request. This prevents a JWS intended for one endpoint being replayed // against a different endpoint. If the URL isn't present, is invalid, or // doesn't match the HTTP request a problem is returned.
[ "validPOSTURL", "checks", "the", "JWS", "URL", "header", "against", "the", "expected", "URL", "based", "on", "the", "HTTP", "request", ".", "This", "prevents", "a", "JWS", "intended", "for", "one", "endpoint", "being", "replayed", "against", "a", "different", "endpoint", ".", "If", "the", "URL", "isn", "t", "present", "is", "invalid", "or", "doesn", "t", "match", "the", "HTTP", "request", "a", "problem", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/verify.go#L199-L231
train
letsencrypt/boulder
wfe2/verify.go
matchJWSURLs
func (wfe *WebFrontEndImpl) matchJWSURLs(outer, inner *jose.JSONWebSignature) *probs.ProblemDetails { // Verify that the outer JWS has a non-empty URL header. This is strictly // defensive since the expectation is that endpoints using `matchJWSURLs` // have received at least one of their JWS from calling validPOSTForAccount(), // which checks the outer JWS has the expected URL header before processing // the inner JWS. outerURL, ok := outer.Signatures[0].Header.ExtraHeaders[jose.HeaderKey("url")].(string) if !ok || len(outerURL) == 0 { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "KeyRolloverOuterJWSNoURL"}).Inc() return probs.Malformed("Outer JWS header parameter 'url' required") } // Verify the inner JWS has a non-empty URL header. innerURL, ok := inner.Signatures[0].Header.ExtraHeaders[jose.HeaderKey("url")].(string) if !ok || len(innerURL) == 0 { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "KeyRolloverInnerJWSNoURL"}).Inc() return probs.Malformed("Inner JWS header parameter 'url' required") } // Verify that the outer URL matches the inner URL if outerURL != innerURL { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "KeyRolloverMismatchedURLs"}).Inc() return probs.Malformed("Outer JWS 'url' value %q does not match inner JWS 'url' value %q", outerURL, innerURL) } return nil }
go
func (wfe *WebFrontEndImpl) matchJWSURLs(outer, inner *jose.JSONWebSignature) *probs.ProblemDetails { // Verify that the outer JWS has a non-empty URL header. This is strictly // defensive since the expectation is that endpoints using `matchJWSURLs` // have received at least one of their JWS from calling validPOSTForAccount(), // which checks the outer JWS has the expected URL header before processing // the inner JWS. outerURL, ok := outer.Signatures[0].Header.ExtraHeaders[jose.HeaderKey("url")].(string) if !ok || len(outerURL) == 0 { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "KeyRolloverOuterJWSNoURL"}).Inc() return probs.Malformed("Outer JWS header parameter 'url' required") } // Verify the inner JWS has a non-empty URL header. innerURL, ok := inner.Signatures[0].Header.ExtraHeaders[jose.HeaderKey("url")].(string) if !ok || len(innerURL) == 0 { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "KeyRolloverInnerJWSNoURL"}).Inc() return probs.Malformed("Inner JWS header parameter 'url' required") } // Verify that the outer URL matches the inner URL if outerURL != innerURL { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "KeyRolloverMismatchedURLs"}).Inc() return probs.Malformed("Outer JWS 'url' value %q does not match inner JWS 'url' value %q", outerURL, innerURL) } return nil }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "matchJWSURLs", "(", "outer", ",", "inner", "*", "jose", ".", "JSONWebSignature", ")", "*", "probs", ".", "ProblemDetails", "{", "// Verify that the outer JWS has a non-empty URL header. This is strictly", "// defensive since the expectation is that endpoints using `matchJWSURLs`", "// have received at least one of their JWS from calling validPOSTForAccount(),", "// which checks the outer JWS has the expected URL header before processing", "// the inner JWS.", "outerURL", ",", "ok", ":=", "outer", ".", "Signatures", "[", "0", "]", ".", "Header", ".", "ExtraHeaders", "[", "jose", ".", "HeaderKey", "(", "\"", "\"", ")", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "||", "len", "(", "outerURL", ")", "==", "0", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Verify the inner JWS has a non-empty URL header.", "innerURL", ",", "ok", ":=", "inner", ".", "Signatures", "[", "0", "]", ".", "Header", ".", "ExtraHeaders", "[", "jose", ".", "HeaderKey", "(", "\"", "\"", ")", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "||", "len", "(", "innerURL", ")", "==", "0", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Verify that the outer URL matches the inner URL", "if", "outerURL", "!=", "innerURL", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "probs", ".", "Malformed", "(", "\"", "\"", ",", "outerURL", ",", "innerURL", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// matchJWSURLs checks two JWS' URL headers are equal. This is used during key // rollover to check that the inner JWS URL matches the outer JWS URL. If the // JWS URLs do not match a problem is returned.
[ "matchJWSURLs", "checks", "two", "JWS", "URL", "headers", "are", "equal", ".", "This", "is", "used", "during", "key", "rollover", "to", "check", "that", "the", "inner", "JWS", "URL", "matches", "the", "outer", "JWS", "URL", ".", "If", "the", "JWS", "URLs", "do", "not", "match", "a", "problem", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/verify.go#L236-L263
train
letsencrypt/boulder
wfe2/verify.go
parseJWSRequest
func (wfe *WebFrontEndImpl) parseJWSRequest(request *http.Request) (*jose.JSONWebSignature, *probs.ProblemDetails) { // Verify that the POST request has the expected headers if prob := wfe.validPOSTRequest(request); prob != nil { return nil, prob } // Read the POST request body's bytes. validPOSTRequest has already checked // that the body is non-nil bodyBytes, err := ioutil.ReadAll(request.Body) if err != nil { wfe.stats.httpErrorCount.With(prometheus.Labels{"type": "UnableToReadReqBody"}).Inc() return nil, probs.ServerInternal("unable to read request body") } return wfe.parseJWS(bodyBytes) }
go
func (wfe *WebFrontEndImpl) parseJWSRequest(request *http.Request) (*jose.JSONWebSignature, *probs.ProblemDetails) { // Verify that the POST request has the expected headers if prob := wfe.validPOSTRequest(request); prob != nil { return nil, prob } // Read the POST request body's bytes. validPOSTRequest has already checked // that the body is non-nil bodyBytes, err := ioutil.ReadAll(request.Body) if err != nil { wfe.stats.httpErrorCount.With(prometheus.Labels{"type": "UnableToReadReqBody"}).Inc() return nil, probs.ServerInternal("unable to read request body") } return wfe.parseJWS(bodyBytes) }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "parseJWSRequest", "(", "request", "*", "http", ".", "Request", ")", "(", "*", "jose", ".", "JSONWebSignature", ",", "*", "probs", ".", "ProblemDetails", ")", "{", "// Verify that the POST request has the expected headers", "if", "prob", ":=", "wfe", ".", "validPOSTRequest", "(", "request", ")", ";", "prob", "!=", "nil", "{", "return", "nil", ",", "prob", "\n", "}", "\n\n", "// Read the POST request body's bytes. validPOSTRequest has already checked", "// that the body is non-nil", "bodyBytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "request", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "wfe", ".", "stats", ".", "httpErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "nil", ",", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "wfe", ".", "parseJWS", "(", "bodyBytes", ")", "\n", "}" ]
// parseJWSRequest extracts a JSONWebSignature from an HTTP POST request's body using parseJWS.
[ "parseJWSRequest", "extracts", "a", "JSONWebSignature", "from", "an", "HTTP", "POST", "request", "s", "body", "using", "parseJWS", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/verify.go#L326-L341
train
letsencrypt/boulder
wfe2/verify.go
extractJWK
func (wfe *WebFrontEndImpl) extractJWK(jws *jose.JSONWebSignature) (*jose.JSONWebKey, *probs.ProblemDetails) { // extractJWK expects the request to be using an embedded JWK auth type and // to not contain the mutually exclusive KeyID. if prob := wfe.enforceJWSAuthType(jws, embeddedJWK); prob != nil { return nil, prob } // extractJWK must be called after parseJWS() which defends against the // incorrect number of signatures. header := jws.Signatures[0].Header // We can be sure that JSONWebKey is != nil because we have already called // enforceJWSAuthType() key := header.JSONWebKey // If the key isn't considered valid by go-jose return a problem immediately if !key.Valid() { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWKInvalid"}).Inc() return nil, probs.Malformed("Invalid JWK in JWS header") } return key, nil }
go
func (wfe *WebFrontEndImpl) extractJWK(jws *jose.JSONWebSignature) (*jose.JSONWebKey, *probs.ProblemDetails) { // extractJWK expects the request to be using an embedded JWK auth type and // to not contain the mutually exclusive KeyID. if prob := wfe.enforceJWSAuthType(jws, embeddedJWK); prob != nil { return nil, prob } // extractJWK must be called after parseJWS() which defends against the // incorrect number of signatures. header := jws.Signatures[0].Header // We can be sure that JSONWebKey is != nil because we have already called // enforceJWSAuthType() key := header.JSONWebKey // If the key isn't considered valid by go-jose return a problem immediately if !key.Valid() { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWKInvalid"}).Inc() return nil, probs.Malformed("Invalid JWK in JWS header") } return key, nil }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "extractJWK", "(", "jws", "*", "jose", ".", "JSONWebSignature", ")", "(", "*", "jose", ".", "JSONWebKey", ",", "*", "probs", ".", "ProblemDetails", ")", "{", "// extractJWK expects the request to be using an embedded JWK auth type and", "// to not contain the mutually exclusive KeyID.", "if", "prob", ":=", "wfe", ".", "enforceJWSAuthType", "(", "jws", ",", "embeddedJWK", ")", ";", "prob", "!=", "nil", "{", "return", "nil", ",", "prob", "\n", "}", "\n\n", "// extractJWK must be called after parseJWS() which defends against the", "// incorrect number of signatures.", "header", ":=", "jws", ".", "Signatures", "[", "0", "]", ".", "Header", "\n", "// We can be sure that JSONWebKey is != nil because we have already called", "// enforceJWSAuthType()", "key", ":=", "header", ".", "JSONWebKey", "\n\n", "// If the key isn't considered valid by go-jose return a problem immediately", "if", "!", "key", ".", "Valid", "(", ")", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "nil", ",", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "key", ",", "nil", "\n", "}" ]
// extractJWK extracts a JWK from a provided JWS or returns a problem. It // expects that the JWS is using the embedded JWK style of authentication and // does not contain an embedded Key ID. Callers should have acquired the // provided JWS from parseJWS to ensure it has the correct number of signatures // present.
[ "extractJWK", "extracts", "a", "JWK", "from", "a", "provided", "JWS", "or", "returns", "a", "problem", ".", "It", "expects", "that", "the", "JWS", "is", "using", "the", "embedded", "JWK", "style", "of", "authentication", "and", "does", "not", "contain", "an", "embedded", "Key", "ID", ".", "Callers", "should", "have", "acquired", "the", "provided", "JWS", "from", "parseJWS", "to", "ensure", "it", "has", "the", "correct", "number", "of", "signatures", "present", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/verify.go#L348-L369
train
letsencrypt/boulder
wfe2/verify.go
acctIDFromURL
func (wfe *WebFrontEndImpl) acctIDFromURL(acctURL string, request *http.Request) (int64, *probs.ProblemDetails) { // For normal ACME v2 accounts we expect the account URL has a prefix composed // of the Host header and the acctPath. expectedURLPrefix := web.RelativeEndpoint(request, acctPath) // Process the acctURL to find only the trailing numeric account ID. Both the // expected URL prefix and a legacy URL prefix are permitted in order to allow // ACME v1 clients to use legacy accounts with unmodified account URLs for V2 // requests. var accountIDStr string if strings.HasPrefix(acctURL, expectedURLPrefix) { accountIDStr = strings.TrimPrefix(acctURL, expectedURLPrefix) } else if strings.HasPrefix(acctURL, wfe.LegacyKeyIDPrefix) { accountIDStr = strings.TrimPrefix(acctURL, wfe.LegacyKeyIDPrefix) } else { return 0, probs.Malformed( fmt.Sprintf("KeyID header contained an invalid account URL: %q", acctURL)) } // Convert the raw account ID string to an int64 for use with the SA's // GetRegistration RPC accountID, err := strconv.ParseInt(accountIDStr, 10, 64) if err != nil { return 0, probs.Malformed("Malformed account ID in KeyID header URL: %q", acctURL) } return accountID, nil }
go
func (wfe *WebFrontEndImpl) acctIDFromURL(acctURL string, request *http.Request) (int64, *probs.ProblemDetails) { // For normal ACME v2 accounts we expect the account URL has a prefix composed // of the Host header and the acctPath. expectedURLPrefix := web.RelativeEndpoint(request, acctPath) // Process the acctURL to find only the trailing numeric account ID. Both the // expected URL prefix and a legacy URL prefix are permitted in order to allow // ACME v1 clients to use legacy accounts with unmodified account URLs for V2 // requests. var accountIDStr string if strings.HasPrefix(acctURL, expectedURLPrefix) { accountIDStr = strings.TrimPrefix(acctURL, expectedURLPrefix) } else if strings.HasPrefix(acctURL, wfe.LegacyKeyIDPrefix) { accountIDStr = strings.TrimPrefix(acctURL, wfe.LegacyKeyIDPrefix) } else { return 0, probs.Malformed( fmt.Sprintf("KeyID header contained an invalid account URL: %q", acctURL)) } // Convert the raw account ID string to an int64 for use with the SA's // GetRegistration RPC accountID, err := strconv.ParseInt(accountIDStr, 10, 64) if err != nil { return 0, probs.Malformed("Malformed account ID in KeyID header URL: %q", acctURL) } return accountID, nil }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "acctIDFromURL", "(", "acctURL", "string", ",", "request", "*", "http", ".", "Request", ")", "(", "int64", ",", "*", "probs", ".", "ProblemDetails", ")", "{", "// For normal ACME v2 accounts we expect the account URL has a prefix composed", "// of the Host header and the acctPath.", "expectedURLPrefix", ":=", "web", ".", "RelativeEndpoint", "(", "request", ",", "acctPath", ")", "\n\n", "// Process the acctURL to find only the trailing numeric account ID. Both the", "// expected URL prefix and a legacy URL prefix are permitted in order to allow", "// ACME v1 clients to use legacy accounts with unmodified account URLs for V2", "// requests.", "var", "accountIDStr", "string", "\n", "if", "strings", ".", "HasPrefix", "(", "acctURL", ",", "expectedURLPrefix", ")", "{", "accountIDStr", "=", "strings", ".", "TrimPrefix", "(", "acctURL", ",", "expectedURLPrefix", ")", "\n", "}", "else", "if", "strings", ".", "HasPrefix", "(", "acctURL", ",", "wfe", ".", "LegacyKeyIDPrefix", ")", "{", "accountIDStr", "=", "strings", ".", "TrimPrefix", "(", "acctURL", ",", "wfe", ".", "LegacyKeyIDPrefix", ")", "\n", "}", "else", "{", "return", "0", ",", "probs", ".", "Malformed", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "acctURL", ")", ")", "\n", "}", "\n\n", "// Convert the raw account ID string to an int64 for use with the SA's", "// GetRegistration RPC", "accountID", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "accountIDStr", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "probs", ".", "Malformed", "(", "\"", "\"", ",", "acctURL", ")", "\n", "}", "\n", "return", "accountID", ",", "nil", "\n", "}" ]
// acctIDFromURL extracts the numeric int64 account ID from a ACMEv1 or ACMEv2 // account URL. If the acctURL has an invalid URL or the account ID in the // acctURL is non-numeric a MalformedProblem is returned.
[ "acctIDFromURL", "extracts", "the", "numeric", "int64", "account", "ID", "from", "a", "ACMEv1", "or", "ACMEv2", "account", "URL", ".", "If", "the", "acctURL", "has", "an", "invalid", "URL", "or", "the", "account", "ID", "in", "the", "acctURL", "is", "non", "-", "numeric", "a", "MalformedProblem", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/verify.go#L374-L400
train
letsencrypt/boulder
wfe2/verify.go
lookupJWK
func (wfe *WebFrontEndImpl) lookupJWK( jws *jose.JSONWebSignature, ctx context.Context, request *http.Request, logEvent *web.RequestEvent) (*jose.JSONWebKey, *core.Registration, *probs.ProblemDetails) { // We expect the request to be using an embedded Key ID auth type and to not // contain the mutually exclusive embedded JWK. if prob := wfe.enforceJWSAuthType(jws, embeddedKeyID); prob != nil { return nil, nil, prob } header := jws.Signatures[0].Header accountURL := header.KeyID accountID, prob := wfe.acctIDFromURL(accountURL, request) if prob != nil { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSInvalidKeyID"}).Inc() return nil, nil, prob } // Try to find the account for this account ID account, err := wfe.SA.GetRegistration(ctx, accountID) if err != nil { // If the account isn't found, return a suitable problem if berrors.Is(err, berrors.NotFound) { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSKeyIDNotFound"}).Inc() return nil, nil, probs.AccountDoesNotExist("Account %q not found", accountURL) } // If there was an error and it isn't a "Not Found" error, return // a ServerInternal problem since this is unexpected. wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSKeyIDLookupFailed"}).Inc() // Add an error to the log event with the internal error message logEvent.AddError(fmt.Sprintf("Error calling SA.GetRegistration: %s", err.Error())) return nil, nil, probs.ServerInternal("Error retreiving account %q", accountURL) } // Verify the account is not deactivated if account.Status != core.StatusValid { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSKeyIDAccountInvalid"}).Inc() return nil, nil, probs.Unauthorized("Account is not valid, has status %q", account.Status) } // Update the logEvent with the account information and return the JWK logEvent.Requester = account.ID if account.Contact != nil { logEvent.Contacts = *account.Contact } return account.Key, &account, nil }
go
func (wfe *WebFrontEndImpl) lookupJWK( jws *jose.JSONWebSignature, ctx context.Context, request *http.Request, logEvent *web.RequestEvent) (*jose.JSONWebKey, *core.Registration, *probs.ProblemDetails) { // We expect the request to be using an embedded Key ID auth type and to not // contain the mutually exclusive embedded JWK. if prob := wfe.enforceJWSAuthType(jws, embeddedKeyID); prob != nil { return nil, nil, prob } header := jws.Signatures[0].Header accountURL := header.KeyID accountID, prob := wfe.acctIDFromURL(accountURL, request) if prob != nil { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSInvalidKeyID"}).Inc() return nil, nil, prob } // Try to find the account for this account ID account, err := wfe.SA.GetRegistration(ctx, accountID) if err != nil { // If the account isn't found, return a suitable problem if berrors.Is(err, berrors.NotFound) { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSKeyIDNotFound"}).Inc() return nil, nil, probs.AccountDoesNotExist("Account %q not found", accountURL) } // If there was an error and it isn't a "Not Found" error, return // a ServerInternal problem since this is unexpected. wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSKeyIDLookupFailed"}).Inc() // Add an error to the log event with the internal error message logEvent.AddError(fmt.Sprintf("Error calling SA.GetRegistration: %s", err.Error())) return nil, nil, probs.ServerInternal("Error retreiving account %q", accountURL) } // Verify the account is not deactivated if account.Status != core.StatusValid { wfe.stats.joseErrorCount.With(prometheus.Labels{"type": "JWSKeyIDAccountInvalid"}).Inc() return nil, nil, probs.Unauthorized("Account is not valid, has status %q", account.Status) } // Update the logEvent with the account information and return the JWK logEvent.Requester = account.ID if account.Contact != nil { logEvent.Contacts = *account.Contact } return account.Key, &account, nil }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "lookupJWK", "(", "jws", "*", "jose", ".", "JSONWebSignature", ",", "ctx", "context", ".", "Context", ",", "request", "*", "http", ".", "Request", ",", "logEvent", "*", "web", ".", "RequestEvent", ")", "(", "*", "jose", ".", "JSONWebKey", ",", "*", "core", ".", "Registration", ",", "*", "probs", ".", "ProblemDetails", ")", "{", "// We expect the request to be using an embedded Key ID auth type and to not", "// contain the mutually exclusive embedded JWK.", "if", "prob", ":=", "wfe", ".", "enforceJWSAuthType", "(", "jws", ",", "embeddedKeyID", ")", ";", "prob", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "prob", "\n", "}", "\n\n", "header", ":=", "jws", ".", "Signatures", "[", "0", "]", ".", "Header", "\n", "accountURL", ":=", "header", ".", "KeyID", "\n", "accountID", ",", "prob", ":=", "wfe", ".", "acctIDFromURL", "(", "accountURL", ",", "request", ")", "\n", "if", "prob", "!=", "nil", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "nil", ",", "nil", ",", "prob", "\n", "}", "\n\n", "// Try to find the account for this account ID", "account", ",", "err", ":=", "wfe", ".", "SA", ".", "GetRegistration", "(", "ctx", ",", "accountID", ")", "\n", "if", "err", "!=", "nil", "{", "// If the account isn't found, return a suitable problem", "if", "berrors", ".", "Is", "(", "err", ",", "berrors", ".", "NotFound", ")", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "nil", ",", "nil", ",", "probs", ".", "AccountDoesNotExist", "(", "\"", "\"", ",", "accountURL", ")", "\n", "}", "\n\n", "// If there was an error and it isn't a \"Not Found\" error, return", "// a ServerInternal problem since this is unexpected.", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "// Add an error to the log event with the internal error message", "logEvent", ".", "AddError", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "return", "nil", ",", "nil", ",", "probs", ".", "ServerInternal", "(", "\"", "\"", ",", "accountURL", ")", "\n", "}", "\n\n", "// Verify the account is not deactivated", "if", "account", ".", "Status", "!=", "core", ".", "StatusValid", "{", "wfe", ".", "stats", ".", "joseErrorCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "Inc", "(", ")", "\n", "return", "nil", ",", "nil", ",", "probs", ".", "Unauthorized", "(", "\"", "\"", ",", "account", ".", "Status", ")", "\n", "}", "\n\n", "// Update the logEvent with the account information and return the JWK", "logEvent", ".", "Requester", "=", "account", ".", "ID", "\n", "if", "account", ".", "Contact", "!=", "nil", "{", "logEvent", ".", "Contacts", "=", "*", "account", ".", "Contact", "\n", "}", "\n", "return", "account", ".", "Key", ",", "&", "account", ",", "nil", "\n", "}" ]
// lookupJWK finds a JWK associated with the Key ID present in a provided JWS, // returning the JWK and a pointer to the associated account, or a problem. It // expects that the JWS is using the embedded Key ID style of authentication // and does not contain an embedded JWK. Callers should have acquired the // provided JWS from parseJWS to ensure it has the correct number of signatures // present.
[ "lookupJWK", "finds", "a", "JWK", "associated", "with", "the", "Key", "ID", "present", "in", "a", "provided", "JWS", "returning", "the", "JWK", "and", "a", "pointer", "to", "the", "associated", "account", "or", "a", "problem", ".", "It", "expects", "that", "the", "JWS", "is", "using", "the", "embedded", "Key", "ID", "style", "of", "authentication", "and", "does", "not", "contain", "an", "embedded", "JWK", ".", "Callers", "should", "have", "acquired", "the", "provided", "JWS", "from", "parseJWS", "to", "ensure", "it", "has", "the", "correct", "number", "of", "signatures", "present", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/verify.go#L408-L456
train
letsencrypt/boulder
wfe2/verify.go
validPOSTForAccount
func (wfe *WebFrontEndImpl) validPOSTForAccount( request *http.Request, ctx context.Context, logEvent *web.RequestEvent) ([]byte, *jose.JSONWebSignature, *core.Registration, *probs.ProblemDetails) { // Parse the JWS from the POST request jws, prob := wfe.parseJWSRequest(request) if prob != nil { return nil, nil, nil, prob } return wfe.validJWSForAccount(jws, request, ctx, logEvent) }
go
func (wfe *WebFrontEndImpl) validPOSTForAccount( request *http.Request, ctx context.Context, logEvent *web.RequestEvent) ([]byte, *jose.JSONWebSignature, *core.Registration, *probs.ProblemDetails) { // Parse the JWS from the POST request jws, prob := wfe.parseJWSRequest(request) if prob != nil { return nil, nil, nil, prob } return wfe.validJWSForAccount(jws, request, ctx, logEvent) }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "validPOSTForAccount", "(", "request", "*", "http", ".", "Request", ",", "ctx", "context", ".", "Context", ",", "logEvent", "*", "web", ".", "RequestEvent", ")", "(", "[", "]", "byte", ",", "*", "jose", ".", "JSONWebSignature", ",", "*", "core", ".", "Registration", ",", "*", "probs", ".", "ProblemDetails", ")", "{", "// Parse the JWS from the POST request", "jws", ",", "prob", ":=", "wfe", ".", "parseJWSRequest", "(", "request", ")", "\n", "if", "prob", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "prob", "\n", "}", "\n", "return", "wfe", ".", "validJWSForAccount", "(", "jws", ",", "request", ",", "ctx", ",", "logEvent", ")", "\n", "}" ]
// validPOSTForAccount checks that a given POST request has a valid JWS // using `validJWSForAccount`. If valid, the authenticated JWS body and the // registration that authenticated the body are returned. Otherwise a problem is // returned. The returned JWS body may be empty if the request is a POST-as-GET // request.
[ "validPOSTForAccount", "checks", "that", "a", "given", "POST", "request", "has", "a", "valid", "JWS", "using", "validJWSForAccount", ".", "If", "valid", "the", "authenticated", "JWS", "body", "and", "the", "registration", "that", "authenticated", "the", "body", "are", "returned", ".", "Otherwise", "a", "problem", "is", "returned", ".", "The", "returned", "JWS", "body", "may", "be", "empty", "if", "the", "request", "is", "a", "POST", "-", "as", "-", "GET", "request", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/verify.go#L546-L556
train
letsencrypt/boulder
wfe2/verify.go
validSelfAuthenticatedPOST
func (wfe *WebFrontEndImpl) validSelfAuthenticatedPOST( request *http.Request, logEvent *web.RequestEvent) ([]byte, *jose.JSONWebKey, *probs.ProblemDetails) { // Parse the JWS from the POST request jws, prob := wfe.parseJWSRequest(request) if prob != nil { return nil, nil, prob } // Extract and validate the embedded JWK from the parsed JWS return wfe.validSelfAuthenticatedJWS(jws, request, logEvent) }
go
func (wfe *WebFrontEndImpl) validSelfAuthenticatedPOST( request *http.Request, logEvent *web.RequestEvent) ([]byte, *jose.JSONWebKey, *probs.ProblemDetails) { // Parse the JWS from the POST request jws, prob := wfe.parseJWSRequest(request) if prob != nil { return nil, nil, prob } // Extract and validate the embedded JWK from the parsed JWS return wfe.validSelfAuthenticatedJWS(jws, request, logEvent) }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "validSelfAuthenticatedPOST", "(", "request", "*", "http", ".", "Request", ",", "logEvent", "*", "web", ".", "RequestEvent", ")", "(", "[", "]", "byte", ",", "*", "jose", ".", "JSONWebKey", ",", "*", "probs", ".", "ProblemDetails", ")", "{", "// Parse the JWS from the POST request", "jws", ",", "prob", ":=", "wfe", ".", "parseJWSRequest", "(", "request", ")", "\n", "if", "prob", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "prob", "\n", "}", "\n", "// Extract and validate the embedded JWK from the parsed JWS", "return", "wfe", ".", "validSelfAuthenticatedJWS", "(", "jws", ",", "request", ",", "logEvent", ")", "\n", "}" ]
// validSelfAuthenticatedPOST checks that a given POST request has a valid JWS // using `validSelfAuthenticatedJWS`.
[ "validSelfAuthenticatedPOST", "checks", "that", "a", "given", "POST", "request", "has", "a", "valid", "JWS", "using", "validSelfAuthenticatedJWS", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/verify.go#L619-L629
train
letsencrypt/boulder
bdns/dns.go
NewDNSClientImpl
func NewDNSClientImpl( readTimeout time.Duration, servers []string, stats metrics.Scope, clk clock.Clock, maxTries int, ) *DNSClientImpl { stats = stats.NewScope("DNS") // TODO(jmhodges): make constructor use an Option func pattern dnsClient := new(dns.Client) // Set timeout for underlying net.Conn dnsClient.ReadTimeout = readTimeout dnsClient.Net = "udp" queryTime := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "dns_query_time", Help: "Time taken to perform a DNS query", Buckets: metrics.InternetFacingBuckets, }, []string{"qtype", "result", "authenticated_data", "resolver"}, ) totalLookupTime := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "dns_total_lookup_time", Help: "Time taken to perform a DNS lookup, including all retried queries", Buckets: metrics.InternetFacingBuckets, }, []string{"qtype", "result", "authenticated_data", "retries", "resolver"}, ) timeoutCounter := prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "dns_timeout", Help: "Counter of various types of DNS query timeouts", }, []string{"qtype", "type", "resolver"}, ) stats.MustRegister(queryTime, totalLookupTime, timeoutCounter) return &DNSClientImpl{ dnsClient: dnsClient, servers: servers, allowRestrictedAddresses: false, maxTries: maxTries, clk: clk, queryTime: queryTime, totalLookupTime: totalLookupTime, timeoutCounter: timeoutCounter, } }
go
func NewDNSClientImpl( readTimeout time.Duration, servers []string, stats metrics.Scope, clk clock.Clock, maxTries int, ) *DNSClientImpl { stats = stats.NewScope("DNS") // TODO(jmhodges): make constructor use an Option func pattern dnsClient := new(dns.Client) // Set timeout for underlying net.Conn dnsClient.ReadTimeout = readTimeout dnsClient.Net = "udp" queryTime := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "dns_query_time", Help: "Time taken to perform a DNS query", Buckets: metrics.InternetFacingBuckets, }, []string{"qtype", "result", "authenticated_data", "resolver"}, ) totalLookupTime := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "dns_total_lookup_time", Help: "Time taken to perform a DNS lookup, including all retried queries", Buckets: metrics.InternetFacingBuckets, }, []string{"qtype", "result", "authenticated_data", "retries", "resolver"}, ) timeoutCounter := prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "dns_timeout", Help: "Counter of various types of DNS query timeouts", }, []string{"qtype", "type", "resolver"}, ) stats.MustRegister(queryTime, totalLookupTime, timeoutCounter) return &DNSClientImpl{ dnsClient: dnsClient, servers: servers, allowRestrictedAddresses: false, maxTries: maxTries, clk: clk, queryTime: queryTime, totalLookupTime: totalLookupTime, timeoutCounter: timeoutCounter, } }
[ "func", "NewDNSClientImpl", "(", "readTimeout", "time", ".", "Duration", ",", "servers", "[", "]", "string", ",", "stats", "metrics", ".", "Scope", ",", "clk", "clock", ".", "Clock", ",", "maxTries", "int", ",", ")", "*", "DNSClientImpl", "{", "stats", "=", "stats", ".", "NewScope", "(", "\"", "\"", ")", "\n", "// TODO(jmhodges): make constructor use an Option func pattern", "dnsClient", ":=", "new", "(", "dns", ".", "Client", ")", "\n\n", "// Set timeout for underlying net.Conn", "dnsClient", ".", "ReadTimeout", "=", "readTimeout", "\n", "dnsClient", ".", "Net", "=", "\"", "\"", "\n\n", "queryTime", ":=", "prometheus", ".", "NewHistogramVec", "(", "prometheus", ".", "HistogramOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "Buckets", ":", "metrics", ".", "InternetFacingBuckets", ",", "}", ",", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", ")", "\n", "totalLookupTime", ":=", "prometheus", ".", "NewHistogramVec", "(", "prometheus", ".", "HistogramOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "Buckets", ":", "metrics", ".", "InternetFacingBuckets", ",", "}", ",", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", ")", "\n", "timeoutCounter", ":=", "prometheus", ".", "NewCounterVec", "(", "prometheus", ".", "CounterOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ",", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", ")", "\n", "stats", ".", "MustRegister", "(", "queryTime", ",", "totalLookupTime", ",", "timeoutCounter", ")", "\n\n", "return", "&", "DNSClientImpl", "{", "dnsClient", ":", "dnsClient", ",", "servers", ":", "servers", ",", "allowRestrictedAddresses", ":", "false", ",", "maxTries", ":", "maxTries", ",", "clk", ":", "clk", ",", "queryTime", ":", "queryTime", ",", "totalLookupTime", ":", "totalLookupTime", ",", "timeoutCounter", ":", "timeoutCounter", ",", "}", "\n", "}" ]
// NewDNSClientImpl constructs a new DNS resolver object that utilizes the // provided list of DNS servers for resolution.
[ "NewDNSClientImpl", "constructs", "a", "new", "DNS", "resolver", "object", "that", "utilizes", "the", "provided", "list", "of", "DNS", "servers", "for", "resolution", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/bdns/dns.go#L175-L225
train
letsencrypt/boulder
bdns/dns.go
LookupTXT
func (dnsClient *DNSClientImpl) LookupTXT(ctx context.Context, hostname string) ([]string, []string, error) { var txt []string dnsType := dns.TypeTXT r, err := dnsClient.exchangeOne(ctx, hostname, dnsType) if err != nil { return nil, nil, &DNSError{dnsType, hostname, err, -1} } if r.Rcode != dns.RcodeSuccess { return nil, nil, &DNSError{dnsType, hostname, nil, r.Rcode} } for _, answer := range r.Answer { if answer.Header().Rrtype == dnsType { if txtRec, ok := answer.(*dns.TXT); ok { txt = append(txt, strings.Join(txtRec.Txt, "")) } } } authorities := []string{} for _, a := range r.Ns { authorities = append(authorities, a.String()) } return txt, authorities, err }
go
func (dnsClient *DNSClientImpl) LookupTXT(ctx context.Context, hostname string) ([]string, []string, error) { var txt []string dnsType := dns.TypeTXT r, err := dnsClient.exchangeOne(ctx, hostname, dnsType) if err != nil { return nil, nil, &DNSError{dnsType, hostname, err, -1} } if r.Rcode != dns.RcodeSuccess { return nil, nil, &DNSError{dnsType, hostname, nil, r.Rcode} } for _, answer := range r.Answer { if answer.Header().Rrtype == dnsType { if txtRec, ok := answer.(*dns.TXT); ok { txt = append(txt, strings.Join(txtRec.Txt, "")) } } } authorities := []string{} for _, a := range r.Ns { authorities = append(authorities, a.String()) } return txt, authorities, err }
[ "func", "(", "dnsClient", "*", "DNSClientImpl", ")", "LookupTXT", "(", "ctx", "context", ".", "Context", ",", "hostname", "string", ")", "(", "[", "]", "string", ",", "[", "]", "string", ",", "error", ")", "{", "var", "txt", "[", "]", "string", "\n", "dnsType", ":=", "dns", ".", "TypeTXT", "\n", "r", ",", "err", ":=", "dnsClient", ".", "exchangeOne", "(", "ctx", ",", "hostname", ",", "dnsType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "&", "DNSError", "{", "dnsType", ",", "hostname", ",", "err", ",", "-", "1", "}", "\n", "}", "\n", "if", "r", ".", "Rcode", "!=", "dns", ".", "RcodeSuccess", "{", "return", "nil", ",", "nil", ",", "&", "DNSError", "{", "dnsType", ",", "hostname", ",", "nil", ",", "r", ".", "Rcode", "}", "\n", "}", "\n\n", "for", "_", ",", "answer", ":=", "range", "r", ".", "Answer", "{", "if", "answer", ".", "Header", "(", ")", ".", "Rrtype", "==", "dnsType", "{", "if", "txtRec", ",", "ok", ":=", "answer", ".", "(", "*", "dns", ".", "TXT", ")", ";", "ok", "{", "txt", "=", "append", "(", "txt", ",", "strings", ".", "Join", "(", "txtRec", ".", "Txt", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "authorities", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "a", ":=", "range", "r", ".", "Ns", "{", "authorities", "=", "append", "(", "authorities", ",", "a", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "return", "txt", ",", "authorities", ",", "err", "\n", "}" ]
// LookupTXT sends a DNS query to find all TXT records associated with // the provided hostname which it returns along with the returned // DNS authority section.
[ "LookupTXT", "sends", "a", "DNS", "query", "to", "find", "all", "TXT", "records", "associated", "with", "the", "provided", "hostname", "which", "it", "returns", "along", "with", "the", "returned", "DNS", "authority", "section", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/bdns/dns.go#L360-L385
train
letsencrypt/boulder
bdns/dns.go
LookupCAA
func (dnsClient *DNSClientImpl) LookupCAA(ctx context.Context, hostname string) ([]*dns.CAA, error) { dnsType := dns.TypeCAA r, err := dnsClient.exchangeOne(ctx, hostname, dnsType) if err != nil { return nil, &DNSError{dnsType, hostname, err, -1} } if r.Rcode == dns.RcodeServerFailure { return nil, &DNSError{dnsType, hostname, nil, r.Rcode} } var CAAs []*dns.CAA for _, answer := range r.Answer { if caaR, ok := answer.(*dns.CAA); ok { CAAs = append(CAAs, caaR) } } return CAAs, nil }
go
func (dnsClient *DNSClientImpl) LookupCAA(ctx context.Context, hostname string) ([]*dns.CAA, error) { dnsType := dns.TypeCAA r, err := dnsClient.exchangeOne(ctx, hostname, dnsType) if err != nil { return nil, &DNSError{dnsType, hostname, err, -1} } if r.Rcode == dns.RcodeServerFailure { return nil, &DNSError{dnsType, hostname, nil, r.Rcode} } var CAAs []*dns.CAA for _, answer := range r.Answer { if caaR, ok := answer.(*dns.CAA); ok { CAAs = append(CAAs, caaR) } } return CAAs, nil }
[ "func", "(", "dnsClient", "*", "DNSClientImpl", ")", "LookupCAA", "(", "ctx", "context", ".", "Context", ",", "hostname", "string", ")", "(", "[", "]", "*", "dns", ".", "CAA", ",", "error", ")", "{", "dnsType", ":=", "dns", ".", "TypeCAA", "\n", "r", ",", "err", ":=", "dnsClient", ".", "exchangeOne", "(", "ctx", ",", "hostname", ",", "dnsType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "DNSError", "{", "dnsType", ",", "hostname", ",", "err", ",", "-", "1", "}", "\n", "}", "\n\n", "if", "r", ".", "Rcode", "==", "dns", ".", "RcodeServerFailure", "{", "return", "nil", ",", "&", "DNSError", "{", "dnsType", ",", "hostname", ",", "nil", ",", "r", ".", "Rcode", "}", "\n", "}", "\n\n", "var", "CAAs", "[", "]", "*", "dns", ".", "CAA", "\n", "for", "_", ",", "answer", ":=", "range", "r", ".", "Answer", "{", "if", "caaR", ",", "ok", ":=", "answer", ".", "(", "*", "dns", ".", "CAA", ")", ";", "ok", "{", "CAAs", "=", "append", "(", "CAAs", ",", "caaR", ")", "\n", "}", "\n", "}", "\n", "return", "CAAs", ",", "nil", "\n", "}" ]
// LookupCAA sends a DNS query to find all CAA records associated with // the provided hostname.
[ "LookupCAA", "sends", "a", "DNS", "query", "to", "find", "all", "CAA", "records", "associated", "with", "the", "provided", "hostname", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/bdns/dns.go#L465-L483
train
letsencrypt/boulder
bdns/dns.go
LookupMX
func (dnsClient *DNSClientImpl) LookupMX(ctx context.Context, hostname string) ([]string, error) { dnsType := dns.TypeMX r, err := dnsClient.exchangeOne(ctx, hostname, dnsType) if err != nil { return nil, &DNSError{dnsType, hostname, err, -1} } if r.Rcode != dns.RcodeSuccess { return nil, &DNSError{dnsType, hostname, nil, r.Rcode} } var results []string for _, answer := range r.Answer { if mx, ok := answer.(*dns.MX); ok { results = append(results, mx.Mx) } } return results, nil }
go
func (dnsClient *DNSClientImpl) LookupMX(ctx context.Context, hostname string) ([]string, error) { dnsType := dns.TypeMX r, err := dnsClient.exchangeOne(ctx, hostname, dnsType) if err != nil { return nil, &DNSError{dnsType, hostname, err, -1} } if r.Rcode != dns.RcodeSuccess { return nil, &DNSError{dnsType, hostname, nil, r.Rcode} } var results []string for _, answer := range r.Answer { if mx, ok := answer.(*dns.MX); ok { results = append(results, mx.Mx) } } return results, nil }
[ "func", "(", "dnsClient", "*", "DNSClientImpl", ")", "LookupMX", "(", "ctx", "context", ".", "Context", ",", "hostname", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "dnsType", ":=", "dns", ".", "TypeMX", "\n", "r", ",", "err", ":=", "dnsClient", ".", "exchangeOne", "(", "ctx", ",", "hostname", ",", "dnsType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "DNSError", "{", "dnsType", ",", "hostname", ",", "err", ",", "-", "1", "}", "\n", "}", "\n", "if", "r", ".", "Rcode", "!=", "dns", ".", "RcodeSuccess", "{", "return", "nil", ",", "&", "DNSError", "{", "dnsType", ",", "hostname", ",", "nil", ",", "r", ".", "Rcode", "}", "\n", "}", "\n\n", "var", "results", "[", "]", "string", "\n", "for", "_", ",", "answer", ":=", "range", "r", ".", "Answer", "{", "if", "mx", ",", "ok", ":=", "answer", ".", "(", "*", "dns", ".", "MX", ")", ";", "ok", "{", "results", "=", "append", "(", "results", ",", "mx", ".", "Mx", ")", "\n", "}", "\n", "}", "\n\n", "return", "results", ",", "nil", "\n", "}" ]
// LookupMX sends a DNS query to find a MX record associated hostname and returns the // record target.
[ "LookupMX", "sends", "a", "DNS", "query", "to", "find", "a", "MX", "record", "associated", "hostname", "and", "returns", "the", "record", "target", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/bdns/dns.go#L487-L505
train
letsencrypt/boulder
cmd/gen-key/rsa.go
rsaArgs
func rsaArgs(label string, modulusLen, exponent uint, keyID []byte) generateArgs { // Encode as unpadded big endian encoded byte slice expSlice := big.NewInt(int64(exponent)).Bytes() log.Printf("\tEncoded public exponent (%d) as: %0X\n", exponent, expSlice) return generateArgs{ mechanism: []*pkcs11.Mechanism{ pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_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), // Allow the key to verify signatures pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true), // Set requested modulus length pkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, modulusLen), // Set requested public exponent pkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, expSlice), }, 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 create signatures pkcs11.NewAttribute(pkcs11.CKA_SIGN, true), }, } }
go
func rsaArgs(label string, modulusLen, exponent uint, keyID []byte) generateArgs { // Encode as unpadded big endian encoded byte slice expSlice := big.NewInt(int64(exponent)).Bytes() log.Printf("\tEncoded public exponent (%d) as: %0X\n", exponent, expSlice) return generateArgs{ mechanism: []*pkcs11.Mechanism{ pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_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), // Allow the key to verify signatures pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true), // Set requested modulus length pkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, modulusLen), // Set requested public exponent pkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, expSlice), }, 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 create signatures pkcs11.NewAttribute(pkcs11.CKA_SIGN, true), }, } }
[ "func", "rsaArgs", "(", "label", "string", ",", "modulusLen", ",", "exponent", "uint", ",", "keyID", "[", "]", "byte", ")", "generateArgs", "{", "// Encode as unpadded big endian encoded byte slice", "expSlice", ":=", "big", ".", "NewInt", "(", "int64", "(", "exponent", ")", ")", ".", "Bytes", "(", ")", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "exponent", ",", "expSlice", ")", "\n", "return", "generateArgs", "{", "mechanism", ":", "[", "]", "*", "pkcs11", ".", "Mechanism", "{", "pkcs11", ".", "NewMechanism", "(", "pkcs11", ".", "CKM_RSA_PKCS_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", ")", ",", "// Allow the key to verify signatures", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_VERIFY", ",", "true", ")", ",", "// Set requested modulus length", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_MODULUS_BITS", ",", "modulusLen", ")", ",", "// Set requested public exponent", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_PUBLIC_EXPONENT", ",", "expSlice", ")", ",", "}", ",", "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 create signatures", "pkcs11", ".", "NewAttribute", "(", "pkcs11", ".", "CKA_SIGN", ",", "true", ")", ",", "}", ",", "}", "\n", "}" ]
// rsaArgs constructs the private and public key template attributes sent to the // device and specifies which mechanism should be used. modulusLen specifies the // length of the modulus to be generated on the device in bits and exponent // specifies the public exponent that should be used.
[ "rsaArgs", "constructs", "the", "private", "and", "public", "key", "template", "attributes", "sent", "to", "the", "device", "and", "specifies", "which", "mechanism", "should", "be", "used", ".", "modulusLen", "specifies", "the", "length", "of", "the", "modulus", "to", "be", "generated", "on", "the", "device", "in", "bits", "and", "exponent", "specifies", "the", "public", "exponent", "that", "should", "be", "used", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/gen-key/rsa.go#L21-L52
train
letsencrypt/boulder
cmd/gen-key/rsa.go
rsaPub
func rsaPub(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, modulusLen, exponent uint) (*rsa.PublicKey, error) { pubKey, err := pkcs11helpers.GetRSAPublicKey(ctx, session, object) if err != nil { return nil, err } if pubKey.E != int(exponent) { return nil, errors.New("returned CKA_PUBLIC_EXPONENT doesn't match expected exponent") } if pubKey.N.BitLen() != int(modulusLen) { return nil, errors.New("returned CKA_MODULUS isn't of the expected bit length") } log.Printf("\tPublic exponent: %d\n", pubKey.E) log.Printf("\tModulus: (%d bits) %X\n", pubKey.N.BitLen(), pubKey.N.Bytes()) return pubKey, nil }
go
func rsaPub(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, modulusLen, exponent uint) (*rsa.PublicKey, error) { pubKey, err := pkcs11helpers.GetRSAPublicKey(ctx, session, object) if err != nil { return nil, err } if pubKey.E != int(exponent) { return nil, errors.New("returned CKA_PUBLIC_EXPONENT doesn't match expected exponent") } if pubKey.N.BitLen() != int(modulusLen) { return nil, errors.New("returned CKA_MODULUS isn't of the expected bit length") } log.Printf("\tPublic exponent: %d\n", pubKey.E) log.Printf("\tModulus: (%d bits) %X\n", pubKey.N.BitLen(), pubKey.N.Bytes()) return pubKey, nil }
[ "func", "rsaPub", "(", "ctx", "pkcs11helpers", ".", "PKCtx", ",", "session", "pkcs11", ".", "SessionHandle", ",", "object", "pkcs11", ".", "ObjectHandle", ",", "modulusLen", ",", "exponent", "uint", ")", "(", "*", "rsa", ".", "PublicKey", ",", "error", ")", "{", "pubKey", ",", "err", ":=", "pkcs11helpers", ".", "GetRSAPublicKey", "(", "ctx", ",", "session", ",", "object", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "pubKey", ".", "E", "!=", "int", "(", "exponent", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "pubKey", ".", "N", ".", "BitLen", "(", ")", "!=", "int", "(", "modulusLen", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "pubKey", ".", "E", ")", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "pubKey", ".", "N", ".", "BitLen", "(", ")", ",", "pubKey", ".", "N", ".", "Bytes", "(", ")", ")", "\n", "return", "pubKey", ",", "nil", "\n", "}" ]
// rsaPub extracts the generated public key, specified by the provided object // handle, and constructs a rsa.PublicKey. It also checks that the key has the // correct length modulus and that the public exponent is what was requested in // the public key template.
[ "rsaPub", "extracts", "the", "generated", "public", "key", "specified", "by", "the", "provided", "object", "handle", "and", "constructs", "a", "rsa", ".", "PublicKey", ".", "It", "also", "checks", "that", "the", "key", "has", "the", "correct", "length", "modulus", "and", "that", "the", "public", "exponent", "is", "what", "was", "requested", "in", "the", "public", "key", "template", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/gen-key/rsa.go#L58-L72
train
letsencrypt/boulder
cmd/gen-key/rsa.go
rsaVerify
func rsaVerify(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, pub *rsa.PublicKey) error { nonce, err := getRandomBytes(ctx, session) if err != nil { return fmt.Errorf("Failed to retrieve nonce: %s", err) } log.Printf("\tConstructed nonce: %d (%X)\n", big.NewInt(0).SetBytes(nonce), nonce) digest := sha256.Sum256(nonce) log.Printf("\tMessage SHA-256 hash: %X\n", digest) signature, err := pkcs11helpers.Sign(ctx, session, object, pkcs11helpers.RSAKey, digest[:], crypto.SHA256) if err != nil { return fmt.Errorf("Failed to sign data: %s", err) } log.Printf("\tMessage signature: %X\n", signature) err = rsa.VerifyPKCS1v15(pub, crypto.SHA256, digest[:], signature) if err != nil { return fmt.Errorf("Failed to verify signature: %s", err) } log.Println("\tSignature verified") return nil }
go
func rsaVerify(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, pub *rsa.PublicKey) error { nonce, err := getRandomBytes(ctx, session) if err != nil { return fmt.Errorf("Failed to retrieve nonce: %s", err) } log.Printf("\tConstructed nonce: %d (%X)\n", big.NewInt(0).SetBytes(nonce), nonce) digest := sha256.Sum256(nonce) log.Printf("\tMessage SHA-256 hash: %X\n", digest) signature, err := pkcs11helpers.Sign(ctx, session, object, pkcs11helpers.RSAKey, digest[:], crypto.SHA256) if err != nil { return fmt.Errorf("Failed to sign data: %s", err) } log.Printf("\tMessage signature: %X\n", signature) err = rsa.VerifyPKCS1v15(pub, crypto.SHA256, digest[:], signature) if err != nil { return fmt.Errorf("Failed to verify signature: %s", err) } log.Println("\tSignature verified") return nil }
[ "func", "rsaVerify", "(", "ctx", "pkcs11helpers", ".", "PKCtx", ",", "session", "pkcs11", ".", "SessionHandle", ",", "object", "pkcs11", ".", "ObjectHandle", ",", "pub", "*", "rsa", ".", "PublicKey", ")", "error", "{", "nonce", ",", "err", ":=", "getRandomBytes", "(", "ctx", ",", "session", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "big", ".", "NewInt", "(", "0", ")", ".", "SetBytes", "(", "nonce", ")", ",", "nonce", ")", "\n", "digest", ":=", "sha256", ".", "Sum256", "(", "nonce", ")", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "digest", ")", "\n", "signature", ",", "err", ":=", "pkcs11helpers", ".", "Sign", "(", "ctx", ",", "session", ",", "object", ",", "pkcs11helpers", ".", "RSAKey", ",", "digest", "[", ":", "]", ",", "crypto", ".", "SHA256", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "signature", ")", "\n", "err", "=", "rsa", ".", "VerifyPKCS1v15", "(", "pub", ",", "crypto", ".", "SHA256", ",", "digest", "[", ":", "]", ",", "signature", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "log", ".", "Println", "(", "\"", "\\t", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// rsaVerify 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.
[ "rsaVerify", "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/rsa.go#L78-L97
train
letsencrypt/boulder
cmd/gen-key/rsa.go
rsaGenerate
func rsaGenerate(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, label string, modulusLen, pubExponent uint) (*rsa.PublicKey, error) { keyID := make([]byte, 4) _, err := rand.Read(keyID) if err != nil { return nil, err } log.Printf("Generating RSA key with %d bit modulus and public exponent %d and ID %x\n", modulusLen, pubExponent, keyID) args := rsaArgs(label, modulusLen, pubExponent, 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 := rsaPub(ctx, session, pub, modulusLen, pubExponent) if err != nil { return nil, err } log.Println("Extracted public key") log.Println("Verifying public key") err = rsaVerify(ctx, session, priv, pk) if err != nil { return nil, err } return pk, nil }
go
func rsaGenerate(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, label string, modulusLen, pubExponent uint) (*rsa.PublicKey, error) { keyID := make([]byte, 4) _, err := rand.Read(keyID) if err != nil { return nil, err } log.Printf("Generating RSA key with %d bit modulus and public exponent %d and ID %x\n", modulusLen, pubExponent, keyID) args := rsaArgs(label, modulusLen, pubExponent, 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 := rsaPub(ctx, session, pub, modulusLen, pubExponent) if err != nil { return nil, err } log.Println("Extracted public key") log.Println("Verifying public key") err = rsaVerify(ctx, session, priv, pk) if err != nil { return nil, err } return pk, nil }
[ "func", "rsaGenerate", "(", "ctx", "pkcs11helpers", ".", "PKCtx", ",", "session", "pkcs11", ".", "SessionHandle", ",", "label", "string", ",", "modulusLen", ",", "pubExponent", "uint", ")", "(", "*", "rsa", ".", "PublicKey", ",", "error", ")", "{", "keyID", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "_", ",", "err", ":=", "rand", ".", "Read", "(", "keyID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "modulusLen", ",", "pubExponent", ",", "keyID", ")", "\n", "args", ":=", "rsaArgs", "(", "label", ",", "modulusLen", ",", "pubExponent", ",", "keyID", ")", "\n", "pub", ",", "priv", ",", "err", ":=", "ctx", ".", "GenerateKeyPair", "(", "session", ",", "args", ".", "mechanism", ",", "args", ".", "publicAttrs", ",", "args", ".", "privateAttrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "pk", ",", "err", ":=", "rsaPub", "(", "ctx", ",", "session", ",", "pub", ",", "modulusLen", ",", "pubExponent", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "err", "=", "rsaVerify", "(", "ctx", ",", "session", ",", "priv", ",", "pk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "pk", ",", "nil", "\n", "}" ]
// rsaGenerate is used to generate and verify a RSA key pair of the size // specified by modulusLen and with the exponent specified by pubExponent. // It returns the public part of the generated key pair as a rsa.PublicKey.
[ "rsaGenerate", "is", "used", "to", "generate", "and", "verify", "a", "RSA", "key", "pair", "of", "the", "size", "specified", "by", "modulusLen", "and", "with", "the", "exponent", "specified", "by", "pubExponent", ".", "It", "returns", "the", "public", "part", "of", "the", "generated", "key", "pair", "as", "a", "rsa", ".", "PublicKey", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/gen-key/rsa.go#L102-L127
train
letsencrypt/boulder
log/log.go
New
func New(log *syslog.Writer, stdoutLogLevel int, syslogLogLevel int) (Logger, error) { if log == nil { return nil, errors.New("Attempted to use a nil System Logger.") } return &impl{ &bothWriter{log, stdoutLogLevel, syslogLogLevel, clock.Default()}, }, nil }
go
func New(log *syslog.Writer, stdoutLogLevel int, syslogLogLevel int) (Logger, error) { if log == nil { return nil, errors.New("Attempted to use a nil System Logger.") } return &impl{ &bothWriter{log, stdoutLogLevel, syslogLogLevel, clock.Default()}, }, nil }
[ "func", "New", "(", "log", "*", "syslog", ".", "Writer", ",", "stdoutLogLevel", "int", ",", "syslogLogLevel", "int", ")", "(", "Logger", ",", "error", ")", "{", "if", "log", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "impl", "{", "&", "bothWriter", "{", "log", ",", "stdoutLogLevel", ",", "syslogLogLevel", ",", "clock", ".", "Default", "(", ")", "}", ",", "}", ",", "nil", "\n", "}" ]
// New returns a new Logger that uses the given syslog.Writer as a backend.
[ "New", "returns", "a", "new", "Logger", "that", "uses", "the", "given", "syslog", ".", "Writer", "as", "a", "backend", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L55-L62
train
letsencrypt/boulder
log/log.go
initialize
func initialize() { // defaultPriority is never used because we always use specific priority-based // logging methods. const defaultPriority = syslog.LOG_INFO | syslog.LOG_LOCAL0 syslogger, err := syslog.Dial("", "", defaultPriority, "test") if err != nil { panic(err) } logger, err := New(syslogger, int(syslog.LOG_DEBUG), int(syslog.LOG_DEBUG)) if err != nil { panic(err) } _ = Set(logger) }
go
func initialize() { // defaultPriority is never used because we always use specific priority-based // logging methods. const defaultPriority = syslog.LOG_INFO | syslog.LOG_LOCAL0 syslogger, err := syslog.Dial("", "", defaultPriority, "test") if err != nil { panic(err) } logger, err := New(syslogger, int(syslog.LOG_DEBUG), int(syslog.LOG_DEBUG)) if err != nil { panic(err) } _ = Set(logger) }
[ "func", "initialize", "(", ")", "{", "// defaultPriority is never used because we always use specific priority-based", "// logging methods.", "const", "defaultPriority", "=", "syslog", ".", "LOG_INFO", "|", "syslog", ".", "LOG_LOCAL0", "\n", "syslogger", ",", "err", ":=", "syslog", ".", "Dial", "(", "\"", "\"", ",", "\"", "\"", ",", "defaultPriority", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "logger", ",", "err", ":=", "New", "(", "syslogger", ",", "int", "(", "syslog", ".", "LOG_DEBUG", ")", ",", "int", "(", "syslog", ".", "LOG_DEBUG", ")", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "_", "=", "Set", "(", "logger", ")", "\n", "}" ]
// initialize should only be used in unit tests.
[ "initialize", "should", "only", "be", "used", "in", "unit", "tests", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L65-L79
train
letsencrypt/boulder
log/log.go
Set
func Set(logger Logger) (err error) { if _Singleton.log != nil { err = errors.New("You may not call Set after it has already been implicitly or explicitly set.") _Singleton.log.Warning(err.Error()) } else { _Singleton.log = logger } return }
go
func Set(logger Logger) (err error) { if _Singleton.log != nil { err = errors.New("You may not call Set after it has already been implicitly or explicitly set.") _Singleton.log.Warning(err.Error()) } else { _Singleton.log = logger } return }
[ "func", "Set", "(", "logger", "Logger", ")", "(", "err", "error", ")", "{", "if", "_Singleton", ".", "log", "!=", "nil", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "_Singleton", ".", "log", ".", "Warning", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "{", "_Singleton", ".", "log", "=", "logger", "\n", "}", "\n", "return", "\n", "}" ]
// Set configures the singleton Logger. This method // must only be called once, and before calling Get the // first time.
[ "Set", "configures", "the", "singleton", "Logger", ".", "This", "method", "must", "only", "be", "called", "once", "and", "before", "calling", "Get", "the", "first", "time", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L84-L92
train
letsencrypt/boulder
log/log.go
Get
func Get() Logger { _Singleton.once.Do(func() { if _Singleton.log == nil { initialize() } }) return _Singleton.log }
go
func Get() Logger { _Singleton.once.Do(func() { if _Singleton.log == nil { initialize() } }) return _Singleton.log }
[ "func", "Get", "(", ")", "Logger", "{", "_Singleton", ".", "once", ".", "Do", "(", "func", "(", ")", "{", "if", "_Singleton", ".", "log", "==", "nil", "{", "initialize", "(", ")", "\n", "}", "\n", "}", ")", "\n\n", "return", "_Singleton", ".", "log", "\n", "}" ]
// Get obtains the singleton Logger. If Set has not been called first, this // method initializes with basic defaults. The basic defaults cannot error, and // subsequent access to an already-set Logger also cannot error, so this method is // error-safe.
[ "Get", "obtains", "the", "singleton", "Logger", ".", "If", "Set", "has", "not", "been", "called", "first", "this", "method", "initializes", "with", "basic", "defaults", ".", "The", "basic", "defaults", "cannot", "error", "and", "subsequent", "access", "to", "an", "already", "-", "set", "Logger", "also", "cannot", "error", "so", "this", "method", "is", "error", "-", "safe", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L98-L106
train
letsencrypt/boulder
log/log.go
logAtLevel
func (w *bothWriter) logAtLevel(level syslog.Priority, msg string) { var prefix string var err error const red = "\033[31m\033[1m" const yellow = "\033[33m" switch syslogAllowed := int(level) <= w.syslogLevel; level { case syslog.LOG_ERR: if syslogAllowed { err = w.Err(msg) } prefix = red + "E" case syslog.LOG_WARNING: if syslogAllowed { err = w.Warning(msg) } prefix = yellow + "W" case syslog.LOG_INFO: if syslogAllowed { err = w.Info(msg) } prefix = "I" case syslog.LOG_DEBUG: if syslogAllowed { err = w.Debug(msg) } prefix = "D" default: err = w.Err(fmt.Sprintf("%s (unknown logging level: %d)", msg, int(level))) } if err != nil { fmt.Fprintf(os.Stderr, "Failed to write to syslog: %s (%s)\n", msg, err) } var reset string if strings.HasPrefix(prefix, "\033") { reset = "\033[0m" } if int(level) <= w.stdoutLevel { fmt.Printf("%s%s %s %s%s\n", prefix, w.clk.Now().Format("150405"), path.Base(os.Args[0]), msg, reset) } }
go
func (w *bothWriter) logAtLevel(level syslog.Priority, msg string) { var prefix string var err error const red = "\033[31m\033[1m" const yellow = "\033[33m" switch syslogAllowed := int(level) <= w.syslogLevel; level { case syslog.LOG_ERR: if syslogAllowed { err = w.Err(msg) } prefix = red + "E" case syslog.LOG_WARNING: if syslogAllowed { err = w.Warning(msg) } prefix = yellow + "W" case syslog.LOG_INFO: if syslogAllowed { err = w.Info(msg) } prefix = "I" case syslog.LOG_DEBUG: if syslogAllowed { err = w.Debug(msg) } prefix = "D" default: err = w.Err(fmt.Sprintf("%s (unknown logging level: %d)", msg, int(level))) } if err != nil { fmt.Fprintf(os.Stderr, "Failed to write to syslog: %s (%s)\n", msg, err) } var reset string if strings.HasPrefix(prefix, "\033") { reset = "\033[0m" } if int(level) <= w.stdoutLevel { fmt.Printf("%s%s %s %s%s\n", prefix, w.clk.Now().Format("150405"), path.Base(os.Args[0]), msg, reset) } }
[ "func", "(", "w", "*", "bothWriter", ")", "logAtLevel", "(", "level", "syslog", ".", "Priority", ",", "msg", "string", ")", "{", "var", "prefix", "string", "\n", "var", "err", "error", "\n\n", "const", "red", "=", "\"", "\\033", "\\033", "\"", "\n", "const", "yellow", "=", "\"", "\\033", "\"", "\n\n", "switch", "syslogAllowed", ":=", "int", "(", "level", ")", "<=", "w", ".", "syslogLevel", ";", "level", "{", "case", "syslog", ".", "LOG_ERR", ":", "if", "syslogAllowed", "{", "err", "=", "w", ".", "Err", "(", "msg", ")", "\n", "}", "\n", "prefix", "=", "red", "+", "\"", "\"", "\n", "case", "syslog", ".", "LOG_WARNING", ":", "if", "syslogAllowed", "{", "err", "=", "w", ".", "Warning", "(", "msg", ")", "\n", "}", "\n", "prefix", "=", "yellow", "+", "\"", "\"", "\n", "case", "syslog", ".", "LOG_INFO", ":", "if", "syslogAllowed", "{", "err", "=", "w", ".", "Info", "(", "msg", ")", "\n", "}", "\n", "prefix", "=", "\"", "\"", "\n", "case", "syslog", ".", "LOG_DEBUG", ":", "if", "syslogAllowed", "{", "err", "=", "w", ".", "Debug", "(", "msg", ")", "\n", "}", "\n", "prefix", "=", "\"", "\"", "\n", "default", ":", "err", "=", "w", ".", "Err", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ",", "int", "(", "level", ")", ")", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "msg", ",", "err", ")", "\n", "}", "\n\n", "var", "reset", "string", "\n", "if", "strings", ".", "HasPrefix", "(", "prefix", ",", "\"", "\\033", "\"", ")", "{", "reset", "=", "\"", "\\033", "\"", "\n", "}", "\n\n", "if", "int", "(", "level", ")", "<=", "w", ".", "stdoutLevel", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "prefix", ",", "w", ".", "clk", ".", "Now", "(", ")", ".", "Format", "(", "\"", "\"", ")", ",", "path", ".", "Base", "(", "os", ".", "Args", "[", "0", "]", ")", ",", "msg", ",", "reset", ")", "\n", "}", "\n", "}" ]
// Log the provided message at the appropriate level, writing to // both stdout and the Logger
[ "Log", "the", "provided", "message", "at", "the", "appropriate", "level", "writing", "to", "both", "stdout", "and", "the", "Logger" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L122-L171
train
letsencrypt/boulder
log/log.go
caller
func caller(level int) string { _, file, line, _ := runtime.Caller(level) splits := strings.Split(file, "/") filename := splits[len(splits)-1] return fmt.Sprintf("%s:%d:", filename, line) }
go
func caller(level int) string { _, file, line, _ := runtime.Caller(level) splits := strings.Split(file, "/") filename := splits[len(splits)-1] return fmt.Sprintf("%s:%d:", filename, line) }
[ "func", "caller", "(", "level", "int", ")", "string", "{", "_", ",", "file", ",", "line", ",", "_", ":=", "runtime", ".", "Caller", "(", "level", ")", "\n", "splits", ":=", "strings", ".", "Split", "(", "file", ",", "\"", "\"", ")", "\n", "filename", ":=", "splits", "[", "len", "(", "splits", ")", "-", "1", "]", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filename", ",", "line", ")", "\n", "}" ]
// Return short format caller info for panic events, skipping to before the // panic handler.
[ "Return", "short", "format", "caller", "info", "for", "panic", "events", "skipping", "to", "before", "the", "panic", "handler", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L180-L185
train
letsencrypt/boulder
log/log.go
AuditPanic
func (log *impl) AuditPanic() { if err := recover(); err != nil { buf := make([]byte, 8192) log.AuditErrf("Panic caused by err: %s", err) runtime.Stack(buf, false) log.AuditErrf("Stack Trace (Current frame) %s", buf) runtime.Stack(buf, true) log.Warningf("Stack Trace (All frames): %s", buf) } }
go
func (log *impl) AuditPanic() { if err := recover(); err != nil { buf := make([]byte, 8192) log.AuditErrf("Panic caused by err: %s", err) runtime.Stack(buf, false) log.AuditErrf("Stack Trace (Current frame) %s", buf) runtime.Stack(buf, true) log.Warningf("Stack Trace (All frames): %s", buf) } }
[ "func", "(", "log", "*", "impl", ")", "AuditPanic", "(", ")", "{", "if", "err", ":=", "recover", "(", ")", ";", "err", "!=", "nil", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "8192", ")", "\n", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "err", ")", "\n\n", "runtime", ".", "Stack", "(", "buf", ",", "false", ")", "\n", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "buf", ")", "\n\n", "runtime", ".", "Stack", "(", "buf", ",", "true", ")", "\n", "log", ".", "Warningf", "(", "\"", "\"", ",", "buf", ")", "\n", "}", "\n", "}" ]
// AuditPanic catches panicking executables. This method should be added // in a defer statement as early as possible
[ "AuditPanic", "catches", "panicking", "executables", ".", "This", "method", "should", "be", "added", "in", "a", "defer", "statement", "as", "early", "as", "possible" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L189-L200
train
letsencrypt/boulder
log/log.go
Err
func (log *impl) Err(msg string) { log.auditAtLevel(syslog.LOG_ERR, msg) }
go
func (log *impl) Err(msg string) { log.auditAtLevel(syslog.LOG_ERR, msg) }
[ "func", "(", "log", "*", "impl", ")", "Err", "(", "msg", "string", ")", "{", "log", ".", "auditAtLevel", "(", "syslog", ".", "LOG_ERR", ",", "msg", ")", "\n", "}" ]
// Err level messages are always marked with the audit tag, for special handling // at the upstream system logger.
[ "Err", "level", "messages", "are", "always", "marked", "with", "the", "audit", "tag", "for", "special", "handling", "at", "the", "upstream", "system", "logger", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L204-L206
train
letsencrypt/boulder
log/log.go
Errf
func (log *impl) Errf(format string, a ...interface{}) { log.Err(fmt.Sprintf(format, a...)) }
go
func (log *impl) Errf(format string, a ...interface{}) { log.Err(fmt.Sprintf(format, a...)) }
[ "func", "(", "log", "*", "impl", ")", "Errf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "log", ".", "Err", "(", "fmt", ".", "Sprintf", "(", "format", ",", "a", "...", ")", ")", "\n", "}" ]
// Errf level messages are always marked with the audit tag, for special handling // at the upstream system logger.
[ "Errf", "level", "messages", "are", "always", "marked", "with", "the", "audit", "tag", "for", "special", "handling", "at", "the", "upstream", "system", "logger", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L210-L212
train
letsencrypt/boulder
log/log.go
Warning
func (log *impl) Warning(msg string) { log.w.logAtLevel(syslog.LOG_WARNING, msg) }
go
func (log *impl) Warning(msg string) { log.w.logAtLevel(syslog.LOG_WARNING, msg) }
[ "func", "(", "log", "*", "impl", ")", "Warning", "(", "msg", "string", ")", "{", "log", ".", "w", ".", "logAtLevel", "(", "syslog", ".", "LOG_WARNING", ",", "msg", ")", "\n", "}" ]
// Warning level messages pass through normally.
[ "Warning", "level", "messages", "pass", "through", "normally", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L215-L217
train
letsencrypt/boulder
log/log.go
Warningf
func (log *impl) Warningf(format string, a ...interface{}) { log.Warning(fmt.Sprintf(format, a...)) }
go
func (log *impl) Warningf(format string, a ...interface{}) { log.Warning(fmt.Sprintf(format, a...)) }
[ "func", "(", "log", "*", "impl", ")", "Warningf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "log", ".", "Warning", "(", "fmt", ".", "Sprintf", "(", "format", ",", "a", "...", ")", ")", "\n", "}" ]
// Warningf level messages pass through normally.
[ "Warningf", "level", "messages", "pass", "through", "normally", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L220-L222
train
letsencrypt/boulder
log/log.go
Info
func (log *impl) Info(msg string) { log.w.logAtLevel(syslog.LOG_INFO, msg) }
go
func (log *impl) Info(msg string) { log.w.logAtLevel(syslog.LOG_INFO, msg) }
[ "func", "(", "log", "*", "impl", ")", "Info", "(", "msg", "string", ")", "{", "log", ".", "w", ".", "logAtLevel", "(", "syslog", ".", "LOG_INFO", ",", "msg", ")", "\n", "}" ]
// Info level messages pass through normally.
[ "Info", "level", "messages", "pass", "through", "normally", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L225-L227
train
letsencrypt/boulder
log/log.go
Infof
func (log *impl) Infof(format string, a ...interface{}) { log.Info(fmt.Sprintf(format, a...)) }
go
func (log *impl) Infof(format string, a ...interface{}) { log.Info(fmt.Sprintf(format, a...)) }
[ "func", "(", "log", "*", "impl", ")", "Infof", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "log", ".", "Info", "(", "fmt", ".", "Sprintf", "(", "format", ",", "a", "...", ")", ")", "\n", "}" ]
// Infof level messages pass through normally.
[ "Infof", "level", "messages", "pass", "through", "normally", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L230-L232
train
letsencrypt/boulder
log/log.go
Debug
func (log *impl) Debug(msg string) { log.w.logAtLevel(syslog.LOG_DEBUG, msg) }
go
func (log *impl) Debug(msg string) { log.w.logAtLevel(syslog.LOG_DEBUG, msg) }
[ "func", "(", "log", "*", "impl", ")", "Debug", "(", "msg", "string", ")", "{", "log", ".", "w", ".", "logAtLevel", "(", "syslog", ".", "LOG_DEBUG", ",", "msg", ")", "\n", "}" ]
// Debug level messages pass through normally.
[ "Debug", "level", "messages", "pass", "through", "normally", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L235-L237
train
letsencrypt/boulder
log/log.go
Debugf
func (log *impl) Debugf(format string, a ...interface{}) { log.Debug(fmt.Sprintf(format, a...)) }
go
func (log *impl) Debugf(format string, a ...interface{}) { log.Debug(fmt.Sprintf(format, a...)) }
[ "func", "(", "log", "*", "impl", ")", "Debugf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "log", ".", "Debug", "(", "fmt", ".", "Sprintf", "(", "format", ",", "a", "...", ")", ")", "\n", "}" ]
// Debugf level messages pass through normally.
[ "Debugf", "level", "messages", "pass", "through", "normally", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L240-L242
train
letsencrypt/boulder
log/log.go
AuditInfo
func (log *impl) AuditInfo(msg string) { log.auditAtLevel(syslog.LOG_INFO, msg) }
go
func (log *impl) AuditInfo(msg string) { log.auditAtLevel(syslog.LOG_INFO, msg) }
[ "func", "(", "log", "*", "impl", ")", "AuditInfo", "(", "msg", "string", ")", "{", "log", ".", "auditAtLevel", "(", "syslog", ".", "LOG_INFO", ",", "msg", ")", "\n", "}" ]
// AuditInfo sends an INFO-severity message that is prefixed with the // audit tag, for special handling at the upstream system logger.
[ "AuditInfo", "sends", "an", "INFO", "-", "severity", "message", "that", "is", "prefixed", "with", "the", "audit", "tag", "for", "special", "handling", "at", "the", "upstream", "system", "logger", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L246-L248
train
letsencrypt/boulder
log/log.go
AuditInfof
func (log *impl) AuditInfof(format string, a ...interface{}) { log.AuditInfo(fmt.Sprintf(format, a...)) }
go
func (log *impl) AuditInfof(format string, a ...interface{}) { log.AuditInfo(fmt.Sprintf(format, a...)) }
[ "func", "(", "log", "*", "impl", ")", "AuditInfof", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "log", ".", "AuditInfo", "(", "fmt", ".", "Sprintf", "(", "format", ",", "a", "...", ")", ")", "\n", "}" ]
// AuditInfof sends an INFO-severity message that is prefixed with the // audit tag, for special handling at the upstream system logger.
[ "AuditInfof", "sends", "an", "INFO", "-", "severity", "message", "that", "is", "prefixed", "with", "the", "audit", "tag", "for", "special", "handling", "at", "the", "upstream", "system", "logger", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L252-L254
train
letsencrypt/boulder
log/log.go
AuditObject
func (log *impl) AuditObject(msg string, obj interface{}) { jsonObj, err := json.Marshal(obj) if err != nil { log.auditAtLevel(syslog.LOG_ERR, fmt.Sprintf("Object could not be serialized to JSON. Raw: %+v", obj)) return } log.auditAtLevel(syslog.LOG_INFO, fmt.Sprintf("%s JSON=%s", msg, jsonObj)) }
go
func (log *impl) AuditObject(msg string, obj interface{}) { jsonObj, err := json.Marshal(obj) if err != nil { log.auditAtLevel(syslog.LOG_ERR, fmt.Sprintf("Object could not be serialized to JSON. Raw: %+v", obj)) return } log.auditAtLevel(syslog.LOG_INFO, fmt.Sprintf("%s JSON=%s", msg, jsonObj)) }
[ "func", "(", "log", "*", "impl", ")", "AuditObject", "(", "msg", "string", ",", "obj", "interface", "{", "}", ")", "{", "jsonObj", ",", "err", ":=", "json", ".", "Marshal", "(", "obj", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "auditAtLevel", "(", "syslog", ".", "LOG_ERR", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "obj", ")", ")", "\n", "return", "\n", "}", "\n\n", "log", ".", "auditAtLevel", "(", "syslog", ".", "LOG_INFO", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ",", "jsonObj", ")", ")", "\n", "}" ]
// AuditObject sends an INFO-severity JSON-serialized object message that is prefixed // with the audit tag, for special handling at the upstream system logger.
[ "AuditObject", "sends", "an", "INFO", "-", "severity", "JSON", "-", "serialized", "object", "message", "that", "is", "prefixed", "with", "the", "audit", "tag", "for", "special", "handling", "at", "the", "upstream", "system", "logger", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L258-L266
train
letsencrypt/boulder
log/log.go
AuditErr
func (log *impl) AuditErr(msg string) { log.auditAtLevel(syslog.LOG_ERR, msg) }
go
func (log *impl) AuditErr(msg string) { log.auditAtLevel(syslog.LOG_ERR, msg) }
[ "func", "(", "log", "*", "impl", ")", "AuditErr", "(", "msg", "string", ")", "{", "log", ".", "auditAtLevel", "(", "syslog", ".", "LOG_ERR", ",", "msg", ")", "\n", "}" ]
// AuditErr can format an error for auditing; it does so at ERR level.
[ "AuditErr", "can", "format", "an", "error", "for", "auditing", ";", "it", "does", "so", "at", "ERR", "level", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L269-L271
train
letsencrypt/boulder
log/log.go
AuditErrf
func (log *impl) AuditErrf(format string, a ...interface{}) { log.AuditErr(fmt.Sprintf(format, a...)) }
go
func (log *impl) AuditErrf(format string, a ...interface{}) { log.AuditErr(fmt.Sprintf(format, a...)) }
[ "func", "(", "log", "*", "impl", ")", "AuditErrf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "log", ".", "AuditErr", "(", "fmt", ".", "Sprintf", "(", "format", ",", "a", "...", ")", ")", "\n", "}" ]
// AuditErrf can format an error for auditing; it does so at ERR level.
[ "AuditErrf", "can", "format", "an", "error", "for", "auditing", ";", "it", "does", "so", "at", "ERR", "level", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/log/log.go#L274-L276
train
letsencrypt/boulder
va/caa.go
checkCAA
func (va *ValidationAuthorityImpl) checkCAA( ctx context.Context, identifier core.AcmeIdentifier, params *caaParams) *probs.ProblemDetails { present, valid, records, err := va.checkCAARecords(ctx, identifier, params) if err != nil { return probs.DNS("%v", err) } recordsStr, err := json.Marshal(&records) if err != nil { return probs.CAA("CAA records for %s were malformed", identifier.Value) } accountID, challengeType := "unknown", "unknown" if params.accountURIID != nil { accountID = fmt.Sprintf("%d", *params.accountURIID) } if params.validationMethod != nil { challengeType = *params.validationMethod } va.log.AuditInfof("Checked CAA records for %s, [Present: %t, Account ID: %s, Challenge: %s, Valid for issuance: %t] Records=%s", identifier.Value, present, accountID, challengeType, valid, recordsStr) if !valid { return probs.CAA("CAA record for %s prevents issuance", identifier.Value) } return nil }
go
func (va *ValidationAuthorityImpl) checkCAA( ctx context.Context, identifier core.AcmeIdentifier, params *caaParams) *probs.ProblemDetails { present, valid, records, err := va.checkCAARecords(ctx, identifier, params) if err != nil { return probs.DNS("%v", err) } recordsStr, err := json.Marshal(&records) if err != nil { return probs.CAA("CAA records for %s were malformed", identifier.Value) } accountID, challengeType := "unknown", "unknown" if params.accountURIID != nil { accountID = fmt.Sprintf("%d", *params.accountURIID) } if params.validationMethod != nil { challengeType = *params.validationMethod } va.log.AuditInfof("Checked CAA records for %s, [Present: %t, Account ID: %s, Challenge: %s, Valid for issuance: %t] Records=%s", identifier.Value, present, accountID, challengeType, valid, recordsStr) if !valid { return probs.CAA("CAA record for %s prevents issuance", identifier.Value) } return nil }
[ "func", "(", "va", "*", "ValidationAuthorityImpl", ")", "checkCAA", "(", "ctx", "context", ".", "Context", ",", "identifier", "core", ".", "AcmeIdentifier", ",", "params", "*", "caaParams", ")", "*", "probs", ".", "ProblemDetails", "{", "present", ",", "valid", ",", "records", ",", "err", ":=", "va", ".", "checkCAARecords", "(", "ctx", ",", "identifier", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "probs", ".", "DNS", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "recordsStr", ",", "err", ":=", "json", ".", "Marshal", "(", "&", "records", ")", "\n", "if", "err", "!=", "nil", "{", "return", "probs", ".", "CAA", "(", "\"", "\"", ",", "identifier", ".", "Value", ")", "\n", "}", "\n\n", "accountID", ",", "challengeType", ":=", "\"", "\"", ",", "\"", "\"", "\n", "if", "params", ".", "accountURIID", "!=", "nil", "{", "accountID", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "*", "params", ".", "accountURIID", ")", "\n", "}", "\n", "if", "params", ".", "validationMethod", "!=", "nil", "{", "challengeType", "=", "*", "params", ".", "validationMethod", "\n", "}", "\n\n", "va", ".", "log", ".", "AuditInfof", "(", "\"", "\"", ",", "identifier", ".", "Value", ",", "present", ",", "accountID", ",", "challengeType", ",", "valid", ",", "recordsStr", ")", "\n", "if", "!", "valid", "{", "return", "probs", ".", "CAA", "(", "\"", "\"", ",", "identifier", ".", "Value", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkCAA performs a CAA lookup & validation for the provided identifier. If // the CAA lookup & validation fail a problem is returned.
[ "checkCAA", "performs", "a", "CAA", "lookup", "&", "validation", "for", "the", "provided", "identifier", ".", "If", "the", "CAA", "lookup", "&", "validation", "fail", "a", "problem", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/caa.go#L47-L75
train
letsencrypt/boulder
va/caa.go
criticalUnknown
func (caaSet CAASet) criticalUnknown() bool { if len(caaSet.Unknown) > 0 { for _, caaRecord := range caaSet.Unknown { // The critical flag is the bit with significance 128. However, many CAA // record users have misinterpreted the RFC and concluded that the bit // with significance 1 is the critical bit. This is sufficiently // widespread that that bit must reasonably be considered an alias for // the critical bit. The remaining bits are 0/ignore as proscribed by the // RFC. if (caaRecord.Flag & (128 | 1)) != 0 { return true } } } return false }
go
func (caaSet CAASet) criticalUnknown() bool { if len(caaSet.Unknown) > 0 { for _, caaRecord := range caaSet.Unknown { // The critical flag is the bit with significance 128. However, many CAA // record users have misinterpreted the RFC and concluded that the bit // with significance 1 is the critical bit. This is sufficiently // widespread that that bit must reasonably be considered an alias for // the critical bit. The remaining bits are 0/ignore as proscribed by the // RFC. if (caaRecord.Flag & (128 | 1)) != 0 { return true } } } return false }
[ "func", "(", "caaSet", "CAASet", ")", "criticalUnknown", "(", ")", "bool", "{", "if", "len", "(", "caaSet", ".", "Unknown", ")", ">", "0", "{", "for", "_", ",", "caaRecord", ":=", "range", "caaSet", ".", "Unknown", "{", "// The critical flag is the bit with significance 128. However, many CAA", "// record users have misinterpreted the RFC and concluded that the bit", "// with significance 1 is the critical bit. This is sufficiently", "// widespread that that bit must reasonably be considered an alias for", "// the critical bit. The remaining bits are 0/ignore as proscribed by the", "// RFC.", "if", "(", "caaRecord", ".", "Flag", "&", "(", "128", "|", "1", ")", ")", "!=", "0", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// returns true if any CAA records have unknown tag properties and are flagged critical.
[ "returns", "true", "if", "any", "CAA", "records", "have", "unknown", "tag", "properties", "and", "are", "flagged", "critical", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/caa.go#L86-L102
train
letsencrypt/boulder
va/caa.go
newCAASet
func newCAASet(CAAs []*dns.CAA) *CAASet { var filtered CAASet for _, caaRecord := range CAAs { switch strings.ToLower(caaRecord.Tag) { case "issue": filtered.Issue = append(filtered.Issue, caaRecord) case "issuewild": filtered.Issuewild = append(filtered.Issuewild, caaRecord) case "iodef": filtered.Iodef = append(filtered.Iodef, caaRecord) default: filtered.Unknown = append(filtered.Unknown, caaRecord) } } return &filtered }
go
func newCAASet(CAAs []*dns.CAA) *CAASet { var filtered CAASet for _, caaRecord := range CAAs { switch strings.ToLower(caaRecord.Tag) { case "issue": filtered.Issue = append(filtered.Issue, caaRecord) case "issuewild": filtered.Issuewild = append(filtered.Issuewild, caaRecord) case "iodef": filtered.Iodef = append(filtered.Iodef, caaRecord) default: filtered.Unknown = append(filtered.Unknown, caaRecord) } } return &filtered }
[ "func", "newCAASet", "(", "CAAs", "[", "]", "*", "dns", ".", "CAA", ")", "*", "CAASet", "{", "var", "filtered", "CAASet", "\n\n", "for", "_", ",", "caaRecord", ":=", "range", "CAAs", "{", "switch", "strings", ".", "ToLower", "(", "caaRecord", ".", "Tag", ")", "{", "case", "\"", "\"", ":", "filtered", ".", "Issue", "=", "append", "(", "filtered", ".", "Issue", ",", "caaRecord", ")", "\n", "case", "\"", "\"", ":", "filtered", ".", "Issuewild", "=", "append", "(", "filtered", ".", "Issuewild", ",", "caaRecord", ")", "\n", "case", "\"", "\"", ":", "filtered", ".", "Iodef", "=", "append", "(", "filtered", ".", "Iodef", ",", "caaRecord", ")", "\n", "default", ":", "filtered", ".", "Unknown", "=", "append", "(", "filtered", ".", "Unknown", ",", "caaRecord", ")", "\n", "}", "\n", "}", "\n\n", "return", "&", "filtered", "\n", "}" ]
// Filter CAA records by property
[ "Filter", "CAA", "records", "by", "property" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/caa.go#L105-L122
train
letsencrypt/boulder
va/caa.go
checkAccountURI
func checkAccountURI(accountURI string, accountURIPrefixes []string, accountID int64) bool { for _, prefix := range accountURIPrefixes { if accountURI == fmt.Sprintf("%s%d", prefix, accountID) { return true } } return false }
go
func checkAccountURI(accountURI string, accountURIPrefixes []string, accountID int64) bool { for _, prefix := range accountURIPrefixes { if accountURI == fmt.Sprintf("%s%d", prefix, accountID) { return true } } return false }
[ "func", "checkAccountURI", "(", "accountURI", "string", ",", "accountURIPrefixes", "[", "]", "string", ",", "accountID", "int64", ")", "bool", "{", "for", "_", ",", "prefix", ":=", "range", "accountURIPrefixes", "{", "if", "accountURI", "==", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "prefix", ",", "accountID", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// checkAccountURI checks the specified full account URI against the // given accountID and a list of valid prefixes.
[ "checkAccountURI", "checks", "the", "specified", "full", "account", "URI", "against", "the", "given", "accountID", "and", "a", "list", "of", "valid", "prefixes", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/caa.go#L311-L318
train
letsencrypt/boulder
core/util.go
RandomString
func RandomString(byteLength int) string { b := make([]byte, byteLength) _, err := io.ReadFull(RandReader, b) if err != nil { panic(fmt.Sprintf("Error reading random bytes: %s", err)) } return base64.RawURLEncoding.EncodeToString(b) }
go
func RandomString(byteLength int) string { b := make([]byte, byteLength) _, err := io.ReadFull(RandReader, b) if err != nil { panic(fmt.Sprintf("Error reading random bytes: %s", err)) } return base64.RawURLEncoding.EncodeToString(b) }
[ "func", "RandomString", "(", "byteLength", "int", ")", "string", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "byteLength", ")", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "RandReader", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "base64", ".", "RawURLEncoding", ".", "EncodeToString", "(", "b", ")", "\n", "}" ]
// RandomString returns a randomly generated string of the requested length.
[ "RandomString", "returns", "a", "randomly", "generated", "string", "of", "the", "requested", "length", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L58-L65
train
letsencrypt/boulder
core/util.go
Fingerprint256
func Fingerprint256(data []byte) string { d := sha256.New() _, _ = d.Write(data) // Never returns an error return base64.RawURLEncoding.EncodeToString(d.Sum(nil)) }
go
func Fingerprint256(data []byte) string { d := sha256.New() _, _ = d.Write(data) // Never returns an error return base64.RawURLEncoding.EncodeToString(d.Sum(nil)) }
[ "func", "Fingerprint256", "(", "data", "[", "]", "byte", ")", "string", "{", "d", ":=", "sha256", ".", "New", "(", ")", "\n", "_", ",", "_", "=", "d", ".", "Write", "(", "data", ")", "// Never returns an error", "\n", "return", "base64", ".", "RawURLEncoding", ".", "EncodeToString", "(", "d", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// Fingerprints // Fingerprint256 produces an unpadded, URL-safe Base64-encoded SHA256 digest // of the data.
[ "Fingerprints", "Fingerprint256", "produces", "an", "unpadded", "URL", "-", "safe", "Base64", "-", "encoded", "SHA256", "digest", "of", "the", "data", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L84-L88
train
letsencrypt/boulder
core/util.go
KeyDigest
func KeyDigest(key crypto.PublicKey) (string, error) { switch t := key.(type) { case *jose.JSONWebKey: if t == nil { return "", fmt.Errorf("Cannot compute digest of nil key") } return KeyDigest(t.Key) case jose.JSONWebKey: return KeyDigest(t.Key) default: keyDER, err := x509.MarshalPKIXPublicKey(key) if err != nil { logger := blog.Get() logger.Debugf("Problem marshaling public key: %s", err) return "", err } spkiDigest := sha256.Sum256(keyDER) return base64.StdEncoding.EncodeToString(spkiDigest[0:32]), nil } }
go
func KeyDigest(key crypto.PublicKey) (string, error) { switch t := key.(type) { case *jose.JSONWebKey: if t == nil { return "", fmt.Errorf("Cannot compute digest of nil key") } return KeyDigest(t.Key) case jose.JSONWebKey: return KeyDigest(t.Key) default: keyDER, err := x509.MarshalPKIXPublicKey(key) if err != nil { logger := blog.Get() logger.Debugf("Problem marshaling public key: %s", err) return "", err } spkiDigest := sha256.Sum256(keyDER) return base64.StdEncoding.EncodeToString(spkiDigest[0:32]), nil } }
[ "func", "KeyDigest", "(", "key", "crypto", ".", "PublicKey", ")", "(", "string", ",", "error", ")", "{", "switch", "t", ":=", "key", ".", "(", "type", ")", "{", "case", "*", "jose", ".", "JSONWebKey", ":", "if", "t", "==", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "KeyDigest", "(", "t", ".", "Key", ")", "\n", "case", "jose", ".", "JSONWebKey", ":", "return", "KeyDigest", "(", "t", ".", "Key", ")", "\n", "default", ":", "keyDER", ",", "err", ":=", "x509", ".", "MarshalPKIXPublicKey", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ":=", "blog", ".", "Get", "(", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "spkiDigest", ":=", "sha256", ".", "Sum256", "(", "keyDER", ")", "\n", "return", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "spkiDigest", "[", "0", ":", "32", "]", ")", ",", "nil", "\n", "}", "\n", "}" ]
// KeyDigest produces a padded, standard Base64-encoded SHA256 digest of a // provided public key.
[ "KeyDigest", "produces", "a", "padded", "standard", "Base64", "-", "encoded", "SHA256", "digest", "of", "a", "provided", "public", "key", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L92-L111
train
letsencrypt/boulder
core/util.go
KeyDigestEquals
func KeyDigestEquals(j, k crypto.PublicKey) bool { digestJ, errJ := KeyDigest(j) digestK, errK := KeyDigest(k) // Keys that don't have a valid digest (due to marshalling problems) // are never equal. So, e.g. nil keys are not equal. if errJ != nil || errK != nil { return false } return digestJ == digestK }
go
func KeyDigestEquals(j, k crypto.PublicKey) bool { digestJ, errJ := KeyDigest(j) digestK, errK := KeyDigest(k) // Keys that don't have a valid digest (due to marshalling problems) // are never equal. So, e.g. nil keys are not equal. if errJ != nil || errK != nil { return false } return digestJ == digestK }
[ "func", "KeyDigestEquals", "(", "j", ",", "k", "crypto", ".", "PublicKey", ")", "bool", "{", "digestJ", ",", "errJ", ":=", "KeyDigest", "(", "j", ")", "\n", "digestK", ",", "errK", ":=", "KeyDigest", "(", "k", ")", "\n", "// Keys that don't have a valid digest (due to marshalling problems)", "// are never equal. So, e.g. nil keys are not equal.", "if", "errJ", "!=", "nil", "||", "errK", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "digestJ", "==", "digestK", "\n", "}" ]
// KeyDigestEquals determines whether two public keys have the same digest.
[ "KeyDigestEquals", "determines", "whether", "two", "public", "keys", "have", "the", "same", "digest", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L114-L123
train
letsencrypt/boulder
core/util.go
PublicKeysEqual
func PublicKeysEqual(a, b interface{}) (bool, error) { if a == nil || b == nil { return false, errors.New("One or more nil arguments to PublicKeysEqual") } aBytes, err := x509.MarshalPKIXPublicKey(a) if err != nil { return false, err } bBytes, err := x509.MarshalPKIXPublicKey(b) if err != nil { return false, err } return bytes.Compare(aBytes, bBytes) == 0, nil }
go
func PublicKeysEqual(a, b interface{}) (bool, error) { if a == nil || b == nil { return false, errors.New("One or more nil arguments to PublicKeysEqual") } aBytes, err := x509.MarshalPKIXPublicKey(a) if err != nil { return false, err } bBytes, err := x509.MarshalPKIXPublicKey(b) if err != nil { return false, err } return bytes.Compare(aBytes, bBytes) == 0, nil }
[ "func", "PublicKeysEqual", "(", "a", ",", "b", "interface", "{", "}", ")", "(", "bool", ",", "error", ")", "{", "if", "a", "==", "nil", "||", "b", "==", "nil", "{", "return", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "aBytes", ",", "err", ":=", "x509", ".", "MarshalPKIXPublicKey", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "bBytes", ",", "err", ":=", "x509", ".", "MarshalPKIXPublicKey", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "bytes", ".", "Compare", "(", "aBytes", ",", "bBytes", ")", "==", "0", ",", "nil", "\n", "}" ]
// PublicKeysEqual determines whether two public keys have the same marshalled // bytes as one another
[ "PublicKeysEqual", "determines", "whether", "two", "public", "keys", "have", "the", "same", "marshalled", "bytes", "as", "one", "another" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L127-L140
train
letsencrypt/boulder
core/util.go
ValidSerial
func ValidSerial(serial string) bool { // Originally, serial numbers were 32 hex characters long. We later increased // them to 36, but we allow the shorter ones because they exist in some // production databases. if len(serial) != 32 && len(serial) != 36 { return false } _, err := hex.DecodeString(serial) if err != nil { return false } return true }
go
func ValidSerial(serial string) bool { // Originally, serial numbers were 32 hex characters long. We later increased // them to 36, but we allow the shorter ones because they exist in some // production databases. if len(serial) != 32 && len(serial) != 36 { return false } _, err := hex.DecodeString(serial) if err != nil { return false } return true }
[ "func", "ValidSerial", "(", "serial", "string", ")", "bool", "{", "// Originally, serial numbers were 32 hex characters long. We later increased", "// them to 36, but we allow the shorter ones because they exist in some", "// production databases.", "if", "len", "(", "serial", ")", "!=", "32", "&&", "len", "(", "serial", ")", "!=", "36", "{", "return", "false", "\n", "}", "\n", "_", ",", "err", ":=", "hex", ".", "DecodeString", "(", "serial", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// ValidSerial tests whether the input string represents a syntactically // valid serial number, i.e., that it is a valid hex string between 32 // and 36 characters long.
[ "ValidSerial", "tests", "whether", "the", "input", "string", "represents", "a", "syntactically", "valid", "serial", "number", "i", ".", "e", ".", "that", "it", "is", "a", "valid", "hex", "string", "between", "32", "and", "36", "characters", "long", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L162-L174
train
letsencrypt/boulder
core/util.go
UniqueLowerNames
func UniqueLowerNames(names []string) (unique []string) { nameMap := make(map[string]int, len(names)) for _, name := range names { nameMap[strings.ToLower(name)] = 1 } unique = make([]string, 0, len(nameMap)) for name := range nameMap { unique = append(unique, name) } sort.Strings(unique) return }
go
func UniqueLowerNames(names []string) (unique []string) { nameMap := make(map[string]int, len(names)) for _, name := range names { nameMap[strings.ToLower(name)] = 1 } unique = make([]string, 0, len(nameMap)) for name := range nameMap { unique = append(unique, name) } sort.Strings(unique) return }
[ "func", "UniqueLowerNames", "(", "names", "[", "]", "string", ")", "(", "unique", "[", "]", "string", ")", "{", "nameMap", ":=", "make", "(", "map", "[", "string", "]", "int", ",", "len", "(", "names", ")", ")", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "nameMap", "[", "strings", ".", "ToLower", "(", "name", ")", "]", "=", "1", "\n", "}", "\n\n", "unique", "=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "nameMap", ")", ")", "\n", "for", "name", ":=", "range", "nameMap", "{", "unique", "=", "append", "(", "unique", ",", "name", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "unique", ")", "\n", "return", "\n", "}" ]
// UniqueLowerNames returns the set of all unique names in the input after all // of them are lowercased. The returned names will be in their lowercased form // and sorted alphabetically.
[ "UniqueLowerNames", "returns", "the", "set", "of", "all", "unique", "names", "in", "the", "input", "after", "all", "of", "them", "are", "lowercased", ".", "The", "returned", "names", "will", "be", "in", "their", "lowercased", "form", "and", "sorted", "alphabetically", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L206-L218
train
letsencrypt/boulder
core/util.go
LoadCertBundle
func LoadCertBundle(filename string) ([]*x509.Certificate, error) { bundleBytes, err := ioutil.ReadFile(filename) if err != nil { return nil, err } var bundle []*x509.Certificate var block *pem.Block rest := bundleBytes for { block, rest = pem.Decode(rest) if block == nil { break } if block.Type != "CERTIFICATE" { return nil, fmt.Errorf("Block has invalid type: %s", block.Type) } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, err } bundle = append(bundle, cert) } if len(bundle) == 0 { return nil, fmt.Errorf("Bundle doesn't contain any certificates") } return bundle, nil }
go
func LoadCertBundle(filename string) ([]*x509.Certificate, error) { bundleBytes, err := ioutil.ReadFile(filename) if err != nil { return nil, err } var bundle []*x509.Certificate var block *pem.Block rest := bundleBytes for { block, rest = pem.Decode(rest) if block == nil { break } if block.Type != "CERTIFICATE" { return nil, fmt.Errorf("Block has invalid type: %s", block.Type) } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, err } bundle = append(bundle, cert) } if len(bundle) == 0 { return nil, fmt.Errorf("Bundle doesn't contain any certificates") } return bundle, nil }
[ "func", "LoadCertBundle", "(", "filename", "string", ")", "(", "[", "]", "*", "x509", ".", "Certificate", ",", "error", ")", "{", "bundleBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "bundle", "[", "]", "*", "x509", ".", "Certificate", "\n", "var", "block", "*", "pem", ".", "Block", "\n", "rest", ":=", "bundleBytes", "\n", "for", "{", "block", ",", "rest", "=", "pem", ".", "Decode", "(", "rest", ")", "\n", "if", "block", "==", "nil", "{", "break", "\n", "}", "\n", "if", "block", ".", "Type", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "block", ".", "Type", ")", "\n", "}", "\n", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "block", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "bundle", "=", "append", "(", "bundle", ",", "cert", ")", "\n", "}", "\n\n", "if", "len", "(", "bundle", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "bundle", ",", "nil", "\n", "}" ]
// LoadCertBundle loads a PEM bundle of certificates from disk
[ "LoadCertBundle", "loads", "a", "PEM", "bundle", "of", "certificates", "from", "disk" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L221-L249
train
letsencrypt/boulder
core/util.go
LoadCert
func LoadCert(filename string) (cert *x509.Certificate, err error) { certPEM, err := ioutil.ReadFile(filename) if err != nil { return } block, _ := pem.Decode(certPEM) if block == nil { return nil, fmt.Errorf("No data in cert PEM file %s", filename) } cert, err = x509.ParseCertificate(block.Bytes) return }
go
func LoadCert(filename string) (cert *x509.Certificate, err error) { certPEM, err := ioutil.ReadFile(filename) if err != nil { return } block, _ := pem.Decode(certPEM) if block == nil { return nil, fmt.Errorf("No data in cert PEM file %s", filename) } cert, err = x509.ParseCertificate(block.Bytes) return }
[ "func", "LoadCert", "(", "filename", "string", ")", "(", "cert", "*", "x509", ".", "Certificate", ",", "err", "error", ")", "{", "certPEM", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "certPEM", ")", "\n", "if", "block", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filename", ")", "\n", "}", "\n", "cert", ",", "err", "=", "x509", ".", "ParseCertificate", "(", "block", ".", "Bytes", ")", "\n", "return", "\n", "}" ]
// LoadCert loads a PEM certificate specified by filename or returns an error
[ "LoadCert", "loads", "a", "PEM", "certificate", "specified", "by", "filename", "or", "returns", "an", "error" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L252-L263
train
letsencrypt/boulder
core/util.go
IsASCII
func IsASCII(str string) bool { for _, r := range str { if r > unicode.MaxASCII { return false } } return true }
go
func IsASCII(str string) bool { for _, r := range str { if r > unicode.MaxASCII { return false } } return true }
[ "func", "IsASCII", "(", "str", "string", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "str", "{", "if", "r", ">", "unicode", ".", "MaxASCII", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsASCII determines if every character in a string is encoded in // the ASCII character set.
[ "IsASCII", "determines", "if", "every", "character", "in", "a", "string", "is", "encoded", "in", "the", "ASCII", "character", "set", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/core/util.go#L293-L300
train
letsencrypt/boulder
grpc/pb-marshalling.go
authzMetaToPB
func authzMetaToPB(authz core.Authorization) (*vapb.AuthzMeta, error) { return &vapb.AuthzMeta{ Id: &authz.ID, RegID: &authz.RegistrationID, }, nil }
go
func authzMetaToPB(authz core.Authorization) (*vapb.AuthzMeta, error) { return &vapb.AuthzMeta{ Id: &authz.ID, RegID: &authz.RegistrationID, }, nil }
[ "func", "authzMetaToPB", "(", "authz", "core", ".", "Authorization", ")", "(", "*", "vapb", ".", "AuthzMeta", ",", "error", ")", "{", "return", "&", "vapb", ".", "AuthzMeta", "{", "Id", ":", "&", "authz", ".", "ID", ",", "RegID", ":", "&", "authz", ".", "RegistrationID", ",", "}", ",", "nil", "\n", "}" ]
// This file defines functions to translate between the protobuf types and the // code types.
[ "This", "file", "defines", "functions", "to", "translate", "between", "the", "protobuf", "types", "and", "the", "code", "types", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/pb-marshalling.go#L26-L31
train
letsencrypt/boulder
grpc/pb-marshalling.go
orderValid
func orderValid(order *corepb.Order) bool { return order.Id != nil && order.BeganProcessing != nil && order.Created != nil && newOrderValid(order) }
go
func orderValid(order *corepb.Order) bool { return order.Id != nil && order.BeganProcessing != nil && order.Created != nil && newOrderValid(order) }
[ "func", "orderValid", "(", "order", "*", "corepb", ".", "Order", ")", "bool", "{", "return", "order", ".", "Id", "!=", "nil", "&&", "order", ".", "BeganProcessing", "!=", "nil", "&&", "order", ".", "Created", "!=", "nil", "&&", "newOrderValid", "(", "order", ")", "\n", "}" ]
// orderValid checks that a corepb.Order is valid. In addition to the checks // from `newOrderValid` it ensures the order ID, the BeganProcessing fields // and the Created field are not nil.
[ "orderValid", "checks", "that", "a", "corepb", ".", "Order", "is", "valid", ".", "In", "addition", "to", "the", "checks", "from", "newOrderValid", "it", "ensures", "the", "order", "ID", "the", "BeganProcessing", "fields", "and", "the", "Created", "field", "are", "not", "nil", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/pb-marshalling.go#L410-L412
train
letsencrypt/boulder
grpc/pb-marshalling.go
newOrderValid
func newOrderValid(order *corepb.Order) bool { return !(order.RegistrationID == nil || order.Expires == nil || order.Authorizations == nil || order.Names == nil) }
go
func newOrderValid(order *corepb.Order) bool { return !(order.RegistrationID == nil || order.Expires == nil || order.Authorizations == nil || order.Names == nil) }
[ "func", "newOrderValid", "(", "order", "*", "corepb", ".", "Order", ")", "bool", "{", "return", "!", "(", "order", ".", "RegistrationID", "==", "nil", "||", "order", ".", "Expires", "==", "nil", "||", "order", ".", "Authorizations", "==", "nil", "||", "order", ".", "Names", "==", "nil", ")", "\n", "}" ]
// newOrderValid checks that a corepb.Order is valid. It allows for a nil // `order.Id` because the order has not been assigned an ID yet when it is being // created initially. It allows `order.BeganProcessing` to be nil because // `sa.NewOrder` explicitly sets it to the default value. It allows // `order.Created` to be nil because the SA populates this. It also allows // `order.CertificateSerial` to be nil such that it can be used in places where // the order has not been finalized yet.
[ "newOrderValid", "checks", "that", "a", "corepb", ".", "Order", "is", "valid", ".", "It", "allows", "for", "a", "nil", "order", ".", "Id", "because", "the", "order", "has", "not", "been", "assigned", "an", "ID", "yet", "when", "it", "is", "being", "created", "initially", ".", "It", "allows", "order", ".", "BeganProcessing", "to", "be", "nil", "because", "sa", ".", "NewOrder", "explicitly", "sets", "it", "to", "the", "default", "value", ".", "It", "allows", "order", ".", "Created", "to", "be", "nil", "because", "the", "SA", "populates", "this", ".", "It", "also", "allows", "order", ".", "CertificateSerial", "to", "be", "nil", "such", "that", "it", "can", "be", "used", "in", "places", "where", "the", "order", "has", "not", "been", "finalized", "yet", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/pb-marshalling.go#L421-L423
train
letsencrypt/boulder
policy/pa.go
New
func New(challengeTypes map[string]bool) (*AuthorityImpl, error) { pa := AuthorityImpl{ log: blog.Get(), enabledChallenges: challengeTypes, // We don't need real randomness for this. pseudoRNG: rand.New(rand.NewSource(99)), } return &pa, nil }
go
func New(challengeTypes map[string]bool) (*AuthorityImpl, error) { pa := AuthorityImpl{ log: blog.Get(), enabledChallenges: challengeTypes, // We don't need real randomness for this. pseudoRNG: rand.New(rand.NewSource(99)), } return &pa, nil }
[ "func", "New", "(", "challengeTypes", "map", "[", "string", "]", "bool", ")", "(", "*", "AuthorityImpl", ",", "error", ")", "{", "pa", ":=", "AuthorityImpl", "{", "log", ":", "blog", ".", "Get", "(", ")", ",", "enabledChallenges", ":", "challengeTypes", ",", "// We don't need real randomness for this.", "pseudoRNG", ":", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "99", ")", ")", ",", "}", "\n\n", "return", "&", "pa", ",", "nil", "\n", "}" ]
// New constructs a Policy Authority.
[ "New", "constructs", "a", "Policy", "Authority", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/policy/pa.go#L41-L51
train
letsencrypt/boulder
policy/pa.go
SetHostnamePolicyFile
func (pa *AuthorityImpl) SetHostnamePolicyFile(f string) error { var loadHandler func([]byte) error if strings.HasSuffix(f, ".json") { loadHandler = pa.loadHostnamePolicy(json.Unmarshal) } else if strings.HasSuffix(f, ".yml") || strings.HasSuffix(f, ".yaml") { loadHandler = pa.loadHostnamePolicy(yaml.Unmarshal) } else { return fmt.Errorf( "Hostname policy file %q has unknown extension. Supported: .yml,.yaml,.json", f) } if _, err := reloader.New(f, loadHandler, pa.hostnamePolicyLoadError); err != nil { return err } return nil }
go
func (pa *AuthorityImpl) SetHostnamePolicyFile(f string) error { var loadHandler func([]byte) error if strings.HasSuffix(f, ".json") { loadHandler = pa.loadHostnamePolicy(json.Unmarshal) } else if strings.HasSuffix(f, ".yml") || strings.HasSuffix(f, ".yaml") { loadHandler = pa.loadHostnamePolicy(yaml.Unmarshal) } else { return fmt.Errorf( "Hostname policy file %q has unknown extension. Supported: .yml,.yaml,.json", f) } if _, err := reloader.New(f, loadHandler, pa.hostnamePolicyLoadError); err != nil { return err } return nil }
[ "func", "(", "pa", "*", "AuthorityImpl", ")", "SetHostnamePolicyFile", "(", "f", "string", ")", "error", "{", "var", "loadHandler", "func", "(", "[", "]", "byte", ")", "error", "\n", "if", "strings", ".", "HasSuffix", "(", "f", ",", "\"", "\"", ")", "{", "loadHandler", "=", "pa", ".", "loadHostnamePolicy", "(", "json", ".", "Unmarshal", ")", "\n", "}", "else", "if", "strings", ".", "HasSuffix", "(", "f", ",", "\"", "\"", ")", "||", "strings", ".", "HasSuffix", "(", "f", ",", "\"", "\"", ")", "{", "loadHandler", "=", "pa", ".", "loadHostnamePolicy", "(", "yaml", ".", "Unmarshal", ")", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "reloader", ".", "New", "(", "f", ",", "loadHandler", ",", "pa", ".", "hostnamePolicyLoadError", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetHostnamePolicyFile will load the given policy file, returning error if it // fails. It will also start a reloader in case the file changes. It supports // YAML and JSON serialization formats and chooses the correct unserialization // method based on the file extension which must be ".yaml", ".yml", or ".json".
[ "SetHostnamePolicyFile", "will", "load", "the", "given", "policy", "file", "returning", "error", "if", "it", "fails", ".", "It", "will", "also", "start", "a", "reloader", "in", "case", "the", "file", "changes", ".", "It", "supports", "YAML", "and", "JSON", "serialization", "formats", "and", "chooses", "the", "correct", "unserialization", "method", "based", "on", "the", "file", "extension", "which", "must", "be", ".", "yaml", ".", "yml", "or", ".", "json", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/policy/pa.go#L83-L98
train
letsencrypt/boulder
policy/pa.go
processHostnamePolicy
func (pa *AuthorityImpl) processHostnamePolicy(policy blockedNamesPolicy) error { nameMap := make(map[string]bool) for _, v := range policy.HighRiskBlockedNames { nameMap[v] = true } for _, v := range policy.AdminBlockedNames { nameMap[v] = true } exactNameMap := make(map[string]bool) wildcardNameMap := make(map[string]bool) for _, v := range policy.ExactBlockedNames { exactNameMap[v] = true // Remove the leftmost label of the exact blocked names entry to make an exact // wildcard block list entry that will prevent issuing a wildcard that would // include the exact blocklist entry. e.g. if "highvalue.example.com" is on // the exact blocklist we want "example.com" to be in the // wildcardExactBlocklist so that "*.example.com" cannot be issued. // // First, split the domain into two parts: the first label and the rest of the domain. parts := strings.SplitN(v, ".", 2) // if there are less than 2 parts then this entry is malformed! There should // at least be a "something." and a TLD like "com" if len(parts) < 2 { return fmt.Errorf( "Malformed ExactBlockedNames entry, only one label: %q", v) } // Add the second part, the domain minus the first label, to the // wildcardNameMap to block issuance for `*.`+parts[1] wildcardNameMap[parts[1]] = true } pa.blocklistMu.Lock() pa.blocklist = nameMap pa.exactBlocklist = exactNameMap pa.wildcardExactBlocklist = wildcardNameMap pa.blocklistMu.Unlock() return nil }
go
func (pa *AuthorityImpl) processHostnamePolicy(policy blockedNamesPolicy) error { nameMap := make(map[string]bool) for _, v := range policy.HighRiskBlockedNames { nameMap[v] = true } for _, v := range policy.AdminBlockedNames { nameMap[v] = true } exactNameMap := make(map[string]bool) wildcardNameMap := make(map[string]bool) for _, v := range policy.ExactBlockedNames { exactNameMap[v] = true // Remove the leftmost label of the exact blocked names entry to make an exact // wildcard block list entry that will prevent issuing a wildcard that would // include the exact blocklist entry. e.g. if "highvalue.example.com" is on // the exact blocklist we want "example.com" to be in the // wildcardExactBlocklist so that "*.example.com" cannot be issued. // // First, split the domain into two parts: the first label and the rest of the domain. parts := strings.SplitN(v, ".", 2) // if there are less than 2 parts then this entry is malformed! There should // at least be a "something." and a TLD like "com" if len(parts) < 2 { return fmt.Errorf( "Malformed ExactBlockedNames entry, only one label: %q", v) } // Add the second part, the domain minus the first label, to the // wildcardNameMap to block issuance for `*.`+parts[1] wildcardNameMap[parts[1]] = true } pa.blocklistMu.Lock() pa.blocklist = nameMap pa.exactBlocklist = exactNameMap pa.wildcardExactBlocklist = wildcardNameMap pa.blocklistMu.Unlock() return nil }
[ "func", "(", "pa", "*", "AuthorityImpl", ")", "processHostnamePolicy", "(", "policy", "blockedNamesPolicy", ")", "error", "{", "nameMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "v", ":=", "range", "policy", ".", "HighRiskBlockedNames", "{", "nameMap", "[", "v", "]", "=", "true", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "policy", ".", "AdminBlockedNames", "{", "nameMap", "[", "v", "]", "=", "true", "\n", "}", "\n", "exactNameMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "wildcardNameMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "v", ":=", "range", "policy", ".", "ExactBlockedNames", "{", "exactNameMap", "[", "v", "]", "=", "true", "\n", "// Remove the leftmost label of the exact blocked names entry to make an exact", "// wildcard block list entry that will prevent issuing a wildcard that would", "// include the exact blocklist entry. e.g. if \"highvalue.example.com\" is on", "// the exact blocklist we want \"example.com\" to be in the", "// wildcardExactBlocklist so that \"*.example.com\" cannot be issued.", "//", "// First, split the domain into two parts: the first label and the rest of the domain.", "parts", ":=", "strings", ".", "SplitN", "(", "v", ",", "\"", "\"", ",", "2", ")", "\n", "// if there are less than 2 parts then this entry is malformed! There should", "// at least be a \"something.\" and a TLD like \"com\"", "if", "len", "(", "parts", ")", "<", "2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n", "// Add the second part, the domain minus the first label, to the", "// wildcardNameMap to block issuance for `*.`+parts[1]", "wildcardNameMap", "[", "parts", "[", "1", "]", "]", "=", "true", "\n", "}", "\n", "pa", ".", "blocklistMu", ".", "Lock", "(", ")", "\n", "pa", ".", "blocklist", "=", "nameMap", "\n", "pa", ".", "exactBlocklist", "=", "exactNameMap", "\n", "pa", ".", "wildcardExactBlocklist", "=", "wildcardNameMap", "\n", "pa", ".", "blocklistMu", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// processHostnamePolicy handles loading a new blockedNamesPolicy into the PA. // All of the policy.ExactBlockedNames will be added to the // wildcardExactBlocklist by processHostnamePolicy to ensure that wildcards for // exact blocked names entries are forbidden.
[ "processHostnamePolicy", "handles", "loading", "a", "new", "blockedNamesPolicy", "into", "the", "PA", ".", "All", "of", "the", "policy", ".", "ExactBlockedNames", "will", "be", "added", "to", "the", "wildcardExactBlocklist", "by", "processHostnamePolicy", "to", "ensure", "that", "wildcards", "for", "exact", "blocked", "names", "entries", "are", "forbidden", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/policy/pa.go#L136-L172
train
letsencrypt/boulder
policy/pa.go
checkWildcardHostList
func (pa *AuthorityImpl) checkWildcardHostList(domain string) error { pa.blocklistMu.RLock() defer pa.blocklistMu.RUnlock() if pa.blocklist == nil { return fmt.Errorf("Hostname policy not yet loaded.") } if pa.wildcardExactBlocklist[domain] { return errPolicyForbidden } return nil }
go
func (pa *AuthorityImpl) checkWildcardHostList(domain string) error { pa.blocklistMu.RLock() defer pa.blocklistMu.RUnlock() if pa.blocklist == nil { return fmt.Errorf("Hostname policy not yet loaded.") } if pa.wildcardExactBlocklist[domain] { return errPolicyForbidden } return nil }
[ "func", "(", "pa", "*", "AuthorityImpl", ")", "checkWildcardHostList", "(", "domain", "string", ")", "error", "{", "pa", ".", "blocklistMu", ".", "RLock", "(", ")", "\n", "defer", "pa", ".", "blocklistMu", ".", "RUnlock", "(", ")", "\n\n", "if", "pa", ".", "blocklist", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "pa", ".", "wildcardExactBlocklist", "[", "domain", "]", "{", "return", "errPolicyForbidden", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkWildcardHostList checks the wildcardExactBlocklist for a given domain. // If the domain is not present on the list nil is returned, otherwise // errPolicyForbidden is returned.
[ "checkWildcardHostList", "checks", "the", "wildcardExactBlocklist", "for", "a", "given", "domain", ".", "If", "the", "domain", "is", "not", "present", "on", "the", "list", "nil", "is", "returned", "otherwise", "errPolicyForbidden", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/policy/pa.go#L403-L416
train
letsencrypt/boulder
policy/pa.go
ChallengesFor
func (pa *AuthorityImpl) ChallengesFor(identifier core.AcmeIdentifier) ([]core.Challenge, error) { challenges := []core.Challenge{} // If we are using the new authorization storage schema we only use a single // token for all challenges rather than a unique token per challenge. var token string if features.Enabled(features.NewAuthorizationSchema) { token = core.NewToken() } // If the identifier is for a DNS wildcard name we only // provide a DNS-01 challenge as a matter of CA policy. if strings.HasPrefix(identifier.Value, "*.") { // We must have the DNS-01 challenge type enabled to create challenges for // a wildcard identifier per LE policy. if !pa.ChallengeTypeEnabled(core.ChallengeTypeDNS01) { return nil, fmt.Errorf( "Challenges requested for wildcard identifier but DNS-01 " + "challenge type is not enabled") } // Only provide a DNS-01-Wildcard challenge challenges = []core.Challenge{core.DNSChallenge01(token)} } else { // Otherwise we collect up challenges based on what is enabled. if pa.ChallengeTypeEnabled(core.ChallengeTypeHTTP01) { challenges = append(challenges, core.HTTPChallenge01(token)) } if pa.ChallengeTypeEnabled(core.ChallengeTypeTLSALPN01) { challenges = append(challenges, core.TLSALPNChallenge01(token)) } if pa.ChallengeTypeEnabled(core.ChallengeTypeDNS01) { challenges = append(challenges, core.DNSChallenge01(token)) } } // We shuffle the challenges to prevent ACME clients from relying on the // specific order that boulder returns them in. shuffled := make([]core.Challenge, len(challenges)) pa.rngMu.Lock() defer pa.rngMu.Unlock() for i, challIdx := range pa.pseudoRNG.Perm(len(challenges)) { shuffled[i] = challenges[challIdx] } return shuffled, nil }
go
func (pa *AuthorityImpl) ChallengesFor(identifier core.AcmeIdentifier) ([]core.Challenge, error) { challenges := []core.Challenge{} // If we are using the new authorization storage schema we only use a single // token for all challenges rather than a unique token per challenge. var token string if features.Enabled(features.NewAuthorizationSchema) { token = core.NewToken() } // If the identifier is for a DNS wildcard name we only // provide a DNS-01 challenge as a matter of CA policy. if strings.HasPrefix(identifier.Value, "*.") { // We must have the DNS-01 challenge type enabled to create challenges for // a wildcard identifier per LE policy. if !pa.ChallengeTypeEnabled(core.ChallengeTypeDNS01) { return nil, fmt.Errorf( "Challenges requested for wildcard identifier but DNS-01 " + "challenge type is not enabled") } // Only provide a DNS-01-Wildcard challenge challenges = []core.Challenge{core.DNSChallenge01(token)} } else { // Otherwise we collect up challenges based on what is enabled. if pa.ChallengeTypeEnabled(core.ChallengeTypeHTTP01) { challenges = append(challenges, core.HTTPChallenge01(token)) } if pa.ChallengeTypeEnabled(core.ChallengeTypeTLSALPN01) { challenges = append(challenges, core.TLSALPNChallenge01(token)) } if pa.ChallengeTypeEnabled(core.ChallengeTypeDNS01) { challenges = append(challenges, core.DNSChallenge01(token)) } } // We shuffle the challenges to prevent ACME clients from relying on the // specific order that boulder returns them in. shuffled := make([]core.Challenge, len(challenges)) pa.rngMu.Lock() defer pa.rngMu.Unlock() for i, challIdx := range pa.pseudoRNG.Perm(len(challenges)) { shuffled[i] = challenges[challIdx] } return shuffled, nil }
[ "func", "(", "pa", "*", "AuthorityImpl", ")", "ChallengesFor", "(", "identifier", "core", ".", "AcmeIdentifier", ")", "(", "[", "]", "core", ".", "Challenge", ",", "error", ")", "{", "challenges", ":=", "[", "]", "core", ".", "Challenge", "{", "}", "\n\n", "// If we are using the new authorization storage schema we only use a single", "// token for all challenges rather than a unique token per challenge.", "var", "token", "string", "\n", "if", "features", ".", "Enabled", "(", "features", ".", "NewAuthorizationSchema", ")", "{", "token", "=", "core", ".", "NewToken", "(", ")", "\n", "}", "\n\n", "// If the identifier is for a DNS wildcard name we only", "// provide a DNS-01 challenge as a matter of CA policy.", "if", "strings", ".", "HasPrefix", "(", "identifier", ".", "Value", ",", "\"", "\"", ")", "{", "// We must have the DNS-01 challenge type enabled to create challenges for", "// a wildcard identifier per LE policy.", "if", "!", "pa", ".", "ChallengeTypeEnabled", "(", "core", ".", "ChallengeTypeDNS01", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n", "// Only provide a DNS-01-Wildcard challenge", "challenges", "=", "[", "]", "core", ".", "Challenge", "{", "core", ".", "DNSChallenge01", "(", "token", ")", "}", "\n", "}", "else", "{", "// Otherwise we collect up challenges based on what is enabled.", "if", "pa", ".", "ChallengeTypeEnabled", "(", "core", ".", "ChallengeTypeHTTP01", ")", "{", "challenges", "=", "append", "(", "challenges", ",", "core", ".", "HTTPChallenge01", "(", "token", ")", ")", "\n", "}", "\n\n", "if", "pa", ".", "ChallengeTypeEnabled", "(", "core", ".", "ChallengeTypeTLSALPN01", ")", "{", "challenges", "=", "append", "(", "challenges", ",", "core", ".", "TLSALPNChallenge01", "(", "token", ")", ")", "\n", "}", "\n\n", "if", "pa", ".", "ChallengeTypeEnabled", "(", "core", ".", "ChallengeTypeDNS01", ")", "{", "challenges", "=", "append", "(", "challenges", ",", "core", ".", "DNSChallenge01", "(", "token", ")", ")", "\n", "}", "\n", "}", "\n\n", "// We shuffle the challenges to prevent ACME clients from relying on the", "// specific order that boulder returns them in.", "shuffled", ":=", "make", "(", "[", "]", "core", ".", "Challenge", ",", "len", "(", "challenges", ")", ")", "\n\n", "pa", ".", "rngMu", ".", "Lock", "(", ")", "\n", "defer", "pa", ".", "rngMu", ".", "Unlock", "(", ")", "\n", "for", "i", ",", "challIdx", ":=", "range", "pa", ".", "pseudoRNG", ".", "Perm", "(", "len", "(", "challenges", ")", ")", "{", "shuffled", "[", "i", "]", "=", "challenges", "[", "challIdx", "]", "\n", "}", "\n\n", "return", "shuffled", ",", "nil", "\n", "}" ]
// ChallengesFor makes a decision of what challenges are acceptable for // the given identifier.
[ "ChallengesFor", "makes", "a", "decision", "of", "what", "challenges", "are", "acceptable", "for", "the", "given", "identifier", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/policy/pa.go#L442-L490
train
letsencrypt/boulder
policy/pa.go
ChallengeTypeEnabled
func (pa *AuthorityImpl) ChallengeTypeEnabled(t string) bool { pa.blocklistMu.RLock() defer pa.blocklistMu.RUnlock() return pa.enabledChallenges[t] }
go
func (pa *AuthorityImpl) ChallengeTypeEnabled(t string) bool { pa.blocklistMu.RLock() defer pa.blocklistMu.RUnlock() return pa.enabledChallenges[t] }
[ "func", "(", "pa", "*", "AuthorityImpl", ")", "ChallengeTypeEnabled", "(", "t", "string", ")", "bool", "{", "pa", ".", "blocklistMu", ".", "RLock", "(", ")", "\n", "defer", "pa", ".", "blocklistMu", ".", "RUnlock", "(", ")", "\n", "return", "pa", ".", "enabledChallenges", "[", "t", "]", "\n", "}" ]
// ChallengeTypeEnabled returns whether the specified challenge type is enabled
[ "ChallengeTypeEnabled", "returns", "whether", "the", "specified", "challenge", "type", "is", "enabled" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/policy/pa.go#L493-L497
train
letsencrypt/boulder
nonce/nonce.go
NewNonceService
func NewNonceService(scope metrics.Scope) (*NonceService, error) { scope = scope.NewScope("NonceService") key := make([]byte, 16) if _, err := rand.Read(key); err != nil { return nil, err } c, err := aes.NewCipher(key) if err != nil { panic("Failure in NewCipher: " + err.Error()) } gcm, err := cipher.NewGCM(c) if err != nil { panic("Failure in NewGCM: " + err.Error()) } return &NonceService{ earliest: 0, latest: 0, used: make(map[int64]bool, MaxUsed), usedHeap: &int64Heap{}, gcm: gcm, maxUsed: MaxUsed, stats: scope, }, nil }
go
func NewNonceService(scope metrics.Scope) (*NonceService, error) { scope = scope.NewScope("NonceService") key := make([]byte, 16) if _, err := rand.Read(key); err != nil { return nil, err } c, err := aes.NewCipher(key) if err != nil { panic("Failure in NewCipher: " + err.Error()) } gcm, err := cipher.NewGCM(c) if err != nil { panic("Failure in NewGCM: " + err.Error()) } return &NonceService{ earliest: 0, latest: 0, used: make(map[int64]bool, MaxUsed), usedHeap: &int64Heap{}, gcm: gcm, maxUsed: MaxUsed, stats: scope, }, nil }
[ "func", "NewNonceService", "(", "scope", "metrics", ".", "Scope", ")", "(", "*", "NonceService", ",", "error", ")", "{", "scope", "=", "scope", ".", "NewScope", "(", "\"", "\"", ")", "\n", "key", ":=", "make", "(", "[", "]", "byte", ",", "16", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Read", "(", "key", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "c", ",", "err", ":=", "aes", ".", "NewCipher", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "gcm", ",", "err", ":=", "cipher", ".", "NewGCM", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "&", "NonceService", "{", "earliest", ":", "0", ",", "latest", ":", "0", ",", "used", ":", "make", "(", "map", "[", "int64", "]", "bool", ",", "MaxUsed", ")", ",", "usedHeap", ":", "&", "int64Heap", "{", "}", ",", "gcm", ":", "gcm", ",", "maxUsed", ":", "MaxUsed", ",", "stats", ":", "scope", ",", "}", ",", "nil", "\n", "}" ]
// NewNonceService constructs a NonceService with defaults
[ "NewNonceService", "constructs", "a", "NonceService", "with", "defaults" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/nonce/nonce.go#L68-L93
train
letsencrypt/boulder
nonce/nonce.go
Nonce
func (ns *NonceService) Nonce() (string, error) { ns.mu.Lock() ns.latest++ latest := ns.latest ns.mu.Unlock() defer ns.stats.Inc("Generated", 1) return ns.encrypt(latest) }
go
func (ns *NonceService) Nonce() (string, error) { ns.mu.Lock() ns.latest++ latest := ns.latest ns.mu.Unlock() defer ns.stats.Inc("Generated", 1) return ns.encrypt(latest) }
[ "func", "(", "ns", "*", "NonceService", ")", "Nonce", "(", ")", "(", "string", ",", "error", ")", "{", "ns", ".", "mu", ".", "Lock", "(", ")", "\n", "ns", ".", "latest", "++", "\n", "latest", ":=", "ns", ".", "latest", "\n", "ns", ".", "mu", ".", "Unlock", "(", ")", "\n", "defer", "ns", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "ns", ".", "encrypt", "(", "latest", ")", "\n", "}" ]
// Nonce provides a new Nonce.
[ "Nonce", "provides", "a", "new", "Nonce", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/nonce/nonce.go#L145-L152
train
letsencrypt/boulder
nonce/nonce.go
Valid
func (ns *NonceService) Valid(nonce string) bool { c, err := ns.decrypt(nonce) if err != nil { ns.stats.Inc("Invalid.Decrypt", 1) return false } ns.mu.Lock() defer ns.mu.Unlock() if c > ns.latest { ns.stats.Inc("Invalid.TooHigh", 1) return false } if c <= ns.earliest { ns.stats.Inc("Invalid.TooLow", 1) return false } if ns.used[c] { ns.stats.Inc("Invalid.AlreadyUsed", 1) return false } ns.used[c] = true heap.Push(ns.usedHeap, c) if len(ns.used) > ns.maxUsed { s := time.Now() ns.earliest = heap.Pop(ns.usedHeap).(int64) ns.stats.TimingDuration("Heap.Latency", time.Since(s)) delete(ns.used, ns.earliest) } ns.stats.Inc("Valid", 1) return true }
go
func (ns *NonceService) Valid(nonce string) bool { c, err := ns.decrypt(nonce) if err != nil { ns.stats.Inc("Invalid.Decrypt", 1) return false } ns.mu.Lock() defer ns.mu.Unlock() if c > ns.latest { ns.stats.Inc("Invalid.TooHigh", 1) return false } if c <= ns.earliest { ns.stats.Inc("Invalid.TooLow", 1) return false } if ns.used[c] { ns.stats.Inc("Invalid.AlreadyUsed", 1) return false } ns.used[c] = true heap.Push(ns.usedHeap, c) if len(ns.used) > ns.maxUsed { s := time.Now() ns.earliest = heap.Pop(ns.usedHeap).(int64) ns.stats.TimingDuration("Heap.Latency", time.Since(s)) delete(ns.used, ns.earliest) } ns.stats.Inc("Valid", 1) return true }
[ "func", "(", "ns", "*", "NonceService", ")", "Valid", "(", "nonce", "string", ")", "bool", "{", "c", ",", "err", ":=", "ns", ".", "decrypt", "(", "nonce", ")", "\n", "if", "err", "!=", "nil", "{", "ns", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "false", "\n", "}", "\n\n", "ns", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "ns", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "c", ">", "ns", ".", "latest", "{", "ns", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "false", "\n", "}", "\n\n", "if", "c", "<=", "ns", ".", "earliest", "{", "ns", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "false", "\n", "}", "\n\n", "if", "ns", ".", "used", "[", "c", "]", "{", "ns", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "false", "\n", "}", "\n\n", "ns", ".", "used", "[", "c", "]", "=", "true", "\n", "heap", ".", "Push", "(", "ns", ".", "usedHeap", ",", "c", ")", "\n", "if", "len", "(", "ns", ".", "used", ")", ">", "ns", ".", "maxUsed", "{", "s", ":=", "time", ".", "Now", "(", ")", "\n", "ns", ".", "earliest", "=", "heap", ".", "Pop", "(", "ns", ".", "usedHeap", ")", ".", "(", "int64", ")", "\n", "ns", ".", "stats", ".", "TimingDuration", "(", "\"", "\"", ",", "time", ".", "Since", "(", "s", ")", ")", "\n", "delete", "(", "ns", ".", "used", ",", "ns", ".", "earliest", ")", "\n", "}", "\n\n", "ns", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "return", "true", "\n", "}" ]
// Valid determines whether the provided Nonce string is valid, returning // true if so.
[ "Valid", "determines", "whether", "the", "provided", "Nonce", "string", "is", "valid", "returning", "true", "if", "so", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/nonce/nonce.go#L156-L191
train
letsencrypt/boulder
ctpolicy/ctpolicy.go
New
func New(pub core.Publisher, groups []cmd.CTGroup, informational []cmd.LogDescription, log blog.Logger, stats metrics.Scope, ) *CTPolicy { var finalLogs []cmd.LogDescription for _, group := range groups { for _, log := range group.Logs { if log.SubmitFinalCert { finalLogs = append(finalLogs, log) } } } for _, log := range informational { if log.SubmitFinalCert { finalLogs = append(finalLogs, log) } } winnerCounter := prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "sct_race_winner", Help: "Counter of logs that win SCT submission races.", }, []string{"log", "group"}, ) stats.MustRegister(winnerCounter) return &CTPolicy{ pub: pub, groups: groups, informational: informational, finalLogs: finalLogs, log: log, winnerCounter: winnerCounter, } }
go
func New(pub core.Publisher, groups []cmd.CTGroup, informational []cmd.LogDescription, log blog.Logger, stats metrics.Scope, ) *CTPolicy { var finalLogs []cmd.LogDescription for _, group := range groups { for _, log := range group.Logs { if log.SubmitFinalCert { finalLogs = append(finalLogs, log) } } } for _, log := range informational { if log.SubmitFinalCert { finalLogs = append(finalLogs, log) } } winnerCounter := prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "sct_race_winner", Help: "Counter of logs that win SCT submission races.", }, []string{"log", "group"}, ) stats.MustRegister(winnerCounter) return &CTPolicy{ pub: pub, groups: groups, informational: informational, finalLogs: finalLogs, log: log, winnerCounter: winnerCounter, } }
[ "func", "New", "(", "pub", "core", ".", "Publisher", ",", "groups", "[", "]", "cmd", ".", "CTGroup", ",", "informational", "[", "]", "cmd", ".", "LogDescription", ",", "log", "blog", ".", "Logger", ",", "stats", "metrics", ".", "Scope", ",", ")", "*", "CTPolicy", "{", "var", "finalLogs", "[", "]", "cmd", ".", "LogDescription", "\n", "for", "_", ",", "group", ":=", "range", "groups", "{", "for", "_", ",", "log", ":=", "range", "group", ".", "Logs", "{", "if", "log", ".", "SubmitFinalCert", "{", "finalLogs", "=", "append", "(", "finalLogs", ",", "log", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "log", ":=", "range", "informational", "{", "if", "log", ".", "SubmitFinalCert", "{", "finalLogs", "=", "append", "(", "finalLogs", ",", "log", ")", "\n", "}", "\n", "}", "\n\n", "winnerCounter", ":=", "prometheus", ".", "NewCounterVec", "(", "prometheus", ".", "CounterOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ",", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", ")", "\n", "stats", ".", "MustRegister", "(", "winnerCounter", ")", "\n\n", "return", "&", "CTPolicy", "{", "pub", ":", "pub", ",", "groups", ":", "groups", ",", "informational", ":", "informational", ",", "finalLogs", ":", "finalLogs", ",", "log", ":", "log", ",", "winnerCounter", ":", "winnerCounter", ",", "}", "\n", "}" ]
// New creates a new CTPolicy struct
[ "New", "creates", "a", "new", "CTPolicy", "struct" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ctpolicy/ctpolicy.go#L32-L69
train
letsencrypt/boulder
ctpolicy/ctpolicy.go
GetSCTs
func (ctp *CTPolicy) GetSCTs(ctx context.Context, cert core.CertDER, expiration time.Time) (core.SCTDERs, error) { results := make(chan result, len(ctp.groups)) subCtx, cancel := context.WithCancel(ctx) defer cancel() for i, g := range ctp.groups { go func(i int, g cmd.CTGroup) { sct, err := ctp.race(subCtx, cert, g, expiration) // Only one of these will be non-nil if err != nil { results <- result{err: berrors.MissingSCTsError("CT log group %q: %s", g.Name, err)} } results <- result{sct: sct} }(i, g) } isPrecert := true for _, log := range ctp.informational { go func(l cmd.LogDescription) { // We use a context.Background() here instead of subCtx because these // submissions are running in a goroutine and we don't want them to be // cancelled when the caller of CTPolicy.GetSCTs returns and cancels // its RPC context. uri, key, err := l.Info(expiration) if err != nil { ctp.log.Errf("unable to get log info: %s", err) return } _, err = ctp.pub.SubmitToSingleCTWithResult(context.Background(), &pubpb.Request{ LogURL: &uri, LogPublicKey: &key, Der: cert, Precert: &isPrecert, }) if err != nil { ctp.log.Warningf("ct submission to informational log %q failed: %s", uri, err) } }(log) } var ret core.SCTDERs for i := 0; i < len(ctp.groups); i++ { res := <-results // If any one group fails to get a SCT then we fail out immediately // cancel any other in progress work as we can't continue if res.err != nil { // Returning triggers the defer'd context cancellation method return nil, res.err } ret = append(ret, res.sct) } return ret, nil }
go
func (ctp *CTPolicy) GetSCTs(ctx context.Context, cert core.CertDER, expiration time.Time) (core.SCTDERs, error) { results := make(chan result, len(ctp.groups)) subCtx, cancel := context.WithCancel(ctx) defer cancel() for i, g := range ctp.groups { go func(i int, g cmd.CTGroup) { sct, err := ctp.race(subCtx, cert, g, expiration) // Only one of these will be non-nil if err != nil { results <- result{err: berrors.MissingSCTsError("CT log group %q: %s", g.Name, err)} } results <- result{sct: sct} }(i, g) } isPrecert := true for _, log := range ctp.informational { go func(l cmd.LogDescription) { // We use a context.Background() here instead of subCtx because these // submissions are running in a goroutine and we don't want them to be // cancelled when the caller of CTPolicy.GetSCTs returns and cancels // its RPC context. uri, key, err := l.Info(expiration) if err != nil { ctp.log.Errf("unable to get log info: %s", err) return } _, err = ctp.pub.SubmitToSingleCTWithResult(context.Background(), &pubpb.Request{ LogURL: &uri, LogPublicKey: &key, Der: cert, Precert: &isPrecert, }) if err != nil { ctp.log.Warningf("ct submission to informational log %q failed: %s", uri, err) } }(log) } var ret core.SCTDERs for i := 0; i < len(ctp.groups); i++ { res := <-results // If any one group fails to get a SCT then we fail out immediately // cancel any other in progress work as we can't continue if res.err != nil { // Returning triggers the defer'd context cancellation method return nil, res.err } ret = append(ret, res.sct) } return ret, nil }
[ "func", "(", "ctp", "*", "CTPolicy", ")", "GetSCTs", "(", "ctx", "context", ".", "Context", ",", "cert", "core", ".", "CertDER", ",", "expiration", "time", ".", "Time", ")", "(", "core", ".", "SCTDERs", ",", "error", ")", "{", "results", ":=", "make", "(", "chan", "result", ",", "len", "(", "ctp", ".", "groups", ")", ")", "\n", "subCtx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "defer", "cancel", "(", ")", "\n", "for", "i", ",", "g", ":=", "range", "ctp", ".", "groups", "{", "go", "func", "(", "i", "int", ",", "g", "cmd", ".", "CTGroup", ")", "{", "sct", ",", "err", ":=", "ctp", ".", "race", "(", "subCtx", ",", "cert", ",", "g", ",", "expiration", ")", "\n", "// Only one of these will be non-nil", "if", "err", "!=", "nil", "{", "results", "<-", "result", "{", "err", ":", "berrors", ".", "MissingSCTsError", "(", "\"", "\"", ",", "g", ".", "Name", ",", "err", ")", "}", "\n", "}", "\n", "results", "<-", "result", "{", "sct", ":", "sct", "}", "\n", "}", "(", "i", ",", "g", ")", "\n", "}", "\n", "isPrecert", ":=", "true", "\n", "for", "_", ",", "log", ":=", "range", "ctp", ".", "informational", "{", "go", "func", "(", "l", "cmd", ".", "LogDescription", ")", "{", "// We use a context.Background() here instead of subCtx because these", "// submissions are running in a goroutine and we don't want them to be", "// cancelled when the caller of CTPolicy.GetSCTs returns and cancels", "// its RPC context.", "uri", ",", "key", ",", "err", ":=", "l", ".", "Info", "(", "expiration", ")", "\n", "if", "err", "!=", "nil", "{", "ctp", ".", "log", ".", "Errf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "_", ",", "err", "=", "ctp", ".", "pub", ".", "SubmitToSingleCTWithResult", "(", "context", ".", "Background", "(", ")", ",", "&", "pubpb", ".", "Request", "{", "LogURL", ":", "&", "uri", ",", "LogPublicKey", ":", "&", "key", ",", "Der", ":", "cert", ",", "Precert", ":", "&", "isPrecert", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "ctp", ".", "log", ".", "Warningf", "(", "\"", "\"", ",", "uri", ",", "err", ")", "\n", "}", "\n", "}", "(", "log", ")", "\n", "}", "\n\n", "var", "ret", "core", ".", "SCTDERs", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "ctp", ".", "groups", ")", ";", "i", "++", "{", "res", ":=", "<-", "results", "\n", "// If any one group fails to get a SCT then we fail out immediately", "// cancel any other in progress work as we can't continue", "if", "res", ".", "err", "!=", "nil", "{", "// Returning triggers the defer'd context cancellation method", "return", "nil", ",", "res", ".", "err", "\n", "}", "\n", "ret", "=", "append", "(", "ret", ",", "res", ".", "sct", ")", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// GetSCTs attempts to retrieve a SCT from each configured grouping of logs and returns // the set of SCTs to the caller.
[ "GetSCTs", "attempts", "to", "retrieve", "a", "SCT", "from", "each", "configured", "grouping", "of", "logs", "and", "returns", "the", "set", "of", "SCTs", "to", "the", "caller", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ctpolicy/ctpolicy.go#L143-L193
train
letsencrypt/boulder
ctpolicy/ctpolicy.go
SubmitFinalCert
func (ctp *CTPolicy) SubmitFinalCert(cert []byte, expiration time.Time) { falseVar := false for _, log := range ctp.finalLogs { go func(l cmd.LogDescription) { uri, key, err := l.Info(expiration) if err != nil { ctp.log.Errf("unable to get log info: %s", err) return } _, err = ctp.pub.SubmitToSingleCTWithResult(context.Background(), &pubpb.Request{ LogURL: &uri, LogPublicKey: &key, Der: cert, Precert: &falseVar, StoreSCT: &falseVar, }) if err != nil { ctp.log.Warningf("ct submission of final cert to log %q failed: %s", uri, err) } }(log) } }
go
func (ctp *CTPolicy) SubmitFinalCert(cert []byte, expiration time.Time) { falseVar := false for _, log := range ctp.finalLogs { go func(l cmd.LogDescription) { uri, key, err := l.Info(expiration) if err != nil { ctp.log.Errf("unable to get log info: %s", err) return } _, err = ctp.pub.SubmitToSingleCTWithResult(context.Background(), &pubpb.Request{ LogURL: &uri, LogPublicKey: &key, Der: cert, Precert: &falseVar, StoreSCT: &falseVar, }) if err != nil { ctp.log.Warningf("ct submission of final cert to log %q failed: %s", uri, err) } }(log) } }
[ "func", "(", "ctp", "*", "CTPolicy", ")", "SubmitFinalCert", "(", "cert", "[", "]", "byte", ",", "expiration", "time", ".", "Time", ")", "{", "falseVar", ":=", "false", "\n", "for", "_", ",", "log", ":=", "range", "ctp", ".", "finalLogs", "{", "go", "func", "(", "l", "cmd", ".", "LogDescription", ")", "{", "uri", ",", "key", ",", "err", ":=", "l", ".", "Info", "(", "expiration", ")", "\n", "if", "err", "!=", "nil", "{", "ctp", ".", "log", ".", "Errf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "_", ",", "err", "=", "ctp", ".", "pub", ".", "SubmitToSingleCTWithResult", "(", "context", ".", "Background", "(", ")", ",", "&", "pubpb", ".", "Request", "{", "LogURL", ":", "&", "uri", ",", "LogPublicKey", ":", "&", "key", ",", "Der", ":", "cert", ",", "Precert", ":", "&", "falseVar", ",", "StoreSCT", ":", "&", "falseVar", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "ctp", ".", "log", ".", "Warningf", "(", "\"", "\"", ",", "uri", ",", "err", ")", "\n", "}", "\n", "}", "(", "log", ")", "\n", "}", "\n", "}" ]
// SubmitFinalCert submits finalized certificates created from precertificates // to any configured logs
[ "SubmitFinalCert", "submits", "finalized", "certificates", "created", "from", "precertificates", "to", "any", "configured", "logs" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ctpolicy/ctpolicy.go#L197-L218
train
letsencrypt/boulder
web/context.go
WriteHeader
func (r *responseWriterWithStatus) WriteHeader(code int) { r.code = code r.ResponseWriter.WriteHeader(code) }
go
func (r *responseWriterWithStatus) WriteHeader(code int) { r.code = code r.ResponseWriter.WriteHeader(code) }
[ "func", "(", "r", "*", "responseWriterWithStatus", ")", "WriteHeader", "(", "code", "int", ")", "{", "r", ".", "code", "=", "code", "\n", "r", ".", "ResponseWriter", ".", "WriteHeader", "(", "code", ")", "\n", "}" ]
// WriteHeader stores a status code for generating stats.
[ "WriteHeader", "stores", "a", "status", "code", "for", "generating", "stats", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/web/context.go#L83-L86
train
letsencrypt/boulder
grpc/va-wrappers.go
PerformValidation
func (vac ValidationAuthorityGRPCClient) PerformValidation(ctx context.Context, domain string, challenge core.Challenge, authz core.Authorization) ([]core.ValidationRecord, error) { req, err := argsToPerformValidationRequest(domain, challenge, authz) if err != nil { return nil, err } gRecords, err := vac.gc.PerformValidation(ctx, req) if err != nil { return nil, err } records, prob, err := pbToValidationResult(gRecords) if err != nil { return nil, err } if prob != nil { return records, prob } // We return nil explicitly to avoid "typed nil" problems. // https://golang.org/doc/faq#nil_error return records, nil }
go
func (vac ValidationAuthorityGRPCClient) PerformValidation(ctx context.Context, domain string, challenge core.Challenge, authz core.Authorization) ([]core.ValidationRecord, error) { req, err := argsToPerformValidationRequest(domain, challenge, authz) if err != nil { return nil, err } gRecords, err := vac.gc.PerformValidation(ctx, req) if err != nil { return nil, err } records, prob, err := pbToValidationResult(gRecords) if err != nil { return nil, err } if prob != nil { return records, prob } // We return nil explicitly to avoid "typed nil" problems. // https://golang.org/doc/faq#nil_error return records, nil }
[ "func", "(", "vac", "ValidationAuthorityGRPCClient", ")", "PerformValidation", "(", "ctx", "context", ".", "Context", ",", "domain", "string", ",", "challenge", "core", ".", "Challenge", ",", "authz", "core", ".", "Authorization", ")", "(", "[", "]", "core", ".", "ValidationRecord", ",", "error", ")", "{", "req", ",", "err", ":=", "argsToPerformValidationRequest", "(", "domain", ",", "challenge", ",", "authz", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "gRecords", ",", "err", ":=", "vac", ".", "gc", ".", "PerformValidation", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "records", ",", "prob", ",", "err", ":=", "pbToValidationResult", "(", "gRecords", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "prob", "!=", "nil", "{", "return", "records", ",", "prob", "\n", "}", "\n\n", "// We return nil explicitly to avoid \"typed nil\" problems.", "// https://golang.org/doc/faq#nil_error", "return", "records", ",", "nil", "\n", "}" ]
// PerformValidation has the VA revalidate the specified challenge and returns // the updated Challenge object.
[ "PerformValidation", "has", "the", "VA", "revalidate", "the", "specified", "challenge", "and", "returns", "the", "updated", "Challenge", "object", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/va-wrappers.go#L57-L77
train
letsencrypt/boulder
wfe2/wfe.go
requestProto
func requestProto(request *http.Request) string { proto := "http" // If the request was received via TLS, use `https://` for the protocol if request.TLS != nil { proto = "https" } // Allow upstream proxies to specify the forwarded protocol. Allow this value // to override our own guess. if specifiedProto := request.Header.Get("X-Forwarded-Proto"); specifiedProto != "" { proto = specifiedProto } return proto }
go
func requestProto(request *http.Request) string { proto := "http" // If the request was received via TLS, use `https://` for the protocol if request.TLS != nil { proto = "https" } // Allow upstream proxies to specify the forwarded protocol. Allow this value // to override our own guess. if specifiedProto := request.Header.Get("X-Forwarded-Proto"); specifiedProto != "" { proto = specifiedProto } return proto }
[ "func", "requestProto", "(", "request", "*", "http", ".", "Request", ")", "string", "{", "proto", ":=", "\"", "\"", "\n\n", "// If the request was received via TLS, use `https://` for the protocol", "if", "request", ".", "TLS", "!=", "nil", "{", "proto", "=", "\"", "\"", "\n", "}", "\n\n", "// Allow upstream proxies to specify the forwarded protocol. Allow this value", "// to override our own guess.", "if", "specifiedProto", ":=", "request", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ";", "specifiedProto", "!=", "\"", "\"", "{", "proto", "=", "specifiedProto", "\n", "}", "\n\n", "return", "proto", "\n", "}" ]
// requestProto returns "http" for HTTP requests and "https" for HTTPS // requests. It supports the use of "X-Forwarded-Proto" to override the protocol.
[ "requestProto", "returns", "http", "for", "HTTP", "requests", "and", "https", "for", "HTTPS", "requests", ".", "It", "supports", "the", "use", "of", "X", "-", "Forwarded", "-", "Proto", "to", "override", "the", "protocol", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L251-L266
train
letsencrypt/boulder
wfe2/wfe.go
Nonce
func (wfe *WebFrontEndImpl) Nonce( ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) { statusCode := http.StatusNoContent // The ACME specification says GET requets should receive http.StatusNoContent // and HEAD requests should receive http.StatusOK. We gate this with the // HeadNonceStatusOK feature flag because it may break clients that are // programmed to expect StatusOK. if features.Enabled(features.HeadNonceStatusOK) && request.Method == "HEAD" { statusCode = http.StatusOK } response.WriteHeader(statusCode) }
go
func (wfe *WebFrontEndImpl) Nonce( ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) { statusCode := http.StatusNoContent // The ACME specification says GET requets should receive http.StatusNoContent // and HEAD requests should receive http.StatusOK. We gate this with the // HeadNonceStatusOK feature flag because it may break clients that are // programmed to expect StatusOK. if features.Enabled(features.HeadNonceStatusOK) && request.Method == "HEAD" { statusCode = http.StatusOK } response.WriteHeader(statusCode) }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "Nonce", "(", "ctx", "context", ".", "Context", ",", "logEvent", "*", "web", ".", "RequestEvent", ",", "response", "http", ".", "ResponseWriter", ",", "request", "*", "http", ".", "Request", ")", "{", "statusCode", ":=", "http", ".", "StatusNoContent", "\n", "// The ACME specification says GET requets should receive http.StatusNoContent", "// and HEAD requests should receive http.StatusOK. We gate this with the", "// HeadNonceStatusOK feature flag because it may break clients that are", "// programmed to expect StatusOK.", "if", "features", ".", "Enabled", "(", "features", ".", "HeadNonceStatusOK", ")", "&&", "request", ".", "Method", "==", "\"", "\"", "{", "statusCode", "=", "http", ".", "StatusOK", "\n", "}", "\n", "response", ".", "WriteHeader", "(", "statusCode", ")", "\n", "}" ]
// Nonce is an endpoint for getting a fresh nonce with an HTTP GET or HEAD // request. This endpoint only returns a status code header - the `HandleFunc` // wrapper ensures that a nonce is written in the correct response header.
[ "Nonce", "is", "an", "endpoint", "for", "getting", "a", "fresh", "nonce", "with", "an", "HTTP", "GET", "or", "HEAD", "request", ".", "This", "endpoint", "only", "returns", "a", "status", "code", "header", "-", "the", "HandleFunc", "wrapper", "ensures", "that", "a", "nonce", "is", "written", "in", "the", "correct", "response", "header", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L436-L450
train
letsencrypt/boulder
wfe2/wfe.go
processRevocation
func (wfe *WebFrontEndImpl) processRevocation( ctx context.Context, jwsBody []byte, acctID int64, authorizedToRevoke authorizedToRevokeCert, request *http.Request, logEvent *web.RequestEvent) *probs.ProblemDetails { // Read the revoke request from the JWS payload var revokeRequest struct { CertificateDER core.JSONBuffer `json:"certificate"` Reason *revocation.Reason `json:"reason"` } if err := json.Unmarshal(jwsBody, &revokeRequest); err != nil { return probs.Malformed("Unable to JSON parse revoke request") } // Parse the provided certificate providedCert, err := x509.ParseCertificate(revokeRequest.CertificateDER) if err != nil { return probs.Malformed("Unable to parse certificate DER") } // Compute and record the serial number of the provided certificate serial := core.SerialToString(providedCert.SerialNumber) logEvent.Extra["ProvidedCertificateSerial"] = serial // Lookup the certificate by the serial. If the certificate wasn't found, or // it wasn't a byte-for-byte match to the certificate requested for // revocation, return an error cert, err := wfe.SA.GetCertificate(ctx, serial) if err != nil || !bytes.Equal(cert.DER, revokeRequest.CertificateDER) { return probs.NotFound("No such certificate") } // Parse the certificate into memory parsedCertificate, err := x509.ParseCertificate(cert.DER) if err != nil { // InternalServerError because cert.DER came from our own DB. return probs.ServerInternal("invalid parse of stored certificate") } logEvent.Extra["RetrievedCertificateSerial"] = core.SerialToString(parsedCertificate.SerialNumber) logEvent.Extra["RetrievedCertificateDNSNames"] = parsedCertificate.DNSNames if parsedCertificate.NotAfter.Before(wfe.clk.Now()) { return probs.Unauthorized("Certificate is expired") } // Check the certificate status for the provided certificate to see if it is // already revoked certStatus, err := wfe.SA.GetCertificateStatus(ctx, serial) if err != nil { return probs.NotFound("Certificate status not yet available") } logEvent.Extra["CertificateStatus"] = certStatus.Status if certStatus.Status == core.OCSPStatusRevoked { return probs.AlreadyRevoked("Certificate already revoked") } // Validate that the requester is authenticated to revoke the given certificate prob := authorizedToRevoke(parsedCertificate) if prob != nil { return prob } // Verify the revocation reason supplied is allowed reason := revocation.Reason(0) if revokeRequest.Reason != nil && wfe.AcceptRevocationReason { if _, present := revocation.UserAllowedReasons[*revokeRequest.Reason]; !present { return probs.Malformed("unsupported revocation reason code provided") } reason = *revokeRequest.Reason } // Revoke the certificate. AcctID may be 0 if there is no associated account // (e.g. it was a self-authenticated JWS using the certificate public key) if err := wfe.RA.RevokeCertificateWithReg(ctx, *parsedCertificate, reason, acctID); err != nil { return web.ProblemDetailsForError(err, "Failed to revoke certificate") } wfe.log.Debugf("Revoked %v", serial) return nil }
go
func (wfe *WebFrontEndImpl) processRevocation( ctx context.Context, jwsBody []byte, acctID int64, authorizedToRevoke authorizedToRevokeCert, request *http.Request, logEvent *web.RequestEvent) *probs.ProblemDetails { // Read the revoke request from the JWS payload var revokeRequest struct { CertificateDER core.JSONBuffer `json:"certificate"` Reason *revocation.Reason `json:"reason"` } if err := json.Unmarshal(jwsBody, &revokeRequest); err != nil { return probs.Malformed("Unable to JSON parse revoke request") } // Parse the provided certificate providedCert, err := x509.ParseCertificate(revokeRequest.CertificateDER) if err != nil { return probs.Malformed("Unable to parse certificate DER") } // Compute and record the serial number of the provided certificate serial := core.SerialToString(providedCert.SerialNumber) logEvent.Extra["ProvidedCertificateSerial"] = serial // Lookup the certificate by the serial. If the certificate wasn't found, or // it wasn't a byte-for-byte match to the certificate requested for // revocation, return an error cert, err := wfe.SA.GetCertificate(ctx, serial) if err != nil || !bytes.Equal(cert.DER, revokeRequest.CertificateDER) { return probs.NotFound("No such certificate") } // Parse the certificate into memory parsedCertificate, err := x509.ParseCertificate(cert.DER) if err != nil { // InternalServerError because cert.DER came from our own DB. return probs.ServerInternal("invalid parse of stored certificate") } logEvent.Extra["RetrievedCertificateSerial"] = core.SerialToString(parsedCertificate.SerialNumber) logEvent.Extra["RetrievedCertificateDNSNames"] = parsedCertificate.DNSNames if parsedCertificate.NotAfter.Before(wfe.clk.Now()) { return probs.Unauthorized("Certificate is expired") } // Check the certificate status for the provided certificate to see if it is // already revoked certStatus, err := wfe.SA.GetCertificateStatus(ctx, serial) if err != nil { return probs.NotFound("Certificate status not yet available") } logEvent.Extra["CertificateStatus"] = certStatus.Status if certStatus.Status == core.OCSPStatusRevoked { return probs.AlreadyRevoked("Certificate already revoked") } // Validate that the requester is authenticated to revoke the given certificate prob := authorizedToRevoke(parsedCertificate) if prob != nil { return prob } // Verify the revocation reason supplied is allowed reason := revocation.Reason(0) if revokeRequest.Reason != nil && wfe.AcceptRevocationReason { if _, present := revocation.UserAllowedReasons[*revokeRequest.Reason]; !present { return probs.Malformed("unsupported revocation reason code provided") } reason = *revokeRequest.Reason } // Revoke the certificate. AcctID may be 0 if there is no associated account // (e.g. it was a self-authenticated JWS using the certificate public key) if err := wfe.RA.RevokeCertificateWithReg(ctx, *parsedCertificate, reason, acctID); err != nil { return web.ProblemDetailsForError(err, "Failed to revoke certificate") } wfe.log.Debugf("Revoked %v", serial) return nil }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "processRevocation", "(", "ctx", "context", ".", "Context", ",", "jwsBody", "[", "]", "byte", ",", "acctID", "int64", ",", "authorizedToRevoke", "authorizedToRevokeCert", ",", "request", "*", "http", ".", "Request", ",", "logEvent", "*", "web", ".", "RequestEvent", ")", "*", "probs", ".", "ProblemDetails", "{", "// Read the revoke request from the JWS payload", "var", "revokeRequest", "struct", "{", "CertificateDER", "core", ".", "JSONBuffer", "`json:\"certificate\"`", "\n", "Reason", "*", "revocation", ".", "Reason", "`json:\"reason\"`", "\n", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "jwsBody", ",", "&", "revokeRequest", ")", ";", "err", "!=", "nil", "{", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Parse the provided certificate", "providedCert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "revokeRequest", ".", "CertificateDER", ")", "\n", "if", "err", "!=", "nil", "{", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Compute and record the serial number of the provided certificate", "serial", ":=", "core", ".", "SerialToString", "(", "providedCert", ".", "SerialNumber", ")", "\n", "logEvent", ".", "Extra", "[", "\"", "\"", "]", "=", "serial", "\n\n", "// Lookup the certificate by the serial. If the certificate wasn't found, or", "// it wasn't a byte-for-byte match to the certificate requested for", "// revocation, return an error", "cert", ",", "err", ":=", "wfe", ".", "SA", ".", "GetCertificate", "(", "ctx", ",", "serial", ")", "\n", "if", "err", "!=", "nil", "||", "!", "bytes", ".", "Equal", "(", "cert", ".", "DER", ",", "revokeRequest", ".", "CertificateDER", ")", "{", "return", "probs", ".", "NotFound", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Parse the certificate into memory", "parsedCertificate", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "cert", ".", "DER", ")", "\n", "if", "err", "!=", "nil", "{", "// InternalServerError because cert.DER came from our own DB.", "return", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", "\n", "}", "\n", "logEvent", ".", "Extra", "[", "\"", "\"", "]", "=", "core", ".", "SerialToString", "(", "parsedCertificate", ".", "SerialNumber", ")", "\n", "logEvent", ".", "Extra", "[", "\"", "\"", "]", "=", "parsedCertificate", ".", "DNSNames", "\n\n", "if", "parsedCertificate", ".", "NotAfter", ".", "Before", "(", "wfe", ".", "clk", ".", "Now", "(", ")", ")", "{", "return", "probs", ".", "Unauthorized", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check the certificate status for the provided certificate to see if it is", "// already revoked", "certStatus", ",", "err", ":=", "wfe", ".", "SA", ".", "GetCertificateStatus", "(", "ctx", ",", "serial", ")", "\n", "if", "err", "!=", "nil", "{", "return", "probs", ".", "NotFound", "(", "\"", "\"", ")", "\n", "}", "\n", "logEvent", ".", "Extra", "[", "\"", "\"", "]", "=", "certStatus", ".", "Status", "\n\n", "if", "certStatus", ".", "Status", "==", "core", ".", "OCSPStatusRevoked", "{", "return", "probs", ".", "AlreadyRevoked", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Validate that the requester is authenticated to revoke the given certificate", "prob", ":=", "authorizedToRevoke", "(", "parsedCertificate", ")", "\n", "if", "prob", "!=", "nil", "{", "return", "prob", "\n", "}", "\n\n", "// Verify the revocation reason supplied is allowed", "reason", ":=", "revocation", ".", "Reason", "(", "0", ")", "\n", "if", "revokeRequest", ".", "Reason", "!=", "nil", "&&", "wfe", ".", "AcceptRevocationReason", "{", "if", "_", ",", "present", ":=", "revocation", ".", "UserAllowedReasons", "[", "*", "revokeRequest", ".", "Reason", "]", ";", "!", "present", "{", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n", "reason", "=", "*", "revokeRequest", ".", "Reason", "\n", "}", "\n\n", "// Revoke the certificate. AcctID may be 0 if there is no associated account", "// (e.g. it was a self-authenticated JWS using the certificate public key)", "if", "err", ":=", "wfe", ".", "RA", ".", "RevokeCertificateWithReg", "(", "ctx", ",", "*", "parsedCertificate", ",", "reason", ",", "acctID", ")", ";", "err", "!=", "nil", "{", "return", "web", ".", "ProblemDetailsForError", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "wfe", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "serial", ")", "\n", "return", "nil", "\n", "}" ]
// processRevocation accepts the payload for a revocation request along with // an account ID and a callback used to decide if the requester is authorized to // revoke a given certificate. If the request can not be authenticated or the // requester is not authorized to revoke the certificate requested a problem is // returned. Otherwise the certificate is marked revoked through the SA.
[ "processRevocation", "accepts", "the", "payload", "for", "a", "revocation", "request", "along", "with", "an", "account", "ID", "and", "a", "callback", "used", "to", "decide", "if", "the", "requester", "is", "authorized", "to", "revoke", "a", "given", "certificate", ".", "If", "the", "request", "can", "not", "be", "authenticated", "or", "the", "requester", "is", "not", "authorized", "to", "revoke", "the", "certificate", "requested", "a", "problem", "is", "returned", ".", "Otherwise", "the", "certificate", "is", "marked", "revoked", "through", "the", "SA", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L629-L711
train
letsencrypt/boulder
wfe2/wfe.go
revokeCertByKeyID
func (wfe *WebFrontEndImpl) revokeCertByKeyID( ctx context.Context, outerJWS *jose.JSONWebSignature, request *http.Request, logEvent *web.RequestEvent) *probs.ProblemDetails { // For Key ID revocations we authenticate the outer JWS by using // `validJWSForAccount` similar to other WFE endpoints jwsBody, _, acct, prob := wfe.validJWSForAccount(outerJWS, request, ctx, logEvent) if prob != nil { return prob } // For Key ID revocations we decide if an account is able to revoke a specific // certificate by checking that the account has valid authorizations for all // of the names in the certificate or was the issuing account authorizedToRevoke := func(parsedCertificate *x509.Certificate) *probs.ProblemDetails { cert, err := wfe.SA.GetCertificate(ctx, core.SerialToString(parsedCertificate.SerialNumber)) if err != nil { return probs.ServerInternal("Failed to retrieve certificate") } if cert.RegistrationID == acct.ID { return nil } valid, err := wfe.acctHoldsAuthorizations(ctx, acct.ID, parsedCertificate.DNSNames) if err != nil { return probs.ServerInternal("Failed to retrieve authorizations for names in certificate") } if !valid { return probs.Unauthorized( "The key ID specified in the revocation request does not hold valid authorizations for all names in the certificate to be revoked") } return nil } return wfe.processRevocation(ctx, jwsBody, acct.ID, authorizedToRevoke, request, logEvent) }
go
func (wfe *WebFrontEndImpl) revokeCertByKeyID( ctx context.Context, outerJWS *jose.JSONWebSignature, request *http.Request, logEvent *web.RequestEvent) *probs.ProblemDetails { // For Key ID revocations we authenticate the outer JWS by using // `validJWSForAccount` similar to other WFE endpoints jwsBody, _, acct, prob := wfe.validJWSForAccount(outerJWS, request, ctx, logEvent) if prob != nil { return prob } // For Key ID revocations we decide if an account is able to revoke a specific // certificate by checking that the account has valid authorizations for all // of the names in the certificate or was the issuing account authorizedToRevoke := func(parsedCertificate *x509.Certificate) *probs.ProblemDetails { cert, err := wfe.SA.GetCertificate(ctx, core.SerialToString(parsedCertificate.SerialNumber)) if err != nil { return probs.ServerInternal("Failed to retrieve certificate") } if cert.RegistrationID == acct.ID { return nil } valid, err := wfe.acctHoldsAuthorizations(ctx, acct.ID, parsedCertificate.DNSNames) if err != nil { return probs.ServerInternal("Failed to retrieve authorizations for names in certificate") } if !valid { return probs.Unauthorized( "The key ID specified in the revocation request does not hold valid authorizations for all names in the certificate to be revoked") } return nil } return wfe.processRevocation(ctx, jwsBody, acct.ID, authorizedToRevoke, request, logEvent) }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "revokeCertByKeyID", "(", "ctx", "context", ".", "Context", ",", "outerJWS", "*", "jose", ".", "JSONWebSignature", ",", "request", "*", "http", ".", "Request", ",", "logEvent", "*", "web", ".", "RequestEvent", ")", "*", "probs", ".", "ProblemDetails", "{", "// For Key ID revocations we authenticate the outer JWS by using", "// `validJWSForAccount` similar to other WFE endpoints", "jwsBody", ",", "_", ",", "acct", ",", "prob", ":=", "wfe", ".", "validJWSForAccount", "(", "outerJWS", ",", "request", ",", "ctx", ",", "logEvent", ")", "\n", "if", "prob", "!=", "nil", "{", "return", "prob", "\n", "}", "\n", "// For Key ID revocations we decide if an account is able to revoke a specific", "// certificate by checking that the account has valid authorizations for all", "// of the names in the certificate or was the issuing account", "authorizedToRevoke", ":=", "func", "(", "parsedCertificate", "*", "x509", ".", "Certificate", ")", "*", "probs", ".", "ProblemDetails", "{", "cert", ",", "err", ":=", "wfe", ".", "SA", ".", "GetCertificate", "(", "ctx", ",", "core", ".", "SerialToString", "(", "parsedCertificate", ".", "SerialNumber", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cert", ".", "RegistrationID", "==", "acct", ".", "ID", "{", "return", "nil", "\n", "}", "\n", "valid", ",", "err", ":=", "wfe", ".", "acctHoldsAuthorizations", "(", "ctx", ",", "acct", ".", "ID", ",", "parsedCertificate", ".", "DNSNames", ")", "\n", "if", "err", "!=", "nil", "{", "return", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "valid", "{", "return", "probs", ".", "Unauthorized", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "wfe", ".", "processRevocation", "(", "ctx", ",", "jwsBody", ",", "acct", ".", "ID", ",", "authorizedToRevoke", ",", "request", ",", "logEvent", ")", "\n", "}" ]
// revokeCertByKeyID processes an outer JWS as a revocation request that is // authenticated by a KeyID and the associated account.
[ "revokeCertByKeyID", "processes", "an", "outer", "JWS", "as", "a", "revocation", "request", "that", "is", "authenticated", "by", "a", "KeyID", "and", "the", "associated", "account", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L715-L748
train
letsencrypt/boulder
wfe2/wfe.go
revokeCertByJWK
func (wfe *WebFrontEndImpl) revokeCertByJWK( ctx context.Context, outerJWS *jose.JSONWebSignature, request *http.Request, logEvent *web.RequestEvent) *probs.ProblemDetails { // We maintain the requestKey as a var that is closed-over by the // `authorizedToRevoke` function to use var requestKey *jose.JSONWebKey // For embedded JWK revocations we authenticate the outer JWS by using // `validSelfAuthenticatedJWS` similar to new-reg and key rollover. // We do *not* use `validSelfAuthenticatedPOST` here because we've already // read the HTTP request body in `parseJWSRequest` and it is now empty. jwsBody, jwk, prob := wfe.validSelfAuthenticatedJWS(outerJWS, request, logEvent) if prob != nil { return prob } requestKey = jwk // For embedded JWK revocations we decide if a requester is able to revoke a specific // certificate by checking that to-be-revoked certificate has the same public // key as the JWK that was used to authenticate the request authorizedToRevoke := func(parsedCertificate *x509.Certificate) *probs.ProblemDetails { if !core.KeyDigestEquals(requestKey, parsedCertificate.PublicKey) { return probs.Unauthorized( "JWK embedded in revocation request must be the same public key as the cert to be revoked") } return nil } // We use `0` as the account ID provided to `processRevocation` because this // is a self-authenticated request. return wfe.processRevocation(ctx, jwsBody, 0, authorizedToRevoke, request, logEvent) }
go
func (wfe *WebFrontEndImpl) revokeCertByJWK( ctx context.Context, outerJWS *jose.JSONWebSignature, request *http.Request, logEvent *web.RequestEvent) *probs.ProblemDetails { // We maintain the requestKey as a var that is closed-over by the // `authorizedToRevoke` function to use var requestKey *jose.JSONWebKey // For embedded JWK revocations we authenticate the outer JWS by using // `validSelfAuthenticatedJWS` similar to new-reg and key rollover. // We do *not* use `validSelfAuthenticatedPOST` here because we've already // read the HTTP request body in `parseJWSRequest` and it is now empty. jwsBody, jwk, prob := wfe.validSelfAuthenticatedJWS(outerJWS, request, logEvent) if prob != nil { return prob } requestKey = jwk // For embedded JWK revocations we decide if a requester is able to revoke a specific // certificate by checking that to-be-revoked certificate has the same public // key as the JWK that was used to authenticate the request authorizedToRevoke := func(parsedCertificate *x509.Certificate) *probs.ProblemDetails { if !core.KeyDigestEquals(requestKey, parsedCertificate.PublicKey) { return probs.Unauthorized( "JWK embedded in revocation request must be the same public key as the cert to be revoked") } return nil } // We use `0` as the account ID provided to `processRevocation` because this // is a self-authenticated request. return wfe.processRevocation(ctx, jwsBody, 0, authorizedToRevoke, request, logEvent) }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "revokeCertByJWK", "(", "ctx", "context", ".", "Context", ",", "outerJWS", "*", "jose", ".", "JSONWebSignature", ",", "request", "*", "http", ".", "Request", ",", "logEvent", "*", "web", ".", "RequestEvent", ")", "*", "probs", ".", "ProblemDetails", "{", "// We maintain the requestKey as a var that is closed-over by the", "// `authorizedToRevoke` function to use", "var", "requestKey", "*", "jose", ".", "JSONWebKey", "\n", "// For embedded JWK revocations we authenticate the outer JWS by using", "// `validSelfAuthenticatedJWS` similar to new-reg and key rollover.", "// We do *not* use `validSelfAuthenticatedPOST` here because we've already", "// read the HTTP request body in `parseJWSRequest` and it is now empty.", "jwsBody", ",", "jwk", ",", "prob", ":=", "wfe", ".", "validSelfAuthenticatedJWS", "(", "outerJWS", ",", "request", ",", "logEvent", ")", "\n", "if", "prob", "!=", "nil", "{", "return", "prob", "\n", "}", "\n", "requestKey", "=", "jwk", "\n", "// For embedded JWK revocations we decide if a requester is able to revoke a specific", "// certificate by checking that to-be-revoked certificate has the same public", "// key as the JWK that was used to authenticate the request", "authorizedToRevoke", ":=", "func", "(", "parsedCertificate", "*", "x509", ".", "Certificate", ")", "*", "probs", ".", "ProblemDetails", "{", "if", "!", "core", ".", "KeyDigestEquals", "(", "requestKey", ",", "parsedCertificate", ".", "PublicKey", ")", "{", "return", "probs", ".", "Unauthorized", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "// We use `0` as the account ID provided to `processRevocation` because this", "// is a self-authenticated request.", "return", "wfe", ".", "processRevocation", "(", "ctx", ",", "jwsBody", ",", "0", ",", "authorizedToRevoke", ",", "request", ",", "logEvent", ")", "\n", "}" ]
// revokeCertByJWK processes an outer JWS as a revocation request that is // authenticated by an embedded JWK. E.g. in the case where someone is // requesting a revocation by using the keypair associated with the certificate // to be revoked
[ "revokeCertByJWK", "processes", "an", "outer", "JWS", "as", "a", "revocation", "request", "that", "is", "authenticated", "by", "an", "embedded", "JWK", ".", "E", ".", "g", ".", "in", "the", "case", "where", "someone", "is", "requesting", "a", "revocation", "by", "using", "the", "keypair", "associated", "with", "the", "certificate", "to", "be", "revoked" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L754-L784
train
letsencrypt/boulder
wfe2/wfe.go
RevokeCertificate
func (wfe *WebFrontEndImpl) RevokeCertificate( ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) { // The ACME specification handles the verification of revocation requests // differently from other endpoints. For this reason we do *not* immediately // call `wfe.validPOSTForAccount` like all of the other endpoints. // For this endpoint we need to accept a JWS with an embedded JWK, or a JWS // with an embedded key ID, handling each case differently in terms of which // certificates are authorized to be revoked by the requester // Parse the JWS from the HTTP Request jws, prob := wfe.parseJWSRequest(request) if prob != nil { wfe.sendError(response, logEvent, prob, nil) return } // Figure out which type of authentication this JWS uses authType, prob := checkJWSAuthType(jws) if prob != nil { wfe.sendError(response, logEvent, prob, nil) return } // Handle the revocation request according to how it is authenticated, or if // the authentication type is unknown, error immediately if authType == embeddedKeyID { prob = wfe.revokeCertByKeyID(ctx, jws, request, logEvent) addRequesterHeader(response, logEvent.Requester) } else if authType == embeddedJWK { prob = wfe.revokeCertByJWK(ctx, jws, request, logEvent) } else { prob = probs.Malformed("Malformed JWS, no KeyID or embedded JWK") } if prob != nil { wfe.sendError(response, logEvent, prob, nil) return } response.WriteHeader(http.StatusOK) }
go
func (wfe *WebFrontEndImpl) RevokeCertificate( ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) { // The ACME specification handles the verification of revocation requests // differently from other endpoints. For this reason we do *not* immediately // call `wfe.validPOSTForAccount` like all of the other endpoints. // For this endpoint we need to accept a JWS with an embedded JWK, or a JWS // with an embedded key ID, handling each case differently in terms of which // certificates are authorized to be revoked by the requester // Parse the JWS from the HTTP Request jws, prob := wfe.parseJWSRequest(request) if prob != nil { wfe.sendError(response, logEvent, prob, nil) return } // Figure out which type of authentication this JWS uses authType, prob := checkJWSAuthType(jws) if prob != nil { wfe.sendError(response, logEvent, prob, nil) return } // Handle the revocation request according to how it is authenticated, or if // the authentication type is unknown, error immediately if authType == embeddedKeyID { prob = wfe.revokeCertByKeyID(ctx, jws, request, logEvent) addRequesterHeader(response, logEvent.Requester) } else if authType == embeddedJWK { prob = wfe.revokeCertByJWK(ctx, jws, request, logEvent) } else { prob = probs.Malformed("Malformed JWS, no KeyID or embedded JWK") } if prob != nil { wfe.sendError(response, logEvent, prob, nil) return } response.WriteHeader(http.StatusOK) }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "RevokeCertificate", "(", "ctx", "context", ".", "Context", ",", "logEvent", "*", "web", ".", "RequestEvent", ",", "response", "http", ".", "ResponseWriter", ",", "request", "*", "http", ".", "Request", ")", "{", "// The ACME specification handles the verification of revocation requests", "// differently from other endpoints. For this reason we do *not* immediately", "// call `wfe.validPOSTForAccount` like all of the other endpoints.", "// For this endpoint we need to accept a JWS with an embedded JWK, or a JWS", "// with an embedded key ID, handling each case differently in terms of which", "// certificates are authorized to be revoked by the requester", "// Parse the JWS from the HTTP Request", "jws", ",", "prob", ":=", "wfe", ".", "parseJWSRequest", "(", "request", ")", "\n", "if", "prob", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "prob", ",", "nil", ")", "\n", "return", "\n", "}", "\n\n", "// Figure out which type of authentication this JWS uses", "authType", ",", "prob", ":=", "checkJWSAuthType", "(", "jws", ")", "\n", "if", "prob", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "prob", ",", "nil", ")", "\n", "return", "\n", "}", "\n\n", "// Handle the revocation request according to how it is authenticated, or if", "// the authentication type is unknown, error immediately", "if", "authType", "==", "embeddedKeyID", "{", "prob", "=", "wfe", ".", "revokeCertByKeyID", "(", "ctx", ",", "jws", ",", "request", ",", "logEvent", ")", "\n", "addRequesterHeader", "(", "response", ",", "logEvent", ".", "Requester", ")", "\n", "}", "else", "if", "authType", "==", "embeddedJWK", "{", "prob", "=", "wfe", ".", "revokeCertByJWK", "(", "ctx", ",", "jws", ",", "request", ",", "logEvent", ")", "\n", "}", "else", "{", "prob", "=", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "prob", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "prob", ",", "nil", ")", "\n", "return", "\n", "}", "\n", "response", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "}" ]
// RevokeCertificate is used by clients to request the revocation of a cert. The // revocation request is handled uniquely based on the method of authentication // used.
[ "RevokeCertificate", "is", "used", "by", "clients", "to", "request", "the", "revocation", "of", "a", "cert", ".", "The", "revocation", "request", "is", "handled", "uniquely", "based", "on", "the", "method", "of", "authentication", "used", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L789-L831
train
letsencrypt/boulder
wfe2/wfe.go
prepChallengeForDisplay
func (wfe *WebFrontEndImpl) prepChallengeForDisplay(request *http.Request, authz core.Authorization, challenge *core.Challenge) { // Update the challenge URL to be relative to the HTTP request Host if authz.V2 { challenge.URL = web.RelativeEndpoint(request, fmt.Sprintf("%sv2/%s/%s", challengePath, authz.ID, challenge.StringID())) } else { challenge.URL = web.RelativeEndpoint(request, fmt.Sprintf("%s%s/%d", challengePath, authz.ID, challenge.ID)) } // Ensure the challenge URI and challenge ID aren't written by setting them to // values that the JSON omitempty tag considers empty challenge.URI = "" challenge.ID = 0 // ACMEv2 never sends the KeyAuthorization back in a challenge object. challenge.ProvidedKeyAuthorization = "" // Historically the Type field of a problem was always prefixed with a static // error namespace. To support the V2 API and migrating to the correct IETF // namespace we now prefix the Type with the correct namespace at runtime when // we write the problem JSON to the user. We skip this process if the // challenge error type has already been prefixed with the V1ErrorNS. if challenge.Error != nil && !strings.HasPrefix(string(challenge.Error.Type), probs.V1ErrorNS) { challenge.Error.Type = probs.V2ErrorNS + challenge.Error.Type } // If the authz has been marked invalid, consider all challenges on that authz // to be invalid as well. if authz.Status == core.StatusInvalid { challenge.Status = authz.Status } }
go
func (wfe *WebFrontEndImpl) prepChallengeForDisplay(request *http.Request, authz core.Authorization, challenge *core.Challenge) { // Update the challenge URL to be relative to the HTTP request Host if authz.V2 { challenge.URL = web.RelativeEndpoint(request, fmt.Sprintf("%sv2/%s/%s", challengePath, authz.ID, challenge.StringID())) } else { challenge.URL = web.RelativeEndpoint(request, fmt.Sprintf("%s%s/%d", challengePath, authz.ID, challenge.ID)) } // Ensure the challenge URI and challenge ID aren't written by setting them to // values that the JSON omitempty tag considers empty challenge.URI = "" challenge.ID = 0 // ACMEv2 never sends the KeyAuthorization back in a challenge object. challenge.ProvidedKeyAuthorization = "" // Historically the Type field of a problem was always prefixed with a static // error namespace. To support the V2 API and migrating to the correct IETF // namespace we now prefix the Type with the correct namespace at runtime when // we write the problem JSON to the user. We skip this process if the // challenge error type has already been prefixed with the V1ErrorNS. if challenge.Error != nil && !strings.HasPrefix(string(challenge.Error.Type), probs.V1ErrorNS) { challenge.Error.Type = probs.V2ErrorNS + challenge.Error.Type } // If the authz has been marked invalid, consider all challenges on that authz // to be invalid as well. if authz.Status == core.StatusInvalid { challenge.Status = authz.Status } }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "prepChallengeForDisplay", "(", "request", "*", "http", ".", "Request", ",", "authz", "core", ".", "Authorization", ",", "challenge", "*", "core", ".", "Challenge", ")", "{", "// Update the challenge URL to be relative to the HTTP request Host", "if", "authz", ".", "V2", "{", "challenge", ".", "URL", "=", "web", ".", "RelativeEndpoint", "(", "request", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "challengePath", ",", "authz", ".", "ID", ",", "challenge", ".", "StringID", "(", ")", ")", ")", "\n", "}", "else", "{", "challenge", ".", "URL", "=", "web", ".", "RelativeEndpoint", "(", "request", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "challengePath", ",", "authz", ".", "ID", ",", "challenge", ".", "ID", ")", ")", "\n", "}", "\n", "// Ensure the challenge URI and challenge ID aren't written by setting them to", "// values that the JSON omitempty tag considers empty", "challenge", ".", "URI", "=", "\"", "\"", "\n", "challenge", ".", "ID", "=", "0", "\n\n", "// ACMEv2 never sends the KeyAuthorization back in a challenge object.", "challenge", ".", "ProvidedKeyAuthorization", "=", "\"", "\"", "\n\n", "// Historically the Type field of a problem was always prefixed with a static", "// error namespace. To support the V2 API and migrating to the correct IETF", "// namespace we now prefix the Type with the correct namespace at runtime when", "// we write the problem JSON to the user. We skip this process if the", "// challenge error type has already been prefixed with the V1ErrorNS.", "if", "challenge", ".", "Error", "!=", "nil", "&&", "!", "strings", ".", "HasPrefix", "(", "string", "(", "challenge", ".", "Error", ".", "Type", ")", ",", "probs", ".", "V1ErrorNS", ")", "{", "challenge", ".", "Error", ".", "Type", "=", "probs", ".", "V2ErrorNS", "+", "challenge", ".", "Error", ".", "Type", "\n", "}", "\n\n", "// If the authz has been marked invalid, consider all challenges on that authz", "// to be invalid as well.", "if", "authz", ".", "Status", "==", "core", ".", "StatusInvalid", "{", "challenge", ".", "Status", "=", "authz", ".", "Status", "\n", "}", "\n", "}" ]
// prepChallengeForDisplay takes a core.Challenge and prepares it for display to // the client by filling in its URL field and clearing its ID and URI fields.
[ "prepChallengeForDisplay", "takes", "a", "core", ".", "Challenge", "and", "prepares", "it", "for", "display", "to", "the", "client", "by", "filling", "in", "its", "URL", "field", "and", "clearing", "its", "ID", "and", "URI", "fields", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L956-L985
train
letsencrypt/boulder
wfe2/wfe.go
Account
func (wfe *WebFrontEndImpl) Account( ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) { body, _, currAcct, 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 } // Requests to this handler should have a path that leads to a known // account idStr := request.URL.Path id, err := strconv.ParseInt(idStr, 10, 64) if err != nil { wfe.sendError(response, logEvent, probs.Malformed("Account ID must be an integer"), err) return } else if id <= 0 { msg := fmt.Sprintf("Account ID must be a positive non-zero integer, was %d", id) wfe.sendError(response, logEvent, probs.Malformed(msg), nil) return } else if id != currAcct.ID { wfe.sendError(response, logEvent, probs.Unauthorized("Request signing key did not match account key"), nil) return } // If the body was not empty, then this is an account update request. if string(body) != "" { currAcct, prob = wfe.updateAccount(ctx, body, currAcct) if prob != nil { wfe.sendError(response, logEvent, prob, nil) return } } if len(wfe.SubscriberAgreementURL) > 0 { response.Header().Add("Link", link(wfe.SubscriberAgreementURL, "terms-of-service")) } // We populate the account Agreement field when creating a new response to // track which terms-of-service URL was in effect when an account with // "termsOfServiceAgreed":"true" is created. That said, we don't want to send // this value back to a V2 client. The "Agreement" field of an // account/registration is a V1 notion so we strip it here in the WFE2 before // returning the account. currAcct.Agreement = "" err = wfe.writeJsonResponse(response, logEvent, http.StatusOK, currAcct) if err != nil { // ServerInternal because we just generated the account, it should be OK wfe.sendError(response, logEvent, probs.ServerInternal("Failed to marshal account"), err) return } }
go
func (wfe *WebFrontEndImpl) Account( ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) { body, _, currAcct, 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 } // Requests to this handler should have a path that leads to a known // account idStr := request.URL.Path id, err := strconv.ParseInt(idStr, 10, 64) if err != nil { wfe.sendError(response, logEvent, probs.Malformed("Account ID must be an integer"), err) return } else if id <= 0 { msg := fmt.Sprintf("Account ID must be a positive non-zero integer, was %d", id) wfe.sendError(response, logEvent, probs.Malformed(msg), nil) return } else if id != currAcct.ID { wfe.sendError(response, logEvent, probs.Unauthorized("Request signing key did not match account key"), nil) return } // If the body was not empty, then this is an account update request. if string(body) != "" { currAcct, prob = wfe.updateAccount(ctx, body, currAcct) if prob != nil { wfe.sendError(response, logEvent, prob, nil) return } } if len(wfe.SubscriberAgreementURL) > 0 { response.Header().Add("Link", link(wfe.SubscriberAgreementURL, "terms-of-service")) } // We populate the account Agreement field when creating a new response to // track which terms-of-service URL was in effect when an account with // "termsOfServiceAgreed":"true" is created. That said, we don't want to send // this value back to a V2 client. The "Agreement" field of an // account/registration is a V1 notion so we strip it here in the WFE2 before // returning the account. currAcct.Agreement = "" err = wfe.writeJsonResponse(response, logEvent, http.StatusOK, currAcct) if err != nil { // ServerInternal because we just generated the account, it should be OK wfe.sendError(response, logEvent, probs.ServerInternal("Failed to marshal account"), err) return } }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "Account", "(", "ctx", "context", ".", "Context", ",", "logEvent", "*", "web", ".", "RequestEvent", ",", "response", "http", ".", "ResponseWriter", ",", "request", "*", "http", ".", "Request", ")", "{", "body", ",", "_", ",", "currAcct", ",", "prob", ":=", "wfe", ".", "validPOSTForAccount", "(", "request", ",", "ctx", ",", "logEvent", ")", "\n", "addRequesterHeader", "(", "response", ",", "logEvent", ".", "Requester", ")", "\n", "if", "prob", "!=", "nil", "{", "// validPOSTForAccount handles its own setting of logEvent.Errors", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "prob", ",", "nil", ")", "\n", "return", "\n", "}", "\n\n", "// Requests to this handler should have a path that leads to a known", "// account", "idStr", ":=", "request", ".", "URL", ".", "Path", "\n", "id", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "idStr", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Malformed", "(", "\"", "\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "else", "if", "id", "<=", "0", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", "\n", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Malformed", "(", "msg", ")", ",", "nil", ")", "\n", "return", "\n", "}", "else", "if", "id", "!=", "currAcct", ".", "ID", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Unauthorized", "(", "\"", "\"", ")", ",", "nil", ")", "\n", "return", "\n", "}", "\n\n", "// If the body was not empty, then this is an account update request.", "if", "string", "(", "body", ")", "!=", "\"", "\"", "{", "currAcct", ",", "prob", "=", "wfe", ".", "updateAccount", "(", "ctx", ",", "body", ",", "currAcct", ")", "\n", "if", "prob", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "prob", ",", "nil", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "wfe", ".", "SubscriberAgreementURL", ")", ">", "0", "{", "response", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "link", "(", "wfe", ".", "SubscriberAgreementURL", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "// We populate the account Agreement field when creating a new response to", "// track which terms-of-service URL was in effect when an account with", "// \"termsOfServiceAgreed\":\"true\" is created. That said, we don't want to send", "// this value back to a V2 client. The \"Agreement\" field of an", "// account/registration is a V1 notion so we strip it here in the WFE2 before", "// returning the account.", "currAcct", ".", "Agreement", "=", "\"", "\"", "\n\n", "err", "=", "wfe", ".", "writeJsonResponse", "(", "response", ",", "logEvent", ",", "http", ".", "StatusOK", ",", "currAcct", ")", "\n", "if", "err", "!=", "nil", "{", "// ServerInternal because we just generated the account, it should be OK", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}" ]
// Account is used by a client to submit an update to their account.
[ "Account", "is", "used", "by", "a", "client", "to", "submit", "an", "update", "to", "their", "account", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L1132-L1190
train
letsencrypt/boulder
wfe2/wfe.go
Issuer
func (wfe *WebFrontEndImpl) Issuer(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) { // TODO Content negotiation response.Header().Set("Content-Type", "application/pkix-cert") response.WriteHeader(http.StatusOK) if _, err := response.Write(wfe.IssuerCert); err != nil { wfe.log.Warningf("Could not write response: %s", err) } }
go
func (wfe *WebFrontEndImpl) Issuer(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) { // TODO Content negotiation response.Header().Set("Content-Type", "application/pkix-cert") response.WriteHeader(http.StatusOK) if _, err := response.Write(wfe.IssuerCert); err != nil { wfe.log.Warningf("Could not write response: %s", err) } }
[ "func", "(", "wfe", "*", "WebFrontEndImpl", ")", "Issuer", "(", "ctx", "context", ".", "Context", ",", "logEvent", "*", "web", ".", "RequestEvent", ",", "response", "http", ".", "ResponseWriter", ",", "request", "*", "http", ".", "Request", ")", "{", "// TODO Content negotiation", "response", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "response", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "if", "_", ",", "err", ":=", "response", ".", "Write", "(", "wfe", ".", "IssuerCert", ")", ";", "err", "!=", "nil", "{", "wfe", ".", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// Issuer obtains the issuer certificate used by this instance of Boulder.
[ "Issuer", "obtains", "the", "issuer", "certificate", "used", "by", "this", "instance", "of", "Boulder", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/wfe2/wfe.go#L1498-L1505
train
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", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "response", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "detailsString", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "core", ".", "GetBuildID", "(", ")", ",", "core", ".", "GetBuildTime", "(", ")", ")", "\n", "if", "_", ",", "err", ":=", "fmt", ".", "Fprintln", "(", "response", ",", "detailsString", ")", ";", "err", "!=", "nil", "{", "wfe", ".", "log", ".", "Warningf", "(", "\"", "\"", ",", "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", ")", "{", "// Every OPTIONS request gets an Allow header with a list of supported methods.", "response", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "methodsStr", ")", "\n\n", "// CORS preflight requests get additional headers. See", "// http://www.w3.org/TR/cors/#resource-preflight-requests", "reqMethod", ":=", "request", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "reqMethod", "==", "\"", "\"", "{", "reqMethod", "=", "\"", "\"", "\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", "{", "// validPOSTForAccount handles its own setting of logEvent.Errors", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "prob", ",", "nil", ")", "\n", "return", "\n", "}", "\n\n", "// 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\"`", "\n", "NotBefore", ",", "NotAfter", "string", "\n", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "newOrderRequest", ")", "\n", "if", "err", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Malformed", "(", "\"", "\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "len", "(", "newOrderRequest", ".", "Identifiers", ")", "==", "0", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Malformed", "(", "\"", "\"", ")", ",", "nil", ")", "\n", "return", "\n", "}", "\n", "if", "newOrderRequest", ".", "NotBefore", "!=", "\"", "\"", "||", "newOrderRequest", ".", "NotAfter", "!=", "\"", "\"", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Malformed", "(", "\"", "\"", ")", ",", "nil", ")", "\n", "return", "\n", "}", "\n\n", "// 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", ")", ")", "\n", "for", "i", ",", "ident", ":=", "range", "newOrderRequest", ".", "Identifiers", "{", "if", "ident", ".", "Type", "!=", "core", ".", "IdentifierDNS", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Malformed", "(", "\"", "\"", ",", "ident", ".", "Type", ",", "ident", ".", "Value", ")", ",", "nil", ")", "\n", "return", "\n", "}", "\n", "names", "[", "i", "]", "=", "ident", ".", "Value", "\n", "}", "\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", ",", "\"", "\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "logEvent", ".", "Created", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "*", "order", ".", "Id", ")", "\n\n", "orderURL", ":=", "web", ".", "RelativeEndpoint", "(", "request", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "orderPath", ",", "acct", ".", "ID", ",", "*", "order", ".", "Id", ")", ")", "\n", "response", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "orderURL", ")", "\n\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", "(", "\"", "\"", ")", ",", "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", "// 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", "==", "\"", "\"", "{", "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\n", "// Path prefix is stripped, so this should be like \"<account ID>/<order ID>\"", "fields", ":=", "strings", ".", "SplitN", "(", "request", ".", "URL", ".", "Path", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "fields", ")", "!=", "2", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "NotFound", "(", "\"", "\"", ")", ",", "nil", ")", "\n", "return", "\n", "}", "\n", "acctID", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "fields", "[", "0", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Malformed", "(", "\"", "\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "orderID", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "fields", "[", "1", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Malformed", "(", "\"", "\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\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", "(", "\"", "\"", ",", "orderID", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "ServerInternal", "(", "\"", "\"", ",", "orderID", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "*", "order", ".", "RegistrationID", "!=", "acctID", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "NotFound", "(", "\"", "\"", ",", "acctID", ")", ",", "nil", ")", "\n", "return", "\n", "}", "\n\n", "// 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", "(", "\"", "\"", ",", "acctID", ")", ",", "nil", ")", "\n", "return", "\n", "}", "\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", "(", "\"", "\"", ")", ",", "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\n", "for", "_", ",", "r", ":=", "range", "m", ".", "destinations", "{", "// Get the email address for the reg ID", "emails", ",", "err", ":=", "emailsForReg", "(", "r", ".", "id", ",", "m", ".", "dbMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "email", ":=", "range", "emails", "{", "parsedEmail", ",", "err", ":=", "mail", ".", "ParseAddress", "(", "email", ")", "\n", "if", "err", "!=", "nil", "{", "m", ".", "log", ".", "Errf", "(", "\"", "\"", ",", "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\n\t\tFROM registrations\n\t\tWHERE contact != 'null' AND id = :id;`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "id", ",", "}", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "[", "]", "string", "{", "}", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\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", ",", "\"", "\"", ")", "{", "addresses", "=", "append", "(", "addresses", ",", "strings", ".", "TrimPrefix", "(", "entry", ",", "\"", "\"", ")", ")", "\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", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "record", "[", "0", "]", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "columnNames", "[", "]", "string", "\n", "for", "_", ",", "v", ":=", "range", "record", "[", "1", ":", "]", "{", "columnNames", "=", "append", "(", "columnNames", ",", "strings", ".", "TrimSpace", "(", "v", ")", ")", "\n", "}", "\n\n", "results", ":=", "[", "]", "recipient", "{", "}", "\n", "for", "{", "record", ",", "err", ":=", "reader", ".", "Read", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "if", "len", "(", "results", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "record", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "record", ")", "!=", "len", "(", "columnNames", ")", "+", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "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", "return", "pc", ".", "Password", ",", "nil", "\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", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "name", ":=", "range", "pc", ".", "Challenges", "{", "if", "!", "core", ".", "ValidChallenge", "(", "name", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "ts", ".", "Shards", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\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", "(", "\"", "\"", ")", "\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", "(", "\"", "\"", ",", "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", "// Since staticResolver.Next is called in a tight loop block forever", "// after returning the initial set of addresses", "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", "{", "// verifyPOST handles its own setting of logEvent.Errors", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "prob", ",", "nil", ")", "\n", "return", "\n", "}", "\n", "// 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", "(", "\"", "\"", ")", ",", "nil", ")", "\n", "return", "\n", "}", "\n\n", "var", "init", "core", ".", "Authorization", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "init", ")", ";", "err", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "Malformed", "(", "\"", "\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "init", ".", "Identifier", ".", "Type", "==", "core", ".", "IdentifierDNS", "{", "logEvent", ".", "DNSName", "=", "init", ".", "Identifier", ".", "Value", "\n", "}", "\n\n", "// Create new authz and return", "authz", ",", "err", ":=", "wfe", ".", "RA", ".", "NewAuthorization", "(", "ctx", ",", "init", ",", "currReg", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "web", ".", "ProblemDetailsForError", "(", "err", ",", "\"", "\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "logEvent", ".", "Created", "=", "authz", ".", "ID", "\n\n", "// Make a URL for this authz, then blow away the ID and RegID before serializing", "authzURL", ":=", "web", ".", "RelativeEndpoint", "(", "request", ",", "authzPath", "+", "string", "(", "authz", ".", "ID", ")", ")", "\n", "wfe", ".", "prepAuthorizationForDisplay", "(", "request", ",", "&", "authz", ")", "\n\n", "response", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "authzURL", ")", "\n", "response", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "link", "(", "web", ".", "RelativeEndpoint", "(", "request", ",", "newCertPath", ")", ",", "\"", "\"", ")", ")", "\n\n", "err", "=", "wfe", ".", "writeJsonResponse", "(", "response", ",", "logEvent", ",", "http", ".", "StatusCreated", ",", "authz", ")", "\n", "if", "err", "!=", "nil", "{", "// ServerInternal because we generated the authz, it should be OK", "wfe", ".", "sendError", "(", "response", ",", "logEvent", ",", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", ",", "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", "(", "\"", "\"", ")", "\n", "}", "\n\n", "rule", ":=", "publicsuffix", ".", "DefaultList", ".", "Find", "(", "name", ",", "&", "publicsuffix", ".", "FindOptions", "{", "IgnorePrivate", ":", "true", ",", "DefaultRule", ":", "nil", "}", ")", "\n", "if", "rule", "==", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "suffix", ":=", "rule", ".", "Decompose", "(", "name", ")", "[", "1", "]", "\n\n", "// 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", "\n", "}", "\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", ":", "// Internal server error messages may include sensitive data, so we do", "// not include it.", "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\n", "if", "regOverrideExists", "&&", "!", "keyOverrideExists", "{", "// If there is a regOverride and no keyOverride use the regOverride", "return", "regOverride", "\n", "}", "else", "if", "!", "regOverrideExists", "&&", "keyOverrideExists", "{", "// If there is a keyOverride and no regOverride use the keyOverride", "return", "keyOverride", "\n", "}", "else", "if", "regOverrideExists", "&&", "keyOverrideExists", "{", "// If there is both a regOverride and a keyOverride use whichever is larger.", "if", "regOverride", ">", "keyOverride", "{", "return", "regOverride", "\n", "}", "else", "{", "return", "keyOverride", "\n", "}", "\n", "}", "\n\n", "// Otherwise there was no regOverride and no keyOverride, use the base", "// Threshold", "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