repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
letsencrypt/boulder | metrics/mock_metrics/mock_scope.go | NewScope | func (m *MockScope) NewScope(arg0 ...string) metrics.Scope {
m.ctrl.T.Helper()
varargs := []interface{}{}
for _, a := range arg0 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "NewScope", varargs...)
ret0, _ := ret[0].(metrics.Scope)
return ret0
} | go | func (m *MockScope) NewScope(arg0 ...string) metrics.Scope {
m.ctrl.T.Helper()
varargs := []interface{}{}
for _, a := range arg0 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "NewScope", varargs...)
ret0, _ := ret[0].(metrics.Scope)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockScope",
")",
"NewScope",
"(",
"arg0",
"...",
"string",
")",
"metrics",
".",
"Scope",
"{",
"m",
".",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"varargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"arg0",
"{",
"varargs",
"=",
"append",
"(",
"varargs",
",",
"a",
")",
"\n",
"}",
"\n",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"NewScope\"",
",",
"varargs",
"...",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"metrics",
".",
"Scope",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // NewScope mocks base method | [
"NewScope",
"mocks",
"base",
"method"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/mock_metrics/mock_scope.go#L91-L100 | train |
letsencrypt/boulder | metrics/mock_metrics/mock_scope.go | TimingDuration | func (m *MockScope) TimingDuration(arg0 string, arg1 time.Duration) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "TimingDuration", arg0, arg1)
} | go | func (m *MockScope) TimingDuration(arg0 string, arg1 time.Duration) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "TimingDuration", arg0, arg1)
} | [
"func",
"(",
"m",
"*",
"MockScope",
")",
"TimingDuration",
"(",
"arg0",
"string",
",",
"arg1",
"time",
".",
"Duration",
")",
"{",
"m",
".",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"TimingDuration\"",
",",
"arg0",
",",
"arg1",
")",
"\n",
"}"
] | // TimingDuration mocks base method | [
"TimingDuration",
"mocks",
"base",
"method"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/mock_metrics/mock_scope.go#L133-L136 | train |
letsencrypt/boulder | sa/rate_limits.go | baseDomain | func baseDomain(name string) string {
eTLDPlusOne, err := publicsuffix.Domain(name)
if err != nil {
// publicsuffix.Domain will return an error if the input name is itself a
// public suffix. In that case we use the input name as the key for rate
// limiting. Since all of its subdomains will have separate keys for rate
// limiting (e.g. "foo.bar.publicsuffix.com" will have
// "bar.publicsuffix.com", this means that domains exactly equal to a
// public suffix get their own rate limit bucket. This is important
// because otherwise they might be perpetually unable to issue, assuming
// the rate of issuance from their subdomains was high enough.
return name
}
return eTLDPlusOne
} | go | func baseDomain(name string) string {
eTLDPlusOne, err := publicsuffix.Domain(name)
if err != nil {
// publicsuffix.Domain will return an error if the input name is itself a
// public suffix. In that case we use the input name as the key for rate
// limiting. Since all of its subdomains will have separate keys for rate
// limiting (e.g. "foo.bar.publicsuffix.com" will have
// "bar.publicsuffix.com", this means that domains exactly equal to a
// public suffix get their own rate limit bucket. This is important
// because otherwise they might be perpetually unable to issue, assuming
// the rate of issuance from their subdomains was high enough.
return name
}
return eTLDPlusOne
} | [
"func",
"baseDomain",
"(",
"name",
"string",
")",
"string",
"{",
"eTLDPlusOne",
",",
"err",
":=",
"publicsuffix",
".",
"Domain",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"name",
"\n",
"}",
"\n",
"return",
"eTLDPlusOne",
"\n",
"}"
] | // baseDomain returns the eTLD+1 of a domain name for the purpose of rate
// limiting. For a domain name that is itself an eTLD, it returns its input. | [
"baseDomain",
"returns",
"the",
"eTLD",
"+",
"1",
"of",
"a",
"domain",
"name",
"for",
"the",
"purpose",
"of",
"rate",
"limiting",
".",
"For",
"a",
"domain",
"name",
"that",
"is",
"itself",
"an",
"eTLD",
"it",
"returns",
"its",
"input",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/rate_limits.go#L15-L29 | train |
letsencrypt/boulder | sa/rate_limits.go | addCertificatesPerName | func (ssa *SQLStorageAuthority) addCertificatesPerName(
ctx context.Context,
db dbSelectExecer,
names []string,
timeToTheHour time.Time,
) error {
if !features.Enabled(features.FasterRateLimit) {
return nil
}
// De-duplicate the base domains.
baseDomainsMap := make(map[string]bool)
var qmarks []string
var values []interface{}
for _, name := range names {
base := baseDomain(name)
if !baseDomainsMap[base] {
baseDomainsMap[base] = true
values = append(values, base, timeToTheHour, 1)
qmarks = append(qmarks, "(?, ?, ?)")
}
}
_, err := db.Exec(`INSERT INTO certificatesPerName (eTLDPlusOne, time, count) VALUES `+
strings.Join(qmarks, ", ")+` ON DUPLICATE KEY UPDATE count=count+1;`,
values...)
if err != nil {
return err
}
return nil
} | go | func (ssa *SQLStorageAuthority) addCertificatesPerName(
ctx context.Context,
db dbSelectExecer,
names []string,
timeToTheHour time.Time,
) error {
if !features.Enabled(features.FasterRateLimit) {
return nil
}
// De-duplicate the base domains.
baseDomainsMap := make(map[string]bool)
var qmarks []string
var values []interface{}
for _, name := range names {
base := baseDomain(name)
if !baseDomainsMap[base] {
baseDomainsMap[base] = true
values = append(values, base, timeToTheHour, 1)
qmarks = append(qmarks, "(?, ?, ?)")
}
}
_, err := db.Exec(`INSERT INTO certificatesPerName (eTLDPlusOne, time, count) VALUES `+
strings.Join(qmarks, ", ")+` ON DUPLICATE KEY UPDATE count=count+1;`,
values...)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"ssa",
"*",
"SQLStorageAuthority",
")",
"addCertificatesPerName",
"(",
"ctx",
"context",
".",
"Context",
",",
"db",
"dbSelectExecer",
",",
"names",
"[",
"]",
"string",
",",
"timeToTheHour",
"time",
".",
"Time",
",",
")",
"error",
"{",
"if",
"!",
"features",
".",
"Enabled",
"(",
"features",
".",
"FasterRateLimit",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"baseDomainsMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"var",
"qmarks",
"[",
"]",
"string",
"\n",
"var",
"values",
"[",
"]",
"interface",
"{",
"}",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"base",
":=",
"baseDomain",
"(",
"name",
")",
"\n",
"if",
"!",
"baseDomainsMap",
"[",
"base",
"]",
"{",
"baseDomainsMap",
"[",
"base",
"]",
"=",
"true",
"\n",
"values",
"=",
"append",
"(",
"values",
",",
"base",
",",
"timeToTheHour",
",",
"1",
")",
"\n",
"qmarks",
"=",
"append",
"(",
"qmarks",
",",
"\"(?, ?, ?)\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`INSERT INTO certificatesPerName (eTLDPlusOne, time, count) VALUES `",
"+",
"strings",
".",
"Join",
"(",
"qmarks",
",",
"\", \"",
")",
"+",
"` ON DUPLICATE KEY UPDATE count=count+1;`",
",",
"values",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // addCertificatesPerName adds 1 to the rate limit count for the provided domains,
// in a specific time bucket. It must be executed in a transaction, and the
// input timeToTheHour must be a time rounded to an hour. | [
"addCertificatesPerName",
"adds",
"1",
"to",
"the",
"rate",
"limit",
"count",
"for",
"the",
"provided",
"domains",
"in",
"a",
"specific",
"time",
"bucket",
".",
"It",
"must",
"be",
"executed",
"in",
"a",
"transaction",
"and",
"the",
"input",
"timeToTheHour",
"must",
"be",
"a",
"time",
"rounded",
"to",
"an",
"hour",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/rate_limits.go#L34-L64 | train |
letsencrypt/boulder | cmd/gen-ca/main.go | getKey | func getKey(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, label string, idStr string) (*x509Signer, error) {
id, err := hex.DecodeString(idStr)
if err != nil {
return nil, err
}
// Retrieve the private key handle that will later be used for the certificate
// signing operation
privateHandle, err := findObject(ctx, session, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),
pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
pkcs11.NewAttribute(pkcs11.CKA_ID, id),
})
if err != nil {
return nil, fmt.Errorf("failed to retrieve private key handle: %s", err)
}
attrs, err := ctx.GetAttributeValue(session, privateHandle, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, nil)},
)
if err != nil {
return nil, fmt.Errorf("failed to retrieve key type: %s", err)
}
if len(attrs) == 0 {
return nil, errors.New("failed to retrieve key attributes")
}
// Retrieve the public key handle with the same CKA_ID as the private key
// and construct a {rsa,ecdsa}.PublicKey for use in x509.CreateCertificate
pubHandle, err := findObject(ctx, session, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),
pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
pkcs11.NewAttribute(pkcs11.CKA_ID, id),
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, attrs[0].Value),
})
if err != nil {
return nil, fmt.Errorf("failed to retrieve public key handle: %s", err)
}
var pub crypto.PublicKey
var keyType pkcs11helpers.KeyType
switch {
// 0x00000000, CKK_RSA
case bytes.Compare(attrs[0].Value, []byte{0, 0, 0, 0, 0, 0, 0, 0}) == 0:
keyType = pkcs11helpers.RSAKey
pub, err = pkcs11helpers.GetRSAPublicKey(ctx, session, pubHandle)
if err != nil {
return nil, fmt.Errorf("failed to retrieve public key: %s", err)
}
// 0x00000003, CKK_ECDSA
case bytes.Compare(attrs[0].Value, []byte{3, 0, 0, 0, 0, 0, 0, 0}) == 0:
keyType = pkcs11helpers.ECDSAKey
pub, err = pkcs11helpers.GetECDSAPublicKey(ctx, session, pubHandle)
if err != nil {
return nil, fmt.Errorf("failed to retrieve public key: %s", err)
}
default:
return nil, errors.New("unsupported key type")
}
return &x509Signer{
ctx: ctx,
session: session,
objectHandle: privateHandle,
keyType: keyType,
pub: pub,
}, nil
} | go | func getKey(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, label string, idStr string) (*x509Signer, error) {
id, err := hex.DecodeString(idStr)
if err != nil {
return nil, err
}
// Retrieve the private key handle that will later be used for the certificate
// signing operation
privateHandle, err := findObject(ctx, session, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),
pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
pkcs11.NewAttribute(pkcs11.CKA_ID, id),
})
if err != nil {
return nil, fmt.Errorf("failed to retrieve private key handle: %s", err)
}
attrs, err := ctx.GetAttributeValue(session, privateHandle, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, nil)},
)
if err != nil {
return nil, fmt.Errorf("failed to retrieve key type: %s", err)
}
if len(attrs) == 0 {
return nil, errors.New("failed to retrieve key attributes")
}
// Retrieve the public key handle with the same CKA_ID as the private key
// and construct a {rsa,ecdsa}.PublicKey for use in x509.CreateCertificate
pubHandle, err := findObject(ctx, session, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),
pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
pkcs11.NewAttribute(pkcs11.CKA_ID, id),
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, attrs[0].Value),
})
if err != nil {
return nil, fmt.Errorf("failed to retrieve public key handle: %s", err)
}
var pub crypto.PublicKey
var keyType pkcs11helpers.KeyType
switch {
// 0x00000000, CKK_RSA
case bytes.Compare(attrs[0].Value, []byte{0, 0, 0, 0, 0, 0, 0, 0}) == 0:
keyType = pkcs11helpers.RSAKey
pub, err = pkcs11helpers.GetRSAPublicKey(ctx, session, pubHandle)
if err != nil {
return nil, fmt.Errorf("failed to retrieve public key: %s", err)
}
// 0x00000003, CKK_ECDSA
case bytes.Compare(attrs[0].Value, []byte{3, 0, 0, 0, 0, 0, 0, 0}) == 0:
keyType = pkcs11helpers.ECDSAKey
pub, err = pkcs11helpers.GetECDSAPublicKey(ctx, session, pubHandle)
if err != nil {
return nil, fmt.Errorf("failed to retrieve public key: %s", err)
}
default:
return nil, errors.New("unsupported key type")
}
return &x509Signer{
ctx: ctx,
session: session,
objectHandle: privateHandle,
keyType: keyType,
pub: pub,
}, nil
} | [
"func",
"getKey",
"(",
"ctx",
"pkcs11helpers",
".",
"PKCtx",
",",
"session",
"pkcs11",
".",
"SessionHandle",
",",
"label",
"string",
",",
"idStr",
"string",
")",
"(",
"*",
"x509Signer",
",",
"error",
")",
"{",
"id",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"idStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"privateHandle",
",",
"err",
":=",
"findObject",
"(",
"ctx",
",",
"session",
",",
"[",
"]",
"*",
"pkcs11",
".",
"Attribute",
"{",
"pkcs11",
".",
"NewAttribute",
"(",
"pkcs11",
".",
"CKA_CLASS",
",",
"pkcs11",
".",
"CKO_PRIVATE_KEY",
")",
",",
"pkcs11",
".",
"NewAttribute",
"(",
"pkcs11",
".",
"CKA_LABEL",
",",
"label",
")",
",",
"pkcs11",
".",
"NewAttribute",
"(",
"pkcs11",
".",
"CKA_ID",
",",
"id",
")",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to retrieve private key handle: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"attrs",
",",
"err",
":=",
"ctx",
".",
"GetAttributeValue",
"(",
"session",
",",
"privateHandle",
",",
"[",
"]",
"*",
"pkcs11",
".",
"Attribute",
"{",
"pkcs11",
".",
"NewAttribute",
"(",
"pkcs11",
".",
"CKA_KEY_TYPE",
",",
"nil",
")",
"}",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to retrieve key type: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"attrs",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"failed to retrieve key attributes\"",
")",
"\n",
"}",
"\n",
"pubHandle",
",",
"err",
":=",
"findObject",
"(",
"ctx",
",",
"session",
",",
"[",
"]",
"*",
"pkcs11",
".",
"Attribute",
"{",
"pkcs11",
".",
"NewAttribute",
"(",
"pkcs11",
".",
"CKA_CLASS",
",",
"pkcs11",
".",
"CKO_PUBLIC_KEY",
")",
",",
"pkcs11",
".",
"NewAttribute",
"(",
"pkcs11",
".",
"CKA_LABEL",
",",
"label",
")",
",",
"pkcs11",
".",
"NewAttribute",
"(",
"pkcs11",
".",
"CKA_ID",
",",
"id",
")",
",",
"pkcs11",
".",
"NewAttribute",
"(",
"pkcs11",
".",
"CKA_KEY_TYPE",
",",
"attrs",
"[",
"0",
"]",
".",
"Value",
")",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to retrieve public key handle: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"var",
"pub",
"crypto",
".",
"PublicKey",
"\n",
"var",
"keyType",
"pkcs11helpers",
".",
"KeyType",
"\n",
"switch",
"{",
"case",
"bytes",
".",
"Compare",
"(",
"attrs",
"[",
"0",
"]",
".",
"Value",
",",
"[",
"]",
"byte",
"{",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"}",
")",
"==",
"0",
":",
"keyType",
"=",
"pkcs11helpers",
".",
"RSAKey",
"\n",
"pub",
",",
"err",
"=",
"pkcs11helpers",
".",
"GetRSAPublicKey",
"(",
"ctx",
",",
"session",
",",
"pubHandle",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to retrieve public key: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"case",
"bytes",
".",
"Compare",
"(",
"attrs",
"[",
"0",
"]",
".",
"Value",
",",
"[",
"]",
"byte",
"{",
"3",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"}",
")",
"==",
"0",
":",
"keyType",
"=",
"pkcs11helpers",
".",
"ECDSAKey",
"\n",
"pub",
",",
"err",
"=",
"pkcs11helpers",
".",
"GetECDSAPublicKey",
"(",
"ctx",
",",
"session",
",",
"pubHandle",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to retrieve public key: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"unsupported key type\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"x509Signer",
"{",
"ctx",
":",
"ctx",
",",
"session",
":",
"session",
",",
"objectHandle",
":",
"privateHandle",
",",
"keyType",
":",
"keyType",
",",
"pub",
":",
"pub",
",",
"}",
",",
"nil",
"\n",
"}"
] | // getKey constructs a x509Signer for the private key object associated with the
// given label and ID | [
"getKey",
"constructs",
"a",
"x509Signer",
"for",
"the",
"private",
"key",
"object",
"associated",
"with",
"the",
"given",
"label",
"and",
"ID"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/gen-ca/main.go#L96-L161 | train |
letsencrypt/boulder | cmd/gen-ca/main.go | makeTemplate | func makeTemplate(ctx pkcs11helpers.PKCtx, profile *CertProfile, pubKey []byte, session pkcs11.SessionHandle) (*x509.Certificate, error) {
dateLayout := "2006-01-02 15:04:05"
notBefore, err := time.Parse(dateLayout, profile.NotBefore)
if err != nil {
return nil, err
}
notAfter, err := time.Parse(dateLayout, profile.NotAfter)
if err != nil {
return nil, err
}
var ocspServer []string
if profile.OCSPURL != "" {
ocspServer = []string{profile.OCSPURL}
}
var crlDistributionPoints []string
if profile.CRLURL != "" {
crlDistributionPoints = []string{profile.CRLURL}
}
var issuingCertificateURL []string
if profile.IssuerURL != "" {
issuingCertificateURL = []string{profile.IssuerURL}
}
var policyOIDs []asn1.ObjectIdentifier
for _, oidStr := range profile.PolicyOIDs {
oid, err := parseOID(oidStr)
if err != nil {
return nil, err
}
policyOIDs = append(policyOIDs, oid)
}
sigAlg, ok := AllowedSigAlgs[profile.SignatureAlgorithm]
if !ok {
return nil, fmt.Errorf("unsupported signature algorithm %q", profile.SignatureAlgorithm)
}
subjectKeyID := sha256.Sum256(pubKey)
serial, err := ctx.GenerateRandom(session, 16)
if err != nil {
return nil, fmt.Errorf("failed to generate serial number: %s", err)
}
cert := &x509.Certificate{
SignatureAlgorithm: sigAlg,
SerialNumber: big.NewInt(0).SetBytes(serial),
BasicConstraintsValid: true,
IsCA: true,
Subject: pkix.Name{
CommonName: profile.CommonName,
Organization: []string{profile.Organization},
Country: []string{profile.Country},
},
NotBefore: notBefore,
NotAfter: notAfter,
OCSPServer: ocspServer,
CRLDistributionPoints: crlDistributionPoints,
IssuingCertificateURL: issuingCertificateURL,
PolicyIdentifiers: policyOIDs,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
SubjectKeyId: subjectKeyID[:],
}
return cert, nil
} | go | func makeTemplate(ctx pkcs11helpers.PKCtx, profile *CertProfile, pubKey []byte, session pkcs11.SessionHandle) (*x509.Certificate, error) {
dateLayout := "2006-01-02 15:04:05"
notBefore, err := time.Parse(dateLayout, profile.NotBefore)
if err != nil {
return nil, err
}
notAfter, err := time.Parse(dateLayout, profile.NotAfter)
if err != nil {
return nil, err
}
var ocspServer []string
if profile.OCSPURL != "" {
ocspServer = []string{profile.OCSPURL}
}
var crlDistributionPoints []string
if profile.CRLURL != "" {
crlDistributionPoints = []string{profile.CRLURL}
}
var issuingCertificateURL []string
if profile.IssuerURL != "" {
issuingCertificateURL = []string{profile.IssuerURL}
}
var policyOIDs []asn1.ObjectIdentifier
for _, oidStr := range profile.PolicyOIDs {
oid, err := parseOID(oidStr)
if err != nil {
return nil, err
}
policyOIDs = append(policyOIDs, oid)
}
sigAlg, ok := AllowedSigAlgs[profile.SignatureAlgorithm]
if !ok {
return nil, fmt.Errorf("unsupported signature algorithm %q", profile.SignatureAlgorithm)
}
subjectKeyID := sha256.Sum256(pubKey)
serial, err := ctx.GenerateRandom(session, 16)
if err != nil {
return nil, fmt.Errorf("failed to generate serial number: %s", err)
}
cert := &x509.Certificate{
SignatureAlgorithm: sigAlg,
SerialNumber: big.NewInt(0).SetBytes(serial),
BasicConstraintsValid: true,
IsCA: true,
Subject: pkix.Name{
CommonName: profile.CommonName,
Organization: []string{profile.Organization},
Country: []string{profile.Country},
},
NotBefore: notBefore,
NotAfter: notAfter,
OCSPServer: ocspServer,
CRLDistributionPoints: crlDistributionPoints,
IssuingCertificateURL: issuingCertificateURL,
PolicyIdentifiers: policyOIDs,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
SubjectKeyId: subjectKeyID[:],
}
return cert, nil
} | [
"func",
"makeTemplate",
"(",
"ctx",
"pkcs11helpers",
".",
"PKCtx",
",",
"profile",
"*",
"CertProfile",
",",
"pubKey",
"[",
"]",
"byte",
",",
"session",
"pkcs11",
".",
"SessionHandle",
")",
"(",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"dateLayout",
":=",
"\"2006-01-02 15:04:05\"",
"\n",
"notBefore",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"dateLayout",
",",
"profile",
".",
"NotBefore",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"notAfter",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"dateLayout",
",",
"profile",
".",
"NotAfter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"ocspServer",
"[",
"]",
"string",
"\n",
"if",
"profile",
".",
"OCSPURL",
"!=",
"\"\"",
"{",
"ocspServer",
"=",
"[",
"]",
"string",
"{",
"profile",
".",
"OCSPURL",
"}",
"\n",
"}",
"\n",
"var",
"crlDistributionPoints",
"[",
"]",
"string",
"\n",
"if",
"profile",
".",
"CRLURL",
"!=",
"\"\"",
"{",
"crlDistributionPoints",
"=",
"[",
"]",
"string",
"{",
"profile",
".",
"CRLURL",
"}",
"\n",
"}",
"\n",
"var",
"issuingCertificateURL",
"[",
"]",
"string",
"\n",
"if",
"profile",
".",
"IssuerURL",
"!=",
"\"\"",
"{",
"issuingCertificateURL",
"=",
"[",
"]",
"string",
"{",
"profile",
".",
"IssuerURL",
"}",
"\n",
"}",
"\n",
"var",
"policyOIDs",
"[",
"]",
"asn1",
".",
"ObjectIdentifier",
"\n",
"for",
"_",
",",
"oidStr",
":=",
"range",
"profile",
".",
"PolicyOIDs",
"{",
"oid",
",",
"err",
":=",
"parseOID",
"(",
"oidStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"policyOIDs",
"=",
"append",
"(",
"policyOIDs",
",",
"oid",
")",
"\n",
"}",
"\n",
"sigAlg",
",",
"ok",
":=",
"AllowedSigAlgs",
"[",
"profile",
".",
"SignatureAlgorithm",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"unsupported signature algorithm %q\"",
",",
"profile",
".",
"SignatureAlgorithm",
")",
"\n",
"}",
"\n",
"subjectKeyID",
":=",
"sha256",
".",
"Sum256",
"(",
"pubKey",
")",
"\n",
"serial",
",",
"err",
":=",
"ctx",
".",
"GenerateRandom",
"(",
"session",
",",
"16",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to generate serial number: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cert",
":=",
"&",
"x509",
".",
"Certificate",
"{",
"SignatureAlgorithm",
":",
"sigAlg",
",",
"SerialNumber",
":",
"big",
".",
"NewInt",
"(",
"0",
")",
".",
"SetBytes",
"(",
"serial",
")",
",",
"BasicConstraintsValid",
":",
"true",
",",
"IsCA",
":",
"true",
",",
"Subject",
":",
"pkix",
".",
"Name",
"{",
"CommonName",
":",
"profile",
".",
"CommonName",
",",
"Organization",
":",
"[",
"]",
"string",
"{",
"profile",
".",
"Organization",
"}",
",",
"Country",
":",
"[",
"]",
"string",
"{",
"profile",
".",
"Country",
"}",
",",
"}",
",",
"NotBefore",
":",
"notBefore",
",",
"NotAfter",
":",
"notAfter",
",",
"OCSPServer",
":",
"ocspServer",
",",
"CRLDistributionPoints",
":",
"crlDistributionPoints",
",",
"IssuingCertificateURL",
":",
"issuingCertificateURL",
",",
"PolicyIdentifiers",
":",
"policyOIDs",
",",
"KeyUsage",
":",
"x509",
".",
"KeyUsageCertSign",
"|",
"x509",
".",
"KeyUsageCRLSign",
",",
"SubjectKeyId",
":",
"subjectKeyID",
"[",
":",
"]",
",",
"}",
"\n",
"return",
"cert",
",",
"nil",
"\n",
"}"
] | // makeTemplate generates the certificate template for use in x509.CreateCertificate | [
"makeTemplate",
"generates",
"the",
"certificate",
"template",
"for",
"use",
"in",
"x509",
".",
"CreateCertificate"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/gen-ca/main.go#L257-L323 | train |
letsencrypt/boulder | cmd/ocsp-updater/main.go | generateRevokedResponse | func (updater *OCSPUpdater) generateRevokedResponse(ctx context.Context, status core.CertificateStatus) (*core.CertificateStatus, []string, error) {
cert, err := updater.sac.GetCertificate(ctx, status.Serial)
if err != nil {
return nil, nil, err
}
signRequest := core.OCSPSigningRequest{
CertDER: cert.DER,
Status: string(core.OCSPStatusRevoked),
Reason: status.RevokedReason,
RevokedAt: status.RevokedDate,
}
ocspResponse, err := updater.cac.GenerateOCSP(ctx, signRequest)
if err != nil {
return nil, nil, err
}
now := updater.clk.Now()
status.OCSPLastUpdated = now
status.OCSPResponse = ocspResponse
// If cache client is populated generate purge URLs
var purgeURLs []string
if updater.ccu != nil || updater.purgerService != nil {
purgeURLs, err = akamai.GeneratePurgeURLs(cert.DER, updater.issuer)
if err != nil {
return nil, nil, err
}
}
return &status, purgeURLs, nil
} | go | func (updater *OCSPUpdater) generateRevokedResponse(ctx context.Context, status core.CertificateStatus) (*core.CertificateStatus, []string, error) {
cert, err := updater.sac.GetCertificate(ctx, status.Serial)
if err != nil {
return nil, nil, err
}
signRequest := core.OCSPSigningRequest{
CertDER: cert.DER,
Status: string(core.OCSPStatusRevoked),
Reason: status.RevokedReason,
RevokedAt: status.RevokedDate,
}
ocspResponse, err := updater.cac.GenerateOCSP(ctx, signRequest)
if err != nil {
return nil, nil, err
}
now := updater.clk.Now()
status.OCSPLastUpdated = now
status.OCSPResponse = ocspResponse
// If cache client is populated generate purge URLs
var purgeURLs []string
if updater.ccu != nil || updater.purgerService != nil {
purgeURLs, err = akamai.GeneratePurgeURLs(cert.DER, updater.issuer)
if err != nil {
return nil, nil, err
}
}
return &status, purgeURLs, nil
} | [
"func",
"(",
"updater",
"*",
"OCSPUpdater",
")",
"generateRevokedResponse",
"(",
"ctx",
"context",
".",
"Context",
",",
"status",
"core",
".",
"CertificateStatus",
")",
"(",
"*",
"core",
".",
"CertificateStatus",
",",
"[",
"]",
"string",
",",
"error",
")",
"{",
"cert",
",",
"err",
":=",
"updater",
".",
"sac",
".",
"GetCertificate",
"(",
"ctx",
",",
"status",
".",
"Serial",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"signRequest",
":=",
"core",
".",
"OCSPSigningRequest",
"{",
"CertDER",
":",
"cert",
".",
"DER",
",",
"Status",
":",
"string",
"(",
"core",
".",
"OCSPStatusRevoked",
")",
",",
"Reason",
":",
"status",
".",
"RevokedReason",
",",
"RevokedAt",
":",
"status",
".",
"RevokedDate",
",",
"}",
"\n",
"ocspResponse",
",",
"err",
":=",
"updater",
".",
"cac",
".",
"GenerateOCSP",
"(",
"ctx",
",",
"signRequest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"now",
":=",
"updater",
".",
"clk",
".",
"Now",
"(",
")",
"\n",
"status",
".",
"OCSPLastUpdated",
"=",
"now",
"\n",
"status",
".",
"OCSPResponse",
"=",
"ocspResponse",
"\n",
"var",
"purgeURLs",
"[",
"]",
"string",
"\n",
"if",
"updater",
".",
"ccu",
"!=",
"nil",
"||",
"updater",
".",
"purgerService",
"!=",
"nil",
"{",
"purgeURLs",
",",
"err",
"=",
"akamai",
".",
"GeneratePurgeURLs",
"(",
"cert",
".",
"DER",
",",
"updater",
".",
"issuer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"status",
",",
"purgeURLs",
",",
"nil",
"\n",
"}"
] | // generateRevokedResponse takes a core.CertificateStatus and updates it with a revoked OCSP response
// for the certificate it represents. generateRevokedResponse then returns the updated status and a
// list of OCSP request URLs that should be purged or an error. | [
"generateRevokedResponse",
"takes",
"a",
"core",
".",
"CertificateStatus",
"and",
"updates",
"it",
"with",
"a",
"revoked",
"OCSP",
"response",
"for",
"the",
"certificate",
"it",
"represents",
".",
"generateRevokedResponse",
"then",
"returns",
"the",
"updated",
"status",
"and",
"a",
"list",
"of",
"OCSP",
"request",
"URLs",
"that",
"should",
"be",
"purged",
"or",
"an",
"error",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/ocsp-updater/main.go#L235-L267 | train |
letsencrypt/boulder | cmd/ocsp-updater/main.go | markExpired | func (updater *OCSPUpdater) markExpired(status core.CertificateStatus) error {
_, err := updater.dbMap.Exec(
`UPDATE certificateStatus
SET isExpired = TRUE
WHERE serial = ?`,
status.Serial,
)
return err
} | go | func (updater *OCSPUpdater) markExpired(status core.CertificateStatus) error {
_, err := updater.dbMap.Exec(
`UPDATE certificateStatus
SET isExpired = TRUE
WHERE serial = ?`,
status.Serial,
)
return err
} | [
"func",
"(",
"updater",
"*",
"OCSPUpdater",
")",
"markExpired",
"(",
"status",
"core",
".",
"CertificateStatus",
")",
"error",
"{",
"_",
",",
"err",
":=",
"updater",
".",
"dbMap",
".",
"Exec",
"(",
"`UPDATE certificateStatus \t\tSET isExpired = TRUE \t\tWHERE serial = ?`",
",",
"status",
".",
"Serial",
",",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // markExpired updates a given CertificateStatus to have `isExpired` set. | [
"markExpired",
"updates",
"a",
"given",
"CertificateStatus",
"to",
"have",
"isExpired",
"set",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/ocsp-updater/main.go#L288-L296 | train |
letsencrypt/boulder | sa/metrics.go | InitDBMetrics | func InitDBMetrics(dbMap *gorp.DbMap, scope metrics.Scope) {
// Create a dbMetrics instance and register prometheus metrics
dbm := newDbMetrics(dbMap, scope)
// Start the metric reporting goroutine to update the metrics periodically.
go dbm.reportDBMetrics()
} | go | func InitDBMetrics(dbMap *gorp.DbMap, scope metrics.Scope) {
// Create a dbMetrics instance and register prometheus metrics
dbm := newDbMetrics(dbMap, scope)
// Start the metric reporting goroutine to update the metrics periodically.
go dbm.reportDBMetrics()
} | [
"func",
"InitDBMetrics",
"(",
"dbMap",
"*",
"gorp",
".",
"DbMap",
",",
"scope",
"metrics",
".",
"Scope",
")",
"{",
"dbm",
":=",
"newDbMetrics",
"(",
"dbMap",
",",
"scope",
")",
"\n",
"go",
"dbm",
".",
"reportDBMetrics",
"(",
")",
"\n",
"}"
] | // InitDBMetrics will register prometheus stats for the provided dbMap under the
// given metrics.Scope. Every 1 second in a separate go routine the prometheus
// stats will be updated based on the gorp dbMap's inner sql.DBMap's DBStats
// structure values. | [
"InitDBMetrics",
"will",
"register",
"prometheus",
"stats",
"for",
"the",
"provided",
"dbMap",
"under",
"the",
"given",
"metrics",
".",
"Scope",
".",
"Every",
"1",
"second",
"in",
"a",
"separate",
"go",
"routine",
"the",
"prometheus",
"stats",
"will",
"be",
"updated",
"based",
"on",
"the",
"gorp",
"dbMap",
"s",
"inner",
"sql",
".",
"DBMap",
"s",
"DBStats",
"structure",
"values",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/metrics.go#L30-L36 | train |
letsencrypt/boulder | sa/metrics.go | newDbMetrics | func newDbMetrics(dbMap *gorp.DbMap, scope metrics.Scope) *dbMetrics {
maxOpenConns := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_max_open_connections",
Help: "Maximum number of DB connections allowed.",
})
scope.MustRegister(maxOpenConns)
openConns := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_open_connections",
Help: "Number of established DB connections (in-use and idle).",
})
scope.MustRegister(openConns)
inUse := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_inuse",
Help: "Number of DB connections currently in use.",
})
scope.MustRegister(inUse)
idle := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_idle",
Help: "Number of idle DB connections.",
})
scope.MustRegister(idle)
waitCount := prometheus.NewCounter(prometheus.CounterOpts{
Name: "db_wait_count",
Help: "Total number of DB connections waited for.",
})
scope.MustRegister(waitCount)
waitDuration := prometheus.NewCounter(prometheus.CounterOpts{
Name: "db_wait_duration_seconds",
Help: "The total time blocked waiting for a new connection.",
})
scope.MustRegister(waitDuration)
maxIdleClosed := prometheus.NewCounter(prometheus.CounterOpts{
Name: "db_max_idle_closed",
Help: "Total number of connections closed due to SetMaxIdleConns.",
})
scope.MustRegister(maxIdleClosed)
maxLifetimeClosed := prometheus.NewCounter(prometheus.CounterOpts{
Name: "db_max_lifetime_closed",
Help: "Total number of connections closed due to SetConnMaxLifetime.",
})
scope.MustRegister(maxLifetimeClosed)
// Construct a dbMetrics instance with all of the registered metrics and the
// gorp DBMap
return &dbMetrics{
dbMap: dbMap,
maxOpenConnections: maxOpenConns,
openConnections: openConns,
inUse: inUse,
idle: idle,
waitCount: waitCount,
waitDuration: waitDuration,
maxIdleClosed: maxIdleClosed,
maxLifetimeClosed: maxLifetimeClosed,
}
} | go | func newDbMetrics(dbMap *gorp.DbMap, scope metrics.Scope) *dbMetrics {
maxOpenConns := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_max_open_connections",
Help: "Maximum number of DB connections allowed.",
})
scope.MustRegister(maxOpenConns)
openConns := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_open_connections",
Help: "Number of established DB connections (in-use and idle).",
})
scope.MustRegister(openConns)
inUse := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_inuse",
Help: "Number of DB connections currently in use.",
})
scope.MustRegister(inUse)
idle := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_idle",
Help: "Number of idle DB connections.",
})
scope.MustRegister(idle)
waitCount := prometheus.NewCounter(prometheus.CounterOpts{
Name: "db_wait_count",
Help: "Total number of DB connections waited for.",
})
scope.MustRegister(waitCount)
waitDuration := prometheus.NewCounter(prometheus.CounterOpts{
Name: "db_wait_duration_seconds",
Help: "The total time blocked waiting for a new connection.",
})
scope.MustRegister(waitDuration)
maxIdleClosed := prometheus.NewCounter(prometheus.CounterOpts{
Name: "db_max_idle_closed",
Help: "Total number of connections closed due to SetMaxIdleConns.",
})
scope.MustRegister(maxIdleClosed)
maxLifetimeClosed := prometheus.NewCounter(prometheus.CounterOpts{
Name: "db_max_lifetime_closed",
Help: "Total number of connections closed due to SetConnMaxLifetime.",
})
scope.MustRegister(maxLifetimeClosed)
// Construct a dbMetrics instance with all of the registered metrics and the
// gorp DBMap
return &dbMetrics{
dbMap: dbMap,
maxOpenConnections: maxOpenConns,
openConnections: openConns,
inUse: inUse,
idle: idle,
waitCount: waitCount,
waitDuration: waitDuration,
maxIdleClosed: maxIdleClosed,
maxLifetimeClosed: maxLifetimeClosed,
}
} | [
"func",
"newDbMetrics",
"(",
"dbMap",
"*",
"gorp",
".",
"DbMap",
",",
"scope",
"metrics",
".",
"Scope",
")",
"*",
"dbMetrics",
"{",
"maxOpenConns",
":=",
"prometheus",
".",
"NewGauge",
"(",
"prometheus",
".",
"GaugeOpts",
"{",
"Name",
":",
"\"db_max_open_connections\"",
",",
"Help",
":",
"\"Maximum number of DB connections allowed.\"",
",",
"}",
")",
"\n",
"scope",
".",
"MustRegister",
"(",
"maxOpenConns",
")",
"\n",
"openConns",
":=",
"prometheus",
".",
"NewGauge",
"(",
"prometheus",
".",
"GaugeOpts",
"{",
"Name",
":",
"\"db_open_connections\"",
",",
"Help",
":",
"\"Number of established DB connections (in-use and idle).\"",
",",
"}",
")",
"\n",
"scope",
".",
"MustRegister",
"(",
"openConns",
")",
"\n",
"inUse",
":=",
"prometheus",
".",
"NewGauge",
"(",
"prometheus",
".",
"GaugeOpts",
"{",
"Name",
":",
"\"db_inuse\"",
",",
"Help",
":",
"\"Number of DB connections currently in use.\"",
",",
"}",
")",
"\n",
"scope",
".",
"MustRegister",
"(",
"inUse",
")",
"\n",
"idle",
":=",
"prometheus",
".",
"NewGauge",
"(",
"prometheus",
".",
"GaugeOpts",
"{",
"Name",
":",
"\"db_idle\"",
",",
"Help",
":",
"\"Number of idle DB connections.\"",
",",
"}",
")",
"\n",
"scope",
".",
"MustRegister",
"(",
"idle",
")",
"\n",
"waitCount",
":=",
"prometheus",
".",
"NewCounter",
"(",
"prometheus",
".",
"CounterOpts",
"{",
"Name",
":",
"\"db_wait_count\"",
",",
"Help",
":",
"\"Total number of DB connections waited for.\"",
",",
"}",
")",
"\n",
"scope",
".",
"MustRegister",
"(",
"waitCount",
")",
"\n",
"waitDuration",
":=",
"prometheus",
".",
"NewCounter",
"(",
"prometheus",
".",
"CounterOpts",
"{",
"Name",
":",
"\"db_wait_duration_seconds\"",
",",
"Help",
":",
"\"The total time blocked waiting for a new connection.\"",
",",
"}",
")",
"\n",
"scope",
".",
"MustRegister",
"(",
"waitDuration",
")",
"\n",
"maxIdleClosed",
":=",
"prometheus",
".",
"NewCounter",
"(",
"prometheus",
".",
"CounterOpts",
"{",
"Name",
":",
"\"db_max_idle_closed\"",
",",
"Help",
":",
"\"Total number of connections closed due to SetMaxIdleConns.\"",
",",
"}",
")",
"\n",
"scope",
".",
"MustRegister",
"(",
"maxIdleClosed",
")",
"\n",
"maxLifetimeClosed",
":=",
"prometheus",
".",
"NewCounter",
"(",
"prometheus",
".",
"CounterOpts",
"{",
"Name",
":",
"\"db_max_lifetime_closed\"",
",",
"Help",
":",
"\"Total number of connections closed due to SetConnMaxLifetime.\"",
",",
"}",
")",
"\n",
"scope",
".",
"MustRegister",
"(",
"maxLifetimeClosed",
")",
"\n",
"return",
"&",
"dbMetrics",
"{",
"dbMap",
":",
"dbMap",
",",
"maxOpenConnections",
":",
"maxOpenConns",
",",
"openConnections",
":",
"openConns",
",",
"inUse",
":",
"inUse",
",",
"idle",
":",
"idle",
",",
"waitCount",
":",
"waitCount",
",",
"waitDuration",
":",
"waitDuration",
",",
"maxIdleClosed",
":",
"maxIdleClosed",
",",
"maxLifetimeClosed",
":",
"maxLifetimeClosed",
",",
"}",
"\n",
"}"
] | // newDbMetrics constructs a dbMetrics instance by registering prometheus stats. | [
"newDbMetrics",
"constructs",
"a",
"dbMetrics",
"instance",
"by",
"registering",
"prometheus",
"stats",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/metrics.go#L39-L101 | train |
letsencrypt/boulder | sa/metrics.go | updateFrom | func (dbm *dbMetrics) updateFrom(dbStats sql.DBStats) {
dbm.maxOpenConnections.Set(float64(dbStats.MaxOpenConnections))
dbm.openConnections.Set(float64(dbStats.OpenConnections))
dbm.inUse.Set(float64(dbStats.InUse))
dbm.idle.Set(float64(dbStats.InUse))
dbm.waitCount.Set(float64(dbStats.WaitCount))
dbm.waitDuration.Set(float64(dbStats.WaitDuration.Seconds()))
dbm.maxIdleClosed.Set(float64(dbStats.MaxIdleClosed))
dbm.maxLifetimeClosed.Set(float64(dbStats.MaxLifetimeClosed))
} | go | func (dbm *dbMetrics) updateFrom(dbStats sql.DBStats) {
dbm.maxOpenConnections.Set(float64(dbStats.MaxOpenConnections))
dbm.openConnections.Set(float64(dbStats.OpenConnections))
dbm.inUse.Set(float64(dbStats.InUse))
dbm.idle.Set(float64(dbStats.InUse))
dbm.waitCount.Set(float64(dbStats.WaitCount))
dbm.waitDuration.Set(float64(dbStats.WaitDuration.Seconds()))
dbm.maxIdleClosed.Set(float64(dbStats.MaxIdleClosed))
dbm.maxLifetimeClosed.Set(float64(dbStats.MaxLifetimeClosed))
} | [
"func",
"(",
"dbm",
"*",
"dbMetrics",
")",
"updateFrom",
"(",
"dbStats",
"sql",
".",
"DBStats",
")",
"{",
"dbm",
".",
"maxOpenConnections",
".",
"Set",
"(",
"float64",
"(",
"dbStats",
".",
"MaxOpenConnections",
")",
")",
"\n",
"dbm",
".",
"openConnections",
".",
"Set",
"(",
"float64",
"(",
"dbStats",
".",
"OpenConnections",
")",
")",
"\n",
"dbm",
".",
"inUse",
".",
"Set",
"(",
"float64",
"(",
"dbStats",
".",
"InUse",
")",
")",
"\n",
"dbm",
".",
"idle",
".",
"Set",
"(",
"float64",
"(",
"dbStats",
".",
"InUse",
")",
")",
"\n",
"dbm",
".",
"waitCount",
".",
"Set",
"(",
"float64",
"(",
"dbStats",
".",
"WaitCount",
")",
")",
"\n",
"dbm",
".",
"waitDuration",
".",
"Set",
"(",
"float64",
"(",
"dbStats",
".",
"WaitDuration",
".",
"Seconds",
"(",
")",
")",
")",
"\n",
"dbm",
".",
"maxIdleClosed",
".",
"Set",
"(",
"float64",
"(",
"dbStats",
".",
"MaxIdleClosed",
")",
")",
"\n",
"dbm",
".",
"maxLifetimeClosed",
".",
"Set",
"(",
"float64",
"(",
"dbStats",
".",
"MaxLifetimeClosed",
")",
")",
"\n",
"}"
] | // updateFrom updates the dbMetrics prometheus stats based on the provided
// sql.DBStats object. | [
"updateFrom",
"updates",
"the",
"dbMetrics",
"prometheus",
"stats",
"based",
"on",
"the",
"provided",
"sql",
".",
"DBStats",
"object",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/metrics.go#L105-L114 | train |
letsencrypt/boulder | sa/metrics.go | reportDBMetrics | func (dbm *dbMetrics) reportDBMetrics() {
for {
stats := dbm.dbMap.Db.Stats()
dbm.updateFrom(stats)
time.Sleep(1 * time.Second)
}
} | go | func (dbm *dbMetrics) reportDBMetrics() {
for {
stats := dbm.dbMap.Db.Stats()
dbm.updateFrom(stats)
time.Sleep(1 * time.Second)
}
} | [
"func",
"(",
"dbm",
"*",
"dbMetrics",
")",
"reportDBMetrics",
"(",
")",
"{",
"for",
"{",
"stats",
":=",
"dbm",
".",
"dbMap",
".",
"Db",
".",
"Stats",
"(",
")",
"\n",
"dbm",
".",
"updateFrom",
"(",
"stats",
")",
"\n",
"time",
".",
"Sleep",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}"
] | // reportDBMetrics is an infinite loop that will update the dbm with the gorp
// dbMap's inner sql.DBMap's DBStats structure every second. It is intended to
// be run in a dedicated goroutine spawned by InitDBMetrics. | [
"reportDBMetrics",
"is",
"an",
"infinite",
"loop",
"that",
"will",
"update",
"the",
"dbm",
"with",
"the",
"gorp",
"dbMap",
"s",
"inner",
"sql",
".",
"DBMap",
"s",
"DBStats",
"structure",
"every",
"second",
".",
"It",
"is",
"intended",
"to",
"be",
"run",
"in",
"a",
"dedicated",
"goroutine",
"spawned",
"by",
"InitDBMetrics",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/metrics.go#L119-L125 | train |
letsencrypt/boulder | grpc/errors.go | unwrapError | func unwrapError(err error, md metadata.MD) error {
if err == nil {
return nil
}
if errTypeStrs, ok := md["errortype"]; ok {
unwrappedErr := grpc.ErrorDesc(err)
if len(errTypeStrs) != 1 {
return berrors.InternalServerError(
"multiple errorType metadata, wrapped error %q",
unwrappedErr,
)
}
errType, decErr := strconv.Atoi(errTypeStrs[0])
if decErr != nil {
return berrors.InternalServerError(
"failed to decode error type, decoding error %q, wrapped error %q",
decErr,
unwrappedErr,
)
}
return berrors.New(berrors.ErrorType(errType), unwrappedErr)
}
return err
} | go | func unwrapError(err error, md metadata.MD) error {
if err == nil {
return nil
}
if errTypeStrs, ok := md["errortype"]; ok {
unwrappedErr := grpc.ErrorDesc(err)
if len(errTypeStrs) != 1 {
return berrors.InternalServerError(
"multiple errorType metadata, wrapped error %q",
unwrappedErr,
)
}
errType, decErr := strconv.Atoi(errTypeStrs[0])
if decErr != nil {
return berrors.InternalServerError(
"failed to decode error type, decoding error %q, wrapped error %q",
decErr,
unwrappedErr,
)
}
return berrors.New(berrors.ErrorType(errType), unwrappedErr)
}
return err
} | [
"func",
"unwrapError",
"(",
"err",
"error",
",",
"md",
"metadata",
".",
"MD",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"errTypeStrs",
",",
"ok",
":=",
"md",
"[",
"\"errortype\"",
"]",
";",
"ok",
"{",
"unwrappedErr",
":=",
"grpc",
".",
"ErrorDesc",
"(",
"err",
")",
"\n",
"if",
"len",
"(",
"errTypeStrs",
")",
"!=",
"1",
"{",
"return",
"berrors",
".",
"InternalServerError",
"(",
"\"multiple errorType metadata, wrapped error %q\"",
",",
"unwrappedErr",
",",
")",
"\n",
"}",
"\n",
"errType",
",",
"decErr",
":=",
"strconv",
".",
"Atoi",
"(",
"errTypeStrs",
"[",
"0",
"]",
")",
"\n",
"if",
"decErr",
"!=",
"nil",
"{",
"return",
"berrors",
".",
"InternalServerError",
"(",
"\"failed to decode error type, decoding error %q, wrapped error %q\"",
",",
"decErr",
",",
"unwrappedErr",
",",
")",
"\n",
"}",
"\n",
"return",
"berrors",
".",
"New",
"(",
"berrors",
".",
"ErrorType",
"(",
"errType",
")",
",",
"unwrappedErr",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // unwrapError unwraps errors returned from gRPC client calls which were wrapped
// with wrapError to their proper internal error type. If the provided metadata
// object has an "errortype" field, that will be used to set the type of the
// error. | [
"unwrapError",
"unwraps",
"errors",
"returned",
"from",
"gRPC",
"client",
"calls",
"which",
"were",
"wrapped",
"with",
"wrapError",
"to",
"their",
"proper",
"internal",
"error",
"type",
".",
"If",
"the",
"provided",
"metadata",
"object",
"has",
"an",
"errortype",
"field",
"that",
"will",
"be",
"used",
"to",
"set",
"the",
"type",
"of",
"the",
"error",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/grpc/errors.go#L43-L66 | train |
letsencrypt/boulder | mail/mailer.go | New | func New(
server,
port,
username,
password string,
rootCAs *x509.CertPool,
from mail.Address,
logger blog.Logger,
stats metrics.Scope,
reconnectBase time.Duration,
reconnectMax time.Duration) *MailerImpl {
return &MailerImpl{
dialer: &dialerImpl{
username: username,
password: password,
server: server,
port: port,
rootCAs: rootCAs,
},
log: logger,
from: from,
clk: clock.Default(),
csprgSource: realSource{},
stats: stats.NewScope("Mailer"),
reconnectBase: reconnectBase,
reconnectMax: reconnectMax,
}
} | go | func New(
server,
port,
username,
password string,
rootCAs *x509.CertPool,
from mail.Address,
logger blog.Logger,
stats metrics.Scope,
reconnectBase time.Duration,
reconnectMax time.Duration) *MailerImpl {
return &MailerImpl{
dialer: &dialerImpl{
username: username,
password: password,
server: server,
port: port,
rootCAs: rootCAs,
},
log: logger,
from: from,
clk: clock.Default(),
csprgSource: realSource{},
stats: stats.NewScope("Mailer"),
reconnectBase: reconnectBase,
reconnectMax: reconnectMax,
}
} | [
"func",
"New",
"(",
"server",
",",
"port",
",",
"username",
",",
"password",
"string",
",",
"rootCAs",
"*",
"x509",
".",
"CertPool",
",",
"from",
"mail",
".",
"Address",
",",
"logger",
"blog",
".",
"Logger",
",",
"stats",
"metrics",
".",
"Scope",
",",
"reconnectBase",
"time",
".",
"Duration",
",",
"reconnectMax",
"time",
".",
"Duration",
")",
"*",
"MailerImpl",
"{",
"return",
"&",
"MailerImpl",
"{",
"dialer",
":",
"&",
"dialerImpl",
"{",
"username",
":",
"username",
",",
"password",
":",
"password",
",",
"server",
":",
"server",
",",
"port",
":",
"port",
",",
"rootCAs",
":",
"rootCAs",
",",
"}",
",",
"log",
":",
"logger",
",",
"from",
":",
"from",
",",
"clk",
":",
"clock",
".",
"Default",
"(",
")",
",",
"csprgSource",
":",
"realSource",
"{",
"}",
",",
"stats",
":",
"stats",
".",
"NewScope",
"(",
"\"Mailer\"",
")",
",",
"reconnectBase",
":",
"reconnectBase",
",",
"reconnectMax",
":",
"reconnectMax",
",",
"}",
"\n",
"}"
] | // New constructs a Mailer to represent an account on a particular mail
// transfer agent. | [
"New",
"constructs",
"a",
"Mailer",
"to",
"represent",
"an",
"account",
"on",
"a",
"particular",
"mail",
"transfer",
"agent",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/mail/mailer.go#L116-L143 | train |
letsencrypt/boulder | mail/mailer.go | NewDryRun | func NewDryRun(from mail.Address, logger blog.Logger) *MailerImpl {
stats := metrics.NewNoopScope()
return &MailerImpl{
dialer: dryRunClient{logger},
from: from,
clk: clock.Default(),
csprgSource: realSource{},
stats: stats,
}
} | go | func NewDryRun(from mail.Address, logger blog.Logger) *MailerImpl {
stats := metrics.NewNoopScope()
return &MailerImpl{
dialer: dryRunClient{logger},
from: from,
clk: clock.Default(),
csprgSource: realSource{},
stats: stats,
}
} | [
"func",
"NewDryRun",
"(",
"from",
"mail",
".",
"Address",
",",
"logger",
"blog",
".",
"Logger",
")",
"*",
"MailerImpl",
"{",
"stats",
":=",
"metrics",
".",
"NewNoopScope",
"(",
")",
"\n",
"return",
"&",
"MailerImpl",
"{",
"dialer",
":",
"dryRunClient",
"{",
"logger",
"}",
",",
"from",
":",
"from",
",",
"clk",
":",
"clock",
".",
"Default",
"(",
")",
",",
"csprgSource",
":",
"realSource",
"{",
"}",
",",
"stats",
":",
"stats",
",",
"}",
"\n",
"}"
] | // New constructs a Mailer suitable for doing a dry run. It simply logs each
// command that would have been run, at debug level. | [
"New",
"constructs",
"a",
"Mailer",
"suitable",
"for",
"doing",
"a",
"dry",
"run",
".",
"It",
"simply",
"logs",
"each",
"command",
"that",
"would",
"have",
"been",
"run",
"at",
"debug",
"level",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/mail/mailer.go#L147-L156 | train |
letsencrypt/boulder | mail/mailer.go | Connect | func (m *MailerImpl) Connect() error {
client, err := m.dialer.Dial()
if err != nil {
return err
}
m.client = client
return nil
} | go | func (m *MailerImpl) Connect() error {
client, err := m.dialer.Dial()
if err != nil {
return err
}
m.client = client
return nil
} | [
"func",
"(",
"m",
"*",
"MailerImpl",
")",
"Connect",
"(",
")",
"error",
"{",
"client",
",",
"err",
":=",
"m",
".",
"dialer",
".",
"Dial",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"m",
".",
"client",
"=",
"client",
"\n",
"return",
"nil",
"\n",
"}"
] | // Connect opens a connection to the specified mail server. It must be called
// before SendMail. | [
"Connect",
"opens",
"a",
"connection",
"to",
"the",
"specified",
"mail",
"server",
".",
"It",
"must",
"be",
"called",
"before",
"SendMail",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/mail/mailer.go#L217-L224 | train |
letsencrypt/boulder | mail/mailer.go | SendMail | func (m *MailerImpl) SendMail(to []string, subject, msg string) error {
m.stats.Inc("SendMail.Attempts", 1)
for {
err := m.sendOne(to, subject, msg)
if err == nil {
// If the error is nil, we sent the mail without issue. nice!
break
} else if err == io.EOF {
// If the error is an EOF, we should try to reconnect on a backoff
// schedule, sleeping between attempts.
m.stats.Inc("SendMail.Errors.EOF", 1)
m.reconnect()
// After reconnecting, loop around and try `sendOne` again.
m.stats.Inc("SendMail.Reconnects", 1)
continue
} else if protoErr, ok := err.(*textproto.Error); ok && protoErr.Code == 421 {
/*
* If the error is an instance of `textproto.Error` with a SMTP error code,
* and that error code is 421 then treat this as a reconnect-able event.
*
* The SMTP RFC defines this error code as:
* 421 <domain> Service not available, closing transmission channel
* (This may be a reply to any command if the service knows it
* must shut down)
*
* In practice we see this code being used by our production SMTP server
* when the connection has gone idle for too long. For more information
* see issue #2249[0].
*
* [0] - https://github.com/letsencrypt/boulder/issues/2249
*/
m.stats.Inc("SendMail.Errors.SMTP.421", 1)
m.reconnect()
m.stats.Inc("SendMail.Reconnects", 1)
} else if protoErr, ok := err.(*textproto.Error); ok && recoverableErrorCodes[protoErr.Code] {
m.stats.Inc(fmt.Sprintf("SendMail.Errors.SMTP.%d", protoErr.Code), 1)
return RecoverableSMTPError{fmt.Sprintf("%d: %s", protoErr.Code, protoErr.Msg)}
} else {
// If it wasn't an EOF error or a recoverable SMTP error it is unexpected and we
// return from SendMail() with the error
m.stats.Inc("SendMail.Errors", 1)
return err
}
}
m.stats.Inc("SendMail.Successes", 1)
return nil
} | go | func (m *MailerImpl) SendMail(to []string, subject, msg string) error {
m.stats.Inc("SendMail.Attempts", 1)
for {
err := m.sendOne(to, subject, msg)
if err == nil {
// If the error is nil, we sent the mail without issue. nice!
break
} else if err == io.EOF {
// If the error is an EOF, we should try to reconnect on a backoff
// schedule, sleeping between attempts.
m.stats.Inc("SendMail.Errors.EOF", 1)
m.reconnect()
// After reconnecting, loop around and try `sendOne` again.
m.stats.Inc("SendMail.Reconnects", 1)
continue
} else if protoErr, ok := err.(*textproto.Error); ok && protoErr.Code == 421 {
/*
* If the error is an instance of `textproto.Error` with a SMTP error code,
* and that error code is 421 then treat this as a reconnect-able event.
*
* The SMTP RFC defines this error code as:
* 421 <domain> Service not available, closing transmission channel
* (This may be a reply to any command if the service knows it
* must shut down)
*
* In practice we see this code being used by our production SMTP server
* when the connection has gone idle for too long. For more information
* see issue #2249[0].
*
* [0] - https://github.com/letsencrypt/boulder/issues/2249
*/
m.stats.Inc("SendMail.Errors.SMTP.421", 1)
m.reconnect()
m.stats.Inc("SendMail.Reconnects", 1)
} else if protoErr, ok := err.(*textproto.Error); ok && recoverableErrorCodes[protoErr.Code] {
m.stats.Inc(fmt.Sprintf("SendMail.Errors.SMTP.%d", protoErr.Code), 1)
return RecoverableSMTPError{fmt.Sprintf("%d: %s", protoErr.Code, protoErr.Msg)}
} else {
// If it wasn't an EOF error or a recoverable SMTP error it is unexpected and we
// return from SendMail() with the error
m.stats.Inc("SendMail.Errors", 1)
return err
}
}
m.stats.Inc("SendMail.Successes", 1)
return nil
} | [
"func",
"(",
"m",
"*",
"MailerImpl",
")",
"SendMail",
"(",
"to",
"[",
"]",
"string",
",",
"subject",
",",
"msg",
"string",
")",
"error",
"{",
"m",
".",
"stats",
".",
"Inc",
"(",
"\"SendMail.Attempts\"",
",",
"1",
")",
"\n",
"for",
"{",
"err",
":=",
"m",
".",
"sendOne",
"(",
"to",
",",
"subject",
",",
"msg",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"else",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"m",
".",
"stats",
".",
"Inc",
"(",
"\"SendMail.Errors.EOF\"",
",",
"1",
")",
"\n",
"m",
".",
"reconnect",
"(",
")",
"\n",
"m",
".",
"stats",
".",
"Inc",
"(",
"\"SendMail.Reconnects\"",
",",
"1",
")",
"\n",
"continue",
"\n",
"}",
"else",
"if",
"protoErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"textproto",
".",
"Error",
")",
";",
"ok",
"&&",
"protoErr",
".",
"Code",
"==",
"421",
"{",
"m",
".",
"stats",
".",
"Inc",
"(",
"\"SendMail.Errors.SMTP.421\"",
",",
"1",
")",
"\n",
"m",
".",
"reconnect",
"(",
")",
"\n",
"m",
".",
"stats",
".",
"Inc",
"(",
"\"SendMail.Reconnects\"",
",",
"1",
")",
"\n",
"}",
"else",
"if",
"protoErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"textproto",
".",
"Error",
")",
";",
"ok",
"&&",
"recoverableErrorCodes",
"[",
"protoErr",
".",
"Code",
"]",
"{",
"m",
".",
"stats",
".",
"Inc",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"SendMail.Errors.SMTP.%d\"",
",",
"protoErr",
".",
"Code",
")",
",",
"1",
")",
"\n",
"return",
"RecoverableSMTPError",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"%d: %s\"",
",",
"protoErr",
".",
"Code",
",",
"protoErr",
".",
"Msg",
")",
"}",
"\n",
"}",
"else",
"{",
"m",
".",
"stats",
".",
"Inc",
"(",
"\"SendMail.Errors\"",
",",
"1",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"m",
".",
"stats",
".",
"Inc",
"(",
"\"SendMail.Successes\"",
",",
"1",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // SendMail sends an email to the provided list of recipients. The email body
// is simple text. | [
"SendMail",
"sends",
"an",
"email",
"to",
"the",
"provided",
"list",
"of",
"recipients",
".",
"The",
"email",
"body",
"is",
"simple",
"text",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/mail/mailer.go#L327-L375 | train |
letsencrypt/boulder | sa/rollback.go | Rollback | func Rollback(tx *gorp.Transaction, err error) error {
if txErr := tx.Rollback(); txErr != nil {
return &RollbackError{
Err: err,
RollbackErr: txErr,
}
}
return err
} | go | func Rollback(tx *gorp.Transaction, err error) error {
if txErr := tx.Rollback(); txErr != nil {
return &RollbackError{
Err: err,
RollbackErr: txErr,
}
}
return err
} | [
"func",
"Rollback",
"(",
"tx",
"*",
"gorp",
".",
"Transaction",
",",
"err",
"error",
")",
"error",
"{",
"if",
"txErr",
":=",
"tx",
".",
"Rollback",
"(",
")",
";",
"txErr",
"!=",
"nil",
"{",
"return",
"&",
"RollbackError",
"{",
"Err",
":",
"err",
",",
"RollbackErr",
":",
"txErr",
",",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Rollback rolls back the provided transaction. If the rollback fails for any
// reason a `RollbackError` error is returned wrapping the original error. If no
// rollback error occurs then the original error is returned. | [
"Rollback",
"rolls",
"back",
"the",
"provided",
"transaction",
".",
"If",
"the",
"rollback",
"fails",
"for",
"any",
"reason",
"a",
"RollbackError",
"error",
"is",
"returned",
"wrapping",
"the",
"original",
"error",
".",
"If",
"no",
"rollback",
"error",
"occurs",
"then",
"the",
"original",
"error",
"is",
"returned",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/rollback.go#L32-L40 | train |
letsencrypt/boulder | ca/ca.go | noteSignError | func (ca *CertificateAuthorityImpl) noteSignError(err error) {
if err != nil {
if _, ok := err.(*pkcs11.Error); ok {
ca.stats.Inc(metricHSMError, 1)
} else if cfErr, ok := err.(*cferr.Error); ok {
ca.stats.Inc(fmt.Sprintf("%s.%d", metricSigningError, cfErr.ErrorCode), 1)
}
}
return
} | go | func (ca *CertificateAuthorityImpl) noteSignError(err error) {
if err != nil {
if _, ok := err.(*pkcs11.Error); ok {
ca.stats.Inc(metricHSMError, 1)
} else if cfErr, ok := err.(*cferr.Error); ok {
ca.stats.Inc(fmt.Sprintf("%s.%d", metricSigningError, cfErr.ErrorCode), 1)
}
}
return
} | [
"func",
"(",
"ca",
"*",
"CertificateAuthorityImpl",
")",
"noteSignError",
"(",
"err",
"error",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"pkcs11",
".",
"Error",
")",
";",
"ok",
"{",
"ca",
".",
"stats",
".",
"Inc",
"(",
"metricHSMError",
",",
"1",
")",
"\n",
"}",
"else",
"if",
"cfErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"cferr",
".",
"Error",
")",
";",
"ok",
"{",
"ca",
".",
"stats",
".",
"Inc",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s.%d\"",
",",
"metricSigningError",
",",
"cfErr",
".",
"ErrorCode",
")",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // noteSignError is called after operations that may cause a CFSSL
// or PKCS11 signing error. | [
"noteSignError",
"is",
"called",
"after",
"operations",
"that",
"may",
"cause",
"a",
"CFSSL",
"or",
"PKCS11",
"signing",
"error",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ca/ca.go#L305-L314 | train |
letsencrypt/boulder | ca/ca.go | GenerateOCSP | func (ca *CertificateAuthorityImpl) GenerateOCSP(ctx context.Context, xferObj core.OCSPSigningRequest) ([]byte, error) {
cert, err := x509.ParseCertificate(xferObj.CertDER)
if err != nil {
ca.log.AuditErr(err.Error())
return nil, err
}
signRequest := ocsp.SignRequest{
Certificate: cert,
Status: xferObj.Status,
Reason: int(xferObj.Reason),
RevokedAt: xferObj.RevokedAt,
}
cn := cert.Issuer.CommonName
issuer := ca.issuers[cn]
if issuer == nil {
return nil, fmt.Errorf("This CA doesn't have an issuer cert with CommonName %q", cn)
}
err = cert.CheckSignatureFrom(issuer.cert)
if err != nil {
return nil, fmt.Errorf("GenerateOCSP was asked to sign OCSP for cert "+
"%s from %q, but the cert's signature was not valid: %s.",
core.SerialToString(cert.SerialNumber), cn, err)
}
ocspResponse, err := issuer.ocspSigner.Sign(signRequest)
ca.noteSignError(err)
if err == nil {
ca.signatureCount.With(prometheus.Labels{"purpose": "ocsp"}).Inc()
}
return ocspResponse, err
} | go | func (ca *CertificateAuthorityImpl) GenerateOCSP(ctx context.Context, xferObj core.OCSPSigningRequest) ([]byte, error) {
cert, err := x509.ParseCertificate(xferObj.CertDER)
if err != nil {
ca.log.AuditErr(err.Error())
return nil, err
}
signRequest := ocsp.SignRequest{
Certificate: cert,
Status: xferObj.Status,
Reason: int(xferObj.Reason),
RevokedAt: xferObj.RevokedAt,
}
cn := cert.Issuer.CommonName
issuer := ca.issuers[cn]
if issuer == nil {
return nil, fmt.Errorf("This CA doesn't have an issuer cert with CommonName %q", cn)
}
err = cert.CheckSignatureFrom(issuer.cert)
if err != nil {
return nil, fmt.Errorf("GenerateOCSP was asked to sign OCSP for cert "+
"%s from %q, but the cert's signature was not valid: %s.",
core.SerialToString(cert.SerialNumber), cn, err)
}
ocspResponse, err := issuer.ocspSigner.Sign(signRequest)
ca.noteSignError(err)
if err == nil {
ca.signatureCount.With(prometheus.Labels{"purpose": "ocsp"}).Inc()
}
return ocspResponse, err
} | [
"func",
"(",
"ca",
"*",
"CertificateAuthorityImpl",
")",
"GenerateOCSP",
"(",
"ctx",
"context",
".",
"Context",
",",
"xferObj",
"core",
".",
"OCSPSigningRequest",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"xferObj",
".",
"CertDER",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ca",
".",
"log",
".",
"AuditErr",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"signRequest",
":=",
"ocsp",
".",
"SignRequest",
"{",
"Certificate",
":",
"cert",
",",
"Status",
":",
"xferObj",
".",
"Status",
",",
"Reason",
":",
"int",
"(",
"xferObj",
".",
"Reason",
")",
",",
"RevokedAt",
":",
"xferObj",
".",
"RevokedAt",
",",
"}",
"\n",
"cn",
":=",
"cert",
".",
"Issuer",
".",
"CommonName",
"\n",
"issuer",
":=",
"ca",
".",
"issuers",
"[",
"cn",
"]",
"\n",
"if",
"issuer",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"This CA doesn't have an issuer cert with CommonName %q\"",
",",
"cn",
")",
"\n",
"}",
"\n",
"err",
"=",
"cert",
".",
"CheckSignatureFrom",
"(",
"issuer",
".",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"GenerateOCSP was asked to sign OCSP for cert \"",
"+",
"\"%s from %q, but the cert's signature was not valid: %s.\"",
",",
"core",
".",
"SerialToString",
"(",
"cert",
".",
"SerialNumber",
")",
",",
"cn",
",",
"err",
")",
"\n",
"}",
"\n",
"ocspResponse",
",",
"err",
":=",
"issuer",
".",
"ocspSigner",
".",
"Sign",
"(",
"signRequest",
")",
"\n",
"ca",
".",
"noteSignError",
"(",
"err",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"ca",
".",
"signatureCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"purpose\"",
":",
"\"ocsp\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"}",
"\n",
"return",
"ocspResponse",
",",
"err",
"\n",
"}"
] | // GenerateOCSP produces a new OCSP response and returns it | [
"GenerateOCSP",
"produces",
"a",
"new",
"OCSP",
"response",
"and",
"returns",
"it"
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ca/ca.go#L386-L419 | train |
letsencrypt/boulder | ca/ca.go | IssueCertificateForPrecertificate | func (ca *CertificateAuthorityImpl) IssueCertificateForPrecertificate(ctx context.Context, req *caPB.IssueCertificateForPrecertificateRequest) (core.Certificate, error) {
emptyCert := core.Certificate{}
precert, err := x509.ParseCertificate(req.DER)
if err != nil {
return emptyCert, err
}
var scts []ct.SignedCertificateTimestamp
for _, sctBytes := range req.SCTs {
var sct ct.SignedCertificateTimestamp
_, err = cttls.Unmarshal(sctBytes, &sct)
if err != nil {
return emptyCert, err
}
scts = append(scts, sct)
}
certPEM, err := ca.defaultIssuer.eeSigner.SignFromPrecert(precert, scts)
if err != nil {
return emptyCert, err
}
serialHex := core.SerialToString(precert.SerialNumber)
block, _ := pem.Decode(certPEM)
if block == nil || block.Type != "CERTIFICATE" {
err = berrors.InternalServerError("invalid certificate value returned")
ca.log.AuditErrf("PEM decode error, aborting: serial=[%s] pem=[%s] err=[%v]", serialHex, certPEM, err)
return emptyCert, err
}
certDER := block.Bytes
ca.log.AuditInfof("Signing success: serial=[%s] names=[%s] precertificate=[%s] certificate=[%s]",
serialHex, strings.Join(precert.DNSNames, ", "), hex.EncodeToString(req.DER),
hex.EncodeToString(certDER))
return ca.generateOCSPAndStoreCertificate(ctx, *req.RegistrationID, *req.OrderID, precert.SerialNumber, certDER)
} | go | func (ca *CertificateAuthorityImpl) IssueCertificateForPrecertificate(ctx context.Context, req *caPB.IssueCertificateForPrecertificateRequest) (core.Certificate, error) {
emptyCert := core.Certificate{}
precert, err := x509.ParseCertificate(req.DER)
if err != nil {
return emptyCert, err
}
var scts []ct.SignedCertificateTimestamp
for _, sctBytes := range req.SCTs {
var sct ct.SignedCertificateTimestamp
_, err = cttls.Unmarshal(sctBytes, &sct)
if err != nil {
return emptyCert, err
}
scts = append(scts, sct)
}
certPEM, err := ca.defaultIssuer.eeSigner.SignFromPrecert(precert, scts)
if err != nil {
return emptyCert, err
}
serialHex := core.SerialToString(precert.SerialNumber)
block, _ := pem.Decode(certPEM)
if block == nil || block.Type != "CERTIFICATE" {
err = berrors.InternalServerError("invalid certificate value returned")
ca.log.AuditErrf("PEM decode error, aborting: serial=[%s] pem=[%s] err=[%v]", serialHex, certPEM, err)
return emptyCert, err
}
certDER := block.Bytes
ca.log.AuditInfof("Signing success: serial=[%s] names=[%s] precertificate=[%s] certificate=[%s]",
serialHex, strings.Join(precert.DNSNames, ", "), hex.EncodeToString(req.DER),
hex.EncodeToString(certDER))
return ca.generateOCSPAndStoreCertificate(ctx, *req.RegistrationID, *req.OrderID, precert.SerialNumber, certDER)
} | [
"func",
"(",
"ca",
"*",
"CertificateAuthorityImpl",
")",
"IssueCertificateForPrecertificate",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"caPB",
".",
"IssueCertificateForPrecertificateRequest",
")",
"(",
"core",
".",
"Certificate",
",",
"error",
")",
"{",
"emptyCert",
":=",
"core",
".",
"Certificate",
"{",
"}",
"\n",
"precert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"req",
".",
"DER",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"emptyCert",
",",
"err",
"\n",
"}",
"\n",
"var",
"scts",
"[",
"]",
"ct",
".",
"SignedCertificateTimestamp",
"\n",
"for",
"_",
",",
"sctBytes",
":=",
"range",
"req",
".",
"SCTs",
"{",
"var",
"sct",
"ct",
".",
"SignedCertificateTimestamp",
"\n",
"_",
",",
"err",
"=",
"cttls",
".",
"Unmarshal",
"(",
"sctBytes",
",",
"&",
"sct",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"emptyCert",
",",
"err",
"\n",
"}",
"\n",
"scts",
"=",
"append",
"(",
"scts",
",",
"sct",
")",
"\n",
"}",
"\n",
"certPEM",
",",
"err",
":=",
"ca",
".",
"defaultIssuer",
".",
"eeSigner",
".",
"SignFromPrecert",
"(",
"precert",
",",
"scts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"emptyCert",
",",
"err",
"\n",
"}",
"\n",
"serialHex",
":=",
"core",
".",
"SerialToString",
"(",
"precert",
".",
"SerialNumber",
")",
"\n",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"certPEM",
")",
"\n",
"if",
"block",
"==",
"nil",
"||",
"block",
".",
"Type",
"!=",
"\"CERTIFICATE\"",
"{",
"err",
"=",
"berrors",
".",
"InternalServerError",
"(",
"\"invalid certificate value returned\"",
")",
"\n",
"ca",
".",
"log",
".",
"AuditErrf",
"(",
"\"PEM decode error, aborting: serial=[%s] pem=[%s] err=[%v]\"",
",",
"serialHex",
",",
"certPEM",
",",
"err",
")",
"\n",
"return",
"emptyCert",
",",
"err",
"\n",
"}",
"\n",
"certDER",
":=",
"block",
".",
"Bytes",
"\n",
"ca",
".",
"log",
".",
"AuditInfof",
"(",
"\"Signing success: serial=[%s] names=[%s] precertificate=[%s] certificate=[%s]\"",
",",
"serialHex",
",",
"strings",
".",
"Join",
"(",
"precert",
".",
"DNSNames",
",",
"\", \"",
")",
",",
"hex",
".",
"EncodeToString",
"(",
"req",
".",
"DER",
")",
",",
"hex",
".",
"EncodeToString",
"(",
"certDER",
")",
")",
"\n",
"return",
"ca",
".",
"generateOCSPAndStoreCertificate",
"(",
"ctx",
",",
"*",
"req",
".",
"RegistrationID",
",",
"*",
"req",
".",
"OrderID",
",",
"precert",
".",
"SerialNumber",
",",
"certDER",
")",
"\n",
"}"
] | // IssueCertificateForPrecertificate takes a precertificate and a set of SCTs for that precertificate
// and uses the signer to create and sign a certificate from them. The poison extension is removed
// and a SCT list extension is inserted in its place. Except for this and the signature the certificate
// exactly matches the precertificate. After the certificate is signed a OCSP response is generated
// and the response and certificate are stored in the database. | [
"IssueCertificateForPrecertificate",
"takes",
"a",
"precertificate",
"and",
"a",
"set",
"of",
"SCTs",
"for",
"that",
"precertificate",
"and",
"uses",
"the",
"signer",
"to",
"create",
"and",
"sign",
"a",
"certificate",
"from",
"them",
".",
"The",
"poison",
"extension",
"is",
"removed",
"and",
"a",
"SCT",
"list",
"extension",
"is",
"inserted",
"in",
"its",
"place",
".",
"Except",
"for",
"this",
"and",
"the",
"signature",
"the",
"certificate",
"exactly",
"matches",
"the",
"precertificate",
".",
"After",
"the",
"certificate",
"is",
"signed",
"a",
"OCSP",
"response",
"is",
"generated",
"and",
"the",
"response",
"and",
"certificate",
"are",
"stored",
"in",
"the",
"database",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ca/ca.go#L473-L504 | train |
letsencrypt/boulder | ca/ca.go | OrphanIntegrationLoop | func (ca *CertificateAuthorityImpl) OrphanIntegrationLoop() {
for {
if err := ca.integrateOrphan(); err != nil {
if err == goque.ErrEmpty {
time.Sleep(time.Minute)
continue
}
ca.log.AuditErrf("failed to integrate orphaned certs: %s", err)
}
}
} | go | func (ca *CertificateAuthorityImpl) OrphanIntegrationLoop() {
for {
if err := ca.integrateOrphan(); err != nil {
if err == goque.ErrEmpty {
time.Sleep(time.Minute)
continue
}
ca.log.AuditErrf("failed to integrate orphaned certs: %s", err)
}
}
} | [
"func",
"(",
"ca",
"*",
"CertificateAuthorityImpl",
")",
"OrphanIntegrationLoop",
"(",
")",
"{",
"for",
"{",
"if",
"err",
":=",
"ca",
".",
"integrateOrphan",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"goque",
".",
"ErrEmpty",
"{",
"time",
".",
"Sleep",
"(",
"time",
".",
"Minute",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"ca",
".",
"log",
".",
"AuditErrf",
"(",
"\"failed to integrate orphaned certs: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // OrphanIntegrationLoop runs a loop executing integrateOrphans and then waiting a minute.
// It is split out into a separate function called directly by boulder-ca in order to make
// testing the orphan queue functionality somewhat more simple. | [
"OrphanIntegrationLoop",
"runs",
"a",
"loop",
"executing",
"integrateOrphans",
"and",
"then",
"waiting",
"a",
"minute",
".",
"It",
"is",
"split",
"out",
"into",
"a",
"separate",
"function",
"called",
"directly",
"by",
"boulder",
"-",
"ca",
"in",
"order",
"to",
"make",
"testing",
"the",
"orphan",
"queue",
"functionality",
"somewhat",
"more",
"simple",
"."
] | a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf | https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/ca/ca.go#L694-L704 | train |
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",
"(",
"\"failed to peek into orphan queue: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"var",
"orphan",
"orphanedCert",
"\n",
"if",
"err",
"=",
"item",
".",
"ToObject",
"(",
"&",
"orphan",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to marshal orphan: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"orphan",
".",
"DER",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to parse orphan: %s\"",
",",
"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",
"(",
"\"failed to store orphaned certificate: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
"=",
"ca",
".",
"orphanQueue",
".",
"Dequeue",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to dequeue integrated orphaned certificate: %s\"",
",",
"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",
"{",
"authType",
",",
"prob",
":=",
"checkJWSAuthType",
"(",
"jws",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"JWSAuthTypeInvalid\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"prob",
"\n",
"}",
"\n",
"if",
"authType",
"!=",
"expectedAuthType",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"JWSAuthTypeWrong\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"switch",
"expectedAuthType",
"{",
"case",
"embeddedKeyID",
":",
"return",
"probs",
".",
"Malformed",
"(",
"\"No Key ID in JWS header\"",
")",
"\n",
"case",
"embeddedJWK",
":",
"return",
"probs",
".",
"Malformed",
"(",
"\"No embedded JWK in JWS header\"",
")",
"\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",
"{",
"header",
":=",
"jws",
".",
"Signatures",
"[",
"0",
"]",
".",
"Header",
"\n",
"extraHeaders",
":=",
"header",
".",
"ExtraHeaders",
"\n",
"if",
"len",
"(",
"extraHeaders",
")",
"==",
"0",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"JWSNoExtraHeaders\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"probs",
".",
"Malformed",
"(",
"\"JWS header parameter 'url' required\"",
")",
"\n",
"}",
"\n",
"headerURL",
",",
"ok",
":=",
"extraHeaders",
"[",
"jose",
".",
"HeaderKey",
"(",
"\"url\"",
")",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"headerURL",
")",
"==",
"0",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"JWSMissingURL\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"probs",
".",
"Malformed",
"(",
"\"JWS header parameter 'url' required\"",
")",
"\n",
"}",
"\n",
"expectedURL",
":=",
"url",
".",
"URL",
"{",
"Scheme",
":",
"requestProto",
"(",
"request",
")",
",",
"Host",
":",
"request",
".",
"Host",
",",
"Path",
":",
"request",
".",
"RequestURI",
",",
"}",
"\n",
"if",
"expectedURL",
".",
"String",
"(",
")",
"!=",
"headerURL",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"JWSMismatchedURL\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"probs",
".",
"Malformed",
"(",
"\"JWS header parameter 'url' incorrect. Expected %q got %q\"",
",",
"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",
"{",
"outerURL",
",",
"ok",
":=",
"outer",
".",
"Signatures",
"[",
"0",
"]",
".",
"Header",
".",
"ExtraHeaders",
"[",
"jose",
".",
"HeaderKey",
"(",
"\"url\"",
")",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"outerURL",
")",
"==",
"0",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"KeyRolloverOuterJWSNoURL\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"probs",
".",
"Malformed",
"(",
"\"Outer JWS header parameter 'url' required\"",
")",
"\n",
"}",
"\n",
"innerURL",
",",
"ok",
":=",
"inner",
".",
"Signatures",
"[",
"0",
"]",
".",
"Header",
".",
"ExtraHeaders",
"[",
"jose",
".",
"HeaderKey",
"(",
"\"url\"",
")",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"innerURL",
")",
"==",
"0",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"KeyRolloverInnerJWSNoURL\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"probs",
".",
"Malformed",
"(",
"\"Inner JWS header parameter 'url' required\"",
")",
"\n",
"}",
"\n",
"if",
"outerURL",
"!=",
"innerURL",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"KeyRolloverMismatchedURLs\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"probs",
".",
"Malformed",
"(",
"\"Outer JWS 'url' value %q does not match inner JWS 'url' value %q\"",
",",
"outerURL",
",",
"innerURL",
")",
"\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",
")",
"{",
"if",
"prob",
":=",
"wfe",
".",
"validPOSTRequest",
"(",
"request",
")",
";",
"prob",
"!=",
"nil",
"{",
"return",
"nil",
",",
"prob",
"\n",
"}",
"\n",
"bodyBytes",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"request",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"stats",
".",
"httpErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"UnableToReadReqBody\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"nil",
",",
"probs",
".",
"ServerInternal",
"(",
"\"unable to read request body\"",
")",
"\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",
")",
"{",
"if",
"prob",
":=",
"wfe",
".",
"enforceJWSAuthType",
"(",
"jws",
",",
"embeddedJWK",
")",
";",
"prob",
"!=",
"nil",
"{",
"return",
"nil",
",",
"prob",
"\n",
"}",
"\n",
"header",
":=",
"jws",
".",
"Signatures",
"[",
"0",
"]",
".",
"Header",
"\n",
"key",
":=",
"header",
".",
"JSONWebKey",
"\n",
"if",
"!",
"key",
".",
"Valid",
"(",
")",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"JWKInvalid\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"nil",
",",
"probs",
".",
"Malformed",
"(",
"\"Invalid JWK in JWS header\"",
")",
"\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",
")",
"{",
"expectedURLPrefix",
":=",
"web",
".",
"RelativeEndpoint",
"(",
"request",
",",
"acctPath",
")",
"\n",
"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",
"(",
"\"KeyID header contained an invalid account URL: %q\"",
",",
"acctURL",
")",
")",
"\n",
"}",
"\n",
"accountID",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"accountIDStr",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"probs",
".",
"Malformed",
"(",
"\"Malformed account ID in KeyID header URL: %q\"",
",",
"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",
")",
"{",
"if",
"prob",
":=",
"wfe",
".",
"enforceJWSAuthType",
"(",
"jws",
",",
"embeddedKeyID",
")",
";",
"prob",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"prob",
"\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",
"{",
"\"type\"",
":",
"\"JWSInvalidKeyID\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"prob",
"\n",
"}",
"\n",
"account",
",",
"err",
":=",
"wfe",
".",
"SA",
".",
"GetRegistration",
"(",
"ctx",
",",
"accountID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"berrors",
".",
"Is",
"(",
"err",
",",
"berrors",
".",
"NotFound",
")",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"JWSKeyIDNotFound\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"probs",
".",
"AccountDoesNotExist",
"(",
"\"Account %q not found\"",
",",
"accountURL",
")",
"\n",
"}",
"\n",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"JWSKeyIDLookupFailed\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"logEvent",
".",
"AddError",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Error calling SA.GetRegistration: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"probs",
".",
"ServerInternal",
"(",
"\"Error retreiving account %q\"",
",",
"accountURL",
")",
"\n",
"}",
"\n",
"if",
"account",
".",
"Status",
"!=",
"core",
".",
"StatusValid",
"{",
"wfe",
".",
"stats",
".",
"joseErrorCount",
".",
"With",
"(",
"prometheus",
".",
"Labels",
"{",
"\"type\"",
":",
"\"JWSKeyIDAccountInvalid\"",
"}",
")",
".",
"Inc",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"probs",
".",
"Unauthorized",
"(",
"\"Account is not valid, has status %q\"",
",",
"account",
".",
"Status",
")",
"\n",
"}",
"\n",
"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",
")",
"{",
"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",
")",
"{",
"jws",
",",
"prob",
":=",
"wfe",
".",
"parseJWSRequest",
"(",
"request",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"prob",
"\n",
"}",
"\n",
"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",
"(",
"\"DNS\"",
")",
"\n",
"dnsClient",
":=",
"new",
"(",
"dns",
".",
"Client",
")",
"\n",
"dnsClient",
".",
"ReadTimeout",
"=",
"readTimeout",
"\n",
"dnsClient",
".",
"Net",
"=",
"\"udp\"",
"\n",
"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\"",
"}",
",",
")",
"\n",
"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\"",
"}",
",",
")",
"\n",
"timeoutCounter",
":=",
"prometheus",
".",
"NewCounterVec",
"(",
"prometheus",
".",
"CounterOpts",
"{",
"Name",
":",
"\"dns_timeout\"",
",",
"Help",
":",
"\"Counter of various types of DNS query timeouts\"",
",",
"}",
",",
"[",
"]",
"string",
"{",
"\"qtype\"",
",",
"\"type\"",
",",
"\"resolver\"",
"}",
",",
")",
"\n",
"stats",
".",
"MustRegister",
"(",
"queryTime",
",",
"totalLookupTime",
",",
"timeoutCounter",
")",
"\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",
"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",
"authorities",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"r",
".",
"Ns",
"{",
"authorities",
"=",
"append",
"(",
"authorities",
",",
"a",
".",
"String",
"(",
")",
")",
"\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",
"if",
"r",
".",
"Rcode",
"==",
"dns",
".",
"RcodeServerFailure",
"{",
"return",
"nil",
",",
"&",
"DNSError",
"{",
"dnsType",
",",
"hostname",
",",
"nil",
",",
"r",
".",
"Rcode",
"}",
"\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",
"var",
"results",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"answer",
":=",
"range",
"r",
".",
"Answer",
"{",
"if",
"mx",
",",
"ok",
":=",
"answer",
".",
"(",
"*",
"dns",
".",
"MX",
")",
";",
"ok",
"{",
"results",
"=",
"append",
"(",
"results",
",",
"mx",
".",
"Mx",
")",
"\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",
"{",
"expSlice",
":=",
"big",
".",
"NewInt",
"(",
"int64",
"(",
"exponent",
")",
")",
".",
"Bytes",
"(",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"\\tEncoded public exponent (%d) as: %0X\\n\"",
",",
"\\t",
",",
"\\n",
")",
"\n",
"exponent",
"\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",
"(",
"\"returned CKA_PUBLIC_EXPONENT doesn't match expected exponent\"",
")",
"\n",
"}",
"\n",
"if",
"pubKey",
".",
"N",
".",
"BitLen",
"(",
")",
"!=",
"int",
"(",
"modulusLen",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"returned CKA_MODULUS isn't of the expected bit length\"",
")",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"\\tPublic exponent: %d\\n\"",
",",
"\\t",
")",
"\n",
"\\n",
"\n",
"pubKey",
".",
"E",
"\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",
"(",
"\"Failed to retrieve nonce: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"\\tConstructed nonce: %d (%X)\\n\"",
",",
"\\t",
",",
"\\n",
")",
"\n",
"big",
".",
"NewInt",
"(",
"0",
")",
".",
"SetBytes",
"(",
"nonce",
")",
"\n",
"nonce",
"\n",
"digest",
":=",
"sha256",
".",
"Sum256",
"(",
"nonce",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"\\tMessage SHA-256 hash: %X\\n\"",
",",
"\\t",
")",
"\n",
"\\n",
"\n",
"digest",
"\n",
"signature",
",",
"err",
":=",
"pkcs11helpers",
".",
"Sign",
"(",
"ctx",
",",
"session",
",",
"object",
",",
"pkcs11helpers",
".",
"RSAKey",
",",
"digest",
"[",
":",
"]",
",",
"crypto",
".",
"SHA256",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Failed to sign data: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"\\tMessage signature: %X\\n\"",
",",
"\\t",
")",
"\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",
"(",
"\"Generating RSA key with %d bit modulus and public exponent %d and ID %x\\n\"",
",",
"\\n",
",",
"modulusLen",
",",
"pubExponent",
")",
"\n",
"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",
"(",
"\"Key generated\"",
")",
"\n",
"log",
".",
"Println",
"(",
"\"Extracting public key\"",
")",
"\n",
"pk",
",",
"err",
":=",
"rsaPub",
"(",
"ctx",
",",
"session",
",",
"pub",
",",
"modulusLen",
",",
"pubExponent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"\"Extracted public key\"",
")",
"\n",
"log",
".",
"Println",
"(",
"\"Verifying public key\"",
")",
"\n",
"err",
"=",
"rsaVerify",
"(",
"ctx",
",",
"session",
",",
"priv",
",",
"pk",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\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",
"(",
"\"Attempted to use a nil System Logger.\"",
")",
"\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",
"(",
")",
"{",
"const",
"defaultPriority",
"=",
"syslog",
".",
"LOG_INFO",
"|",
"syslog",
".",
"LOG_LOCAL0",
"\n",
"syslogger",
",",
"err",
":=",
"syslog",
".",
"Dial",
"(",
"\"\"",
",",
"\"\"",
",",
"defaultPriority",
",",
"\"test\"",
")",
"\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",
"_",
"=",
"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",
"(",
"\"You may not call Set after it has already been implicitly or explicitly set.\"",
")",
"\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",
"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",
"const",
"red",
"=",
"\"\\033[31m\\033[1m\"",
"\n",
"\\033",
"\n",
"\\033",
"\n",
"const",
"yellow",
"=",
"\"\\033[33m\"",
"\n",
"\\033",
"\n",
"switch",
"syslogAllowed",
":=",
"int",
"(",
"level",
")",
"<=",
"w",
".",
"syslogLevel",
";",
"level",
"{",
"case",
"syslog",
".",
"LOG_ERR",
":",
"if",
"syslogAllowed",
"{",
"err",
"=",
"w",
".",
"Err",
"(",
"msg",
")",
"\n",
"}",
"\n",
"prefix",
"=",
"red",
"+",
"\"E\"",
"\n",
"case",
"syslog",
".",
"LOG_WARNING",
":",
"if",
"syslogAllowed",
"{",
"err",
"=",
"w",
".",
"Warning",
"(",
"msg",
")",
"\n",
"}",
"\n",
"prefix",
"=",
"yellow",
"+",
"\"W\"",
"\n",
"case",
"syslog",
".",
"LOG_INFO",
":",
"if",
"syslogAllowed",
"{",
"err",
"=",
"w",
".",
"Info",
"(",
"msg",
")",
"\n",
"}",
"\n",
"prefix",
"=",
"\"I\"",
"\n",
"case",
"syslog",
".",
"LOG_DEBUG",
":",
"if",
"syslogAllowed",
"{",
"err",
"=",
"w",
".",
"Debug",
"(",
"msg",
")",
"\n",
"}",
"\n",
"prefix",
"=",
"\"D\"",
"\n",
"default",
":",
"err",
"=",
"w",
".",
"Err",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s (unknown logging level: %d)\"",
",",
"msg",
",",
"int",
"(",
"level",
")",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"Failed to write to syslog: %s (%s)\\n\"",
",",
"\\n",
",",
"msg",
")",
"\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",
"(",
"\"%s:%d:\"",
",",
"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",
"(",
"\"Panic caused by err: %s\"",
",",
"err",
")",
"\n",
"runtime",
".",
"Stack",
"(",
"buf",
",",
"false",
")",
"\n",
"log",
".",
"AuditErrf",
"(",
"\"Stack Trace (Current frame) %s\"",
",",
"buf",
")",
"\n",
"runtime",
".",
"Stack",
"(",
"buf",
",",
"true",
")",
"\n",
"log",
".",
"Warningf",
"(",
"\"Stack Trace (All frames): %s\"",
",",
"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",
"(",
"\"Object could not be serialized to JSON. Raw: %+v\"",
",",
"obj",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"log",
".",
"auditAtLevel",
"(",
"syslog",
".",
"LOG_INFO",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s JSON=%s\"",
",",
"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",
"(",
"\"%v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"recordsStr",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"&",
"records",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"probs",
".",
"CAA",
"(",
"\"CAA records for %s were malformed\"",
",",
"identifier",
".",
"Value",
")",
"\n",
"}",
"\n",
"accountID",
",",
"challengeType",
":=",
"\"unknown\"",
",",
"\"unknown\"",
"\n",
"if",
"params",
".",
"accountURIID",
"!=",
"nil",
"{",
"accountID",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%d\"",
",",
"*",
"params",
".",
"accountURIID",
")",
"\n",
"}",
"\n",
"if",
"params",
".",
"validationMethod",
"!=",
"nil",
"{",
"challengeType",
"=",
"*",
"params",
".",
"validationMethod",
"\n",
"}",
"\n",
"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",
")",
"\n",
"if",
"!",
"valid",
"{",
"return",
"probs",
".",
"CAA",
"(",
"\"CAA record for %s prevents issuance\"",
",",
"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",
"{",
"if",
"(",
"caaRecord",
".",
"Flag",
"&",
"(",
"128",
"|",
"1",
")",
")",
"!=",
"0",
"{",
"return",
"true",
"\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",
"for",
"_",
",",
"caaRecord",
":=",
"range",
"CAAs",
"{",
"switch",
"strings",
".",
"ToLower",
"(",
"caaRecord",
".",
"Tag",
")",
"{",
"case",
"\"issue\"",
":",
"filtered",
".",
"Issue",
"=",
"append",
"(",
"filtered",
".",
"Issue",
",",
"caaRecord",
")",
"\n",
"case",
"\"issuewild\"",
":",
"filtered",
".",
"Issuewild",
"=",
"append",
"(",
"filtered",
".",
"Issuewild",
",",
"caaRecord",
")",
"\n",
"case",
"\"iodef\"",
":",
"filtered",
".",
"Iodef",
"=",
"append",
"(",
"filtered",
".",
"Iodef",
",",
"caaRecord",
")",
"\n",
"default",
":",
"filtered",
".",
"Unknown",
"=",
"append",
"(",
"filtered",
".",
"Unknown",
",",
"caaRecord",
")",
"\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",
"(",
"\"%s%d\"",
",",
"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",
"(",
"\"Error reading random bytes: %s\"",
",",
"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",
")",
"\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",
"(",
"\"Cannot compute digest of nil key\"",
")",
"\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",
"(",
"\"Problem marshaling public key: %s\"",
",",
"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",
"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",
"(",
"\"One or more nil arguments to PublicKeysEqual\"",
")",
"\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",
"{",
"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",
"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",
"!=",
"\"CERTIFICATE\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Block has invalid type: %s\"",
",",
"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",
"if",
"len",
"(",
"bundle",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Bundle doesn't contain any certificates\"",
")",
"\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",
"(",
"\"No data in cert PEM file %s\"",
",",
"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",
",",
"pseudoRNG",
":",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"99",
")",
")",
",",
"}",
"\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",
",",
"\".json\"",
")",
"{",
"loadHandler",
"=",
"pa",
".",
"loadHostnamePolicy",
"(",
"json",
".",
"Unmarshal",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasSuffix",
"(",
"f",
",",
"\".yml\"",
")",
"||",
"strings",
".",
"HasSuffix",
"(",
"f",
",",
"\".yaml\"",
")",
"{",
"loadHandler",
"=",
"pa",
".",
"loadHostnamePolicy",
"(",
"yaml",
".",
"Unmarshal",
")",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Hostname policy file %q has unknown extension. Supported: .yml,.yaml,.json\"",
",",
"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",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"v",
",",
"\".\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"<",
"2",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Malformed ExactBlockedNames entry, only one label: %q\"",
",",
"v",
")",
"\n",
"}",
"\n",
"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",
"if",
"pa",
".",
"blocklist",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Hostname policy not yet loaded.\"",
")",
"\n",
"}",
"\n",
"if",
"pa",
".",
"wildcardExactBlocklist",
"[",
"domain",
"]",
"{",
"return",
"errPolicyForbidden",
"\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",
"var",
"token",
"string",
"\n",
"if",
"features",
".",
"Enabled",
"(",
"features",
".",
"NewAuthorizationSchema",
")",
"{",
"token",
"=",
"core",
".",
"NewToken",
"(",
")",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"identifier",
".",
"Value",
",",
"\"*.\"",
")",
"{",
"if",
"!",
"pa",
".",
"ChallengeTypeEnabled",
"(",
"core",
".",
"ChallengeTypeDNS01",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Challenges requested for wildcard identifier but DNS-01 \"",
"+",
"\"challenge type is not enabled\"",
")",
"\n",
"}",
"\n",
"challenges",
"=",
"[",
"]",
"core",
".",
"Challenge",
"{",
"core",
".",
"DNSChallenge01",
"(",
"token",
")",
"}",
"\n",
"}",
"else",
"{",
"if",
"pa",
".",
"ChallengeTypeEnabled",
"(",
"core",
".",
"ChallengeTypeHTTP01",
")",
"{",
"challenges",
"=",
"append",
"(",
"challenges",
",",
"core",
".",
"HTTPChallenge01",
"(",
"token",
")",
")",
"\n",
"}",
"\n",
"if",
"pa",
".",
"ChallengeTypeEnabled",
"(",
"core",
".",
"ChallengeTypeTLSALPN01",
")",
"{",
"challenges",
"=",
"append",
"(",
"challenges",
",",
"core",
".",
"TLSALPNChallenge01",
"(",
"token",
")",
")",
"\n",
"}",
"\n",
"if",
"pa",
".",
"ChallengeTypeEnabled",
"(",
"core",
".",
"ChallengeTypeDNS01",
")",
"{",
"challenges",
"=",
"append",
"(",
"challenges",
",",
"core",
".",
"DNSChallenge01",
"(",
"token",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"shuffled",
":=",
"make",
"(",
"[",
"]",
"core",
".",
"Challenge",
",",
"len",
"(",
"challenges",
")",
")",
"\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",
"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",
"(",
"\"NonceService\"",
")",
"\n",
"key",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"16",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"c",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"\"Failure in NewCipher: \"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"gcm",
",",
"err",
":=",
"cipher",
".",
"NewGCM",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"\"Failure in NewGCM: \"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\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",
"(",
"\"Generated\"",
",",
"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",
"(",
"\"Invalid.Decrypt\"",
",",
"1",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"ns",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ns",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"c",
">",
"ns",
".",
"latest",
"{",
"ns",
".",
"stats",
".",
"Inc",
"(",
"\"Invalid.TooHigh\"",
",",
"1",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"if",
"c",
"<=",
"ns",
".",
"earliest",
"{",
"ns",
".",
"stats",
".",
"Inc",
"(",
"\"Invalid.TooLow\"",
",",
"1",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"if",
"ns",
".",
"used",
"[",
"c",
"]",
"{",
"ns",
".",
"stats",
".",
"Inc",
"(",
"\"Invalid.AlreadyUsed\"",
",",
"1",
")",
"\n",
"return",
"false",
"\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",
"(",
"\"Heap.Latency\"",
",",
"time",
".",
"Since",
"(",
"s",
")",
")",
"\n",
"delete",
"(",
"ns",
".",
"used",
",",
"ns",
".",
"earliest",
")",
"\n",
"}",
"\n",
"ns",
".",
"stats",
".",
"Inc",
"(",
"\"Valid\"",
",",
"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",
"winnerCounter",
":=",
"prometheus",
".",
"NewCounterVec",
"(",
"prometheus",
".",
"CounterOpts",
"{",
"Name",
":",
"\"sct_race_winner\"",
",",
"Help",
":",
"\"Counter of logs that win SCT submission races.\"",
",",
"}",
",",
"[",
"]",
"string",
"{",
"\"log\"",
",",
"\"group\"",
"}",
",",
")",
"\n",
"stats",
".",
"MustRegister",
"(",
"winnerCounter",
")",
"\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",
"if",
"err",
"!=",
"nil",
"{",
"results",
"<-",
"result",
"{",
"err",
":",
"berrors",
".",
"MissingSCTsError",
"(",
"\"CT log group %q: %s\"",
",",
"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",
")",
"{",
"uri",
",",
"key",
",",
"err",
":=",
"l",
".",
"Info",
"(",
"expiration",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctp",
".",
"log",
".",
"Errf",
"(",
"\"unable to get log info: %s\"",
",",
"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",
"(",
"\"ct submission to informational log %q failed: %s\"",
",",
"uri",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
"log",
")",
"\n",
"}",
"\n",
"var",
"ret",
"core",
".",
"SCTDERs",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"ctp",
".",
"groups",
")",
";",
"i",
"++",
"{",
"res",
":=",
"<-",
"results",
"\n",
"if",
"res",
".",
"err",
"!=",
"nil",
"{",
"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",
"(",
"\"unable to get log info: %s\"",
",",
"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",
"(",
"\"ct submission of final cert to log %q failed: %s\"",
",",
"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",
"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",
":=",
"\"http\"",
"\n",
"if",
"request",
".",
"TLS",
"!=",
"nil",
"{",
"proto",
"=",
"\"https\"",
"\n",
"}",
"\n",
"if",
"specifiedProto",
":=",
"request",
".",
"Header",
".",
"Get",
"(",
"\"X-Forwarded-Proto\"",
")",
";",
"specifiedProto",
"!=",
"\"\"",
"{",
"proto",
"=",
"specifiedProto",
"\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",
"if",
"features",
".",
"Enabled",
"(",
"features",
".",
"HeadNonceStatusOK",
")",
"&&",
"request",
".",
"Method",
"==",
"\"HEAD\"",
"{",
"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",
"{",
"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",
"(",
"\"Unable to JSON parse revoke request\"",
")",
"\n",
"}",
"\n",
"providedCert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"revokeRequest",
".",
"CertificateDER",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"probs",
".",
"Malformed",
"(",
"\"Unable to parse certificate DER\"",
")",
"\n",
"}",
"\n",
"serial",
":=",
"core",
".",
"SerialToString",
"(",
"providedCert",
".",
"SerialNumber",
")",
"\n",
"logEvent",
".",
"Extra",
"[",
"\"ProvidedCertificateSerial\"",
"]",
"=",
"serial",
"\n",
"cert",
",",
"err",
":=",
"wfe",
".",
"SA",
".",
"GetCertificate",
"(",
"ctx",
",",
"serial",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"!",
"bytes",
".",
"Equal",
"(",
"cert",
".",
"DER",
",",
"revokeRequest",
".",
"CertificateDER",
")",
"{",
"return",
"probs",
".",
"NotFound",
"(",
"\"No such certificate\"",
")",
"\n",
"}",
"\n",
"parsedCertificate",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"cert",
".",
"DER",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"probs",
".",
"ServerInternal",
"(",
"\"invalid parse of stored certificate\"",
")",
"\n",
"}",
"\n",
"logEvent",
".",
"Extra",
"[",
"\"RetrievedCertificateSerial\"",
"]",
"=",
"core",
".",
"SerialToString",
"(",
"parsedCertificate",
".",
"SerialNumber",
")",
"\n",
"logEvent",
".",
"Extra",
"[",
"\"RetrievedCertificateDNSNames\"",
"]",
"=",
"parsedCertificate",
".",
"DNSNames",
"\n",
"if",
"parsedCertificate",
".",
"NotAfter",
".",
"Before",
"(",
"wfe",
".",
"clk",
".",
"Now",
"(",
")",
")",
"{",
"return",
"probs",
".",
"Unauthorized",
"(",
"\"Certificate is expired\"",
")",
"\n",
"}",
"\n",
"certStatus",
",",
"err",
":=",
"wfe",
".",
"SA",
".",
"GetCertificateStatus",
"(",
"ctx",
",",
"serial",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"probs",
".",
"NotFound",
"(",
"\"Certificate status not yet available\"",
")",
"\n",
"}",
"\n",
"logEvent",
".",
"Extra",
"[",
"\"CertificateStatus\"",
"]",
"=",
"certStatus",
".",
"Status",
"\n",
"if",
"certStatus",
".",
"Status",
"==",
"core",
".",
"OCSPStatusRevoked",
"{",
"return",
"probs",
".",
"AlreadyRevoked",
"(",
"\"Certificate already revoked\"",
")",
"\n",
"}",
"\n",
"prob",
":=",
"authorizedToRevoke",
"(",
"parsedCertificate",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"return",
"prob",
"\n",
"}",
"\n",
"reason",
":=",
"revocation",
".",
"Reason",
"(",
"0",
")",
"\n",
"if",
"revokeRequest",
".",
"Reason",
"!=",
"nil",
"&&",
"wfe",
".",
"AcceptRevocationReason",
"{",
"if",
"_",
",",
"present",
":=",
"revocation",
".",
"UserAllowedReasons",
"[",
"*",
"revokeRequest",
".",
"Reason",
"]",
";",
"!",
"present",
"{",
"return",
"probs",
".",
"Malformed",
"(",
"\"unsupported revocation reason code provided\"",
")",
"\n",
"}",
"\n",
"reason",
"=",
"*",
"revokeRequest",
".",
"Reason",
"\n",
"}",
"\n",
"if",
"err",
":=",
"wfe",
".",
"RA",
".",
"RevokeCertificateWithReg",
"(",
"ctx",
",",
"*",
"parsedCertificate",
",",
"reason",
",",
"acctID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"web",
".",
"ProblemDetailsForError",
"(",
"err",
",",
"\"Failed to revoke certificate\"",
")",
"\n",
"}",
"\n",
"wfe",
".",
"log",
".",
"Debugf",
"(",
"\"Revoked %v\"",
",",
"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",
"{",
"jwsBody",
",",
"_",
",",
"acct",
",",
"prob",
":=",
"wfe",
".",
"validJWSForAccount",
"(",
"outerJWS",
",",
"request",
",",
"ctx",
",",
"logEvent",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"return",
"prob",
"\n",
"}",
"\n",
"authorizedToRevoke",
":=",
"func",
"(",
"parsedCertificate",
"*",
"x509",
".",
"Certificate",
")",
"*",
"probs",
".",
"ProblemDetails",
"{",
"cert",
",",
"err",
":=",
"wfe",
".",
"SA",
".",
"GetCertificate",
"(",
"ctx",
",",
"core",
".",
"SerialToString",
"(",
"parsedCertificate",
".",
"SerialNumber",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"probs",
".",
"ServerInternal",
"(",
"\"Failed to retrieve certificate\"",
")",
"\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",
"(",
"\"Failed to retrieve authorizations for names in certificate\"",
")",
"\n",
"}",
"\n",
"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\"",
")",
"\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",
"{",
"var",
"requestKey",
"*",
"jose",
".",
"JSONWebKey",
"\n",
"jwsBody",
",",
"jwk",
",",
"prob",
":=",
"wfe",
".",
"validSelfAuthenticatedJWS",
"(",
"outerJWS",
",",
"request",
",",
"logEvent",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"return",
"prob",
"\n",
"}",
"\n",
"requestKey",
"=",
"jwk",
"\n",
"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\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"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",
")",
"{",
"jws",
",",
"prob",
":=",
"wfe",
".",
"parseJWSRequest",
"(",
"request",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"prob",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"authType",
",",
"prob",
":=",
"checkJWSAuthType",
"(",
"jws",
")",
"\n",
"if",
"prob",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"prob",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"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",
"(",
"\"Malformed JWS, no KeyID or embedded JWK\"",
")",
"\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",
")",
"{",
"if",
"authz",
".",
"V2",
"{",
"challenge",
".",
"URL",
"=",
"web",
".",
"RelativeEndpoint",
"(",
"request",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%sv2/%s/%s\"",
",",
"challengePath",
",",
"authz",
".",
"ID",
",",
"challenge",
".",
"StringID",
"(",
")",
")",
")",
"\n",
"}",
"else",
"{",
"challenge",
".",
"URL",
"=",
"web",
".",
"RelativeEndpoint",
"(",
"request",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s%s/%d\"",
",",
"challengePath",
",",
"authz",
".",
"ID",
",",
"challenge",
".",
"ID",
")",
")",
"\n",
"}",
"\n",
"challenge",
".",
"URI",
"=",
"\"\"",
"\n",
"challenge",
".",
"ID",
"=",
"0",
"\n",
"challenge",
".",
"ProvidedKeyAuthorization",
"=",
"\"\"",
"\n",
"if",
"challenge",
".",
"Error",
"!=",
"nil",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"string",
"(",
"challenge",
".",
"Error",
".",
"Type",
")",
",",
"probs",
".",
"V1ErrorNS",
")",
"{",
"challenge",
".",
"Error",
".",
"Type",
"=",
"probs",
".",
"V2ErrorNS",
"+",
"challenge",
".",
"Error",
".",
"Type",
"\n",
"}",
"\n",
"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",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"prob",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"idStr",
":=",
"request",
".",
"URL",
".",
"Path",
"\n",
"id",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"idStr",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Malformed",
"(",
"\"Account ID must be an integer\"",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"else",
"if",
"id",
"<=",
"0",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"Account ID must be a positive non-zero integer, was %d\"",
",",
"id",
")",
"\n",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Malformed",
"(",
"msg",
")",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"else",
"if",
"id",
"!=",
"currAcct",
".",
"ID",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"Unauthorized",
"(",
"\"Request signing key did not match account key\"",
")",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"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",
"if",
"len",
"(",
"wfe",
".",
"SubscriberAgreementURL",
")",
">",
"0",
"{",
"response",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"Link\"",
",",
"link",
"(",
"wfe",
".",
"SubscriberAgreementURL",
",",
"\"terms-of-service\"",
")",
")",
"\n",
"}",
"\n",
"currAcct",
".",
"Agreement",
"=",
"\"\"",
"\n",
"err",
"=",
"wfe",
".",
"writeJsonResponse",
"(",
"response",
",",
"logEvent",
",",
"http",
".",
"StatusOK",
",",
"currAcct",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"sendError",
"(",
"response",
",",
"logEvent",
",",
"probs",
".",
"ServerInternal",
"(",
"\"Failed to marshal account\"",
")",
",",
"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",
")",
"{",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"application/pkix-cert\"",
")",
"\n",
"response",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"response",
".",
"Write",
"(",
"wfe",
".",
"IssuerCert",
")",
";",
"err",
"!=",
"nil",
"{",
"wfe",
".",
"log",
".",
"Warningf",
"(",
"\"Could not write response: %s\"",
",",
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.