repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
letsencrypt/boulder
mocks/ca.go
IssuePrecertificate
func (ca *MockCA) IssuePrecertificate(ctx context.Context, _ *caPB.IssueCertificateRequest) (*caPB.IssuePrecertificateResponse, error) { if ca.PEM == nil { return nil, fmt.Errorf("MockCA's PEM field must be set before calling IssueCertificate") } block, _ := pem.Decode(ca.PEM) cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, err } return &caPB.IssuePrecertificateResponse{ DER: cert.Raw, }, nil }
go
func (ca *MockCA) IssuePrecertificate(ctx context.Context, _ *caPB.IssueCertificateRequest) (*caPB.IssuePrecertificateResponse, error) { if ca.PEM == nil { return nil, fmt.Errorf("MockCA's PEM field must be set before calling IssueCertificate") } block, _ := pem.Decode(ca.PEM) cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, err } return &caPB.IssuePrecertificateResponse{ DER: cert.Raw, }, nil }
[ "func", "(", "ca", "*", "MockCA", ")", "IssuePrecertificate", "(", "ctx", "context", ".", "Context", ",", "_", "*", "caPB", ".", "IssueCertificateRequest", ")", "(", "*", "caPB", ".", "IssuePrecertificateResponse", ",", "error", ")", "{", "if", "ca", ".", "PEM", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "ca", ".", "PEM", ")", "\n", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "block", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "caPB", ".", "IssuePrecertificateResponse", "{", "DER", ":", "cert", ".", "Raw", ",", "}", ",", "nil", "\n", "}" ]
// IssuePrecertificate is a mock
[ "IssuePrecertificate", "is", "a", "mock" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/mocks/ca.go#L37-L49
train
letsencrypt/boulder
mocks/ca.go
IssueCertificateForPrecertificate
func (ca *MockCA) IssueCertificateForPrecertificate(ctx context.Context, req *caPB.IssueCertificateForPrecertificateRequest) (core.Certificate, error) { return core.Certificate{DER: req.DER}, nil }
go
func (ca *MockCA) IssueCertificateForPrecertificate(ctx context.Context, req *caPB.IssueCertificateForPrecertificateRequest) (core.Certificate, error) { return core.Certificate{DER: req.DER}, nil }
[ "func", "(", "ca", "*", "MockCA", ")", "IssueCertificateForPrecertificate", "(", "ctx", "context", ".", "Context", ",", "req", "*", "caPB", ".", "IssueCertificateForPrecertificateRequest", ")", "(", "core", ".", "Certificate", ",", "error", ")", "{", "return", "core", ".", "Certificate", "{", "DER", ":", "req", ".", "DER", "}", ",", "nil", "\n", "}" ]
// IssueCertificateForPrecertificate is a mock
[ "IssueCertificateForPrecertificate", "is", "a", "mock" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/mocks/ca.go#L52-L54
train
letsencrypt/boulder
mocks/ca.go
GenerateOCSP
func (ca *MockCA) GenerateOCSP(ctx context.Context, xferObj core.OCSPSigningRequest) (ocsp []byte, err error) { return }
go
func (ca *MockCA) GenerateOCSP(ctx context.Context, xferObj core.OCSPSigningRequest) (ocsp []byte, err error) { return }
[ "func", "(", "ca", "*", "MockCA", ")", "GenerateOCSP", "(", "ctx", "context", ".", "Context", ",", "xferObj", "core", ".", "OCSPSigningRequest", ")", "(", "ocsp", "[", "]", "byte", ",", "err", "error", ")", "{", "return", "\n", "}" ]
// GenerateOCSP is a mock
[ "GenerateOCSP", "is", "a", "mock" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/mocks/ca.go#L57-L59
train
letsencrypt/boulder
va/tlsalpn.go
tlsDial
func (va *ValidationAuthorityImpl) tlsDial(ctx context.Context, hostPort string, config *tls.Config) (*tls.Conn, error) { ctx, cancel := context.WithTimeout(ctx, va.singleDialTimeout) defer cancel() dialer := &net.Dialer{} netConn, err := dialer.DialContext(ctx, "tcp", hostPort) if err != nil { return nil, err } deadline, ok := ctx.Deadline() if !ok { va.log.AuditErr("tlsDial was called without a deadline") return nil, fmt.Errorf("tlsDial was called without a deadline") } _ = netConn.SetDeadline(deadline) conn := tls.Client(netConn, config) err = conn.Handshake() if err != nil { return nil, err } return conn, nil }
go
func (va *ValidationAuthorityImpl) tlsDial(ctx context.Context, hostPort string, config *tls.Config) (*tls.Conn, error) { ctx, cancel := context.WithTimeout(ctx, va.singleDialTimeout) defer cancel() dialer := &net.Dialer{} netConn, err := dialer.DialContext(ctx, "tcp", hostPort) if err != nil { return nil, err } deadline, ok := ctx.Deadline() if !ok { va.log.AuditErr("tlsDial was called without a deadline") return nil, fmt.Errorf("tlsDial was called without a deadline") } _ = netConn.SetDeadline(deadline) conn := tls.Client(netConn, config) err = conn.Handshake() if err != nil { return nil, err } return conn, nil }
[ "func", "(", "va", "*", "ValidationAuthorityImpl", ")", "tlsDial", "(", "ctx", "context", ".", "Context", ",", "hostPort", "string", ",", "config", "*", "tls", ".", "Config", ")", "(", "*", "tls", ".", "Conn", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "va", ".", "singleDialTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "dialer", ":=", "&", "net", ".", "Dialer", "{", "}", "\n", "netConn", ",", "err", ":=", "dialer", ".", "DialContext", "(", "ctx", ",", "\"", "\"", ",", "hostPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "deadline", ",", "ok", ":=", "ctx", ".", "Deadline", "(", ")", "\n", "if", "!", "ok", "{", "va", ".", "log", ".", "AuditErr", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "_", "=", "netConn", ".", "SetDeadline", "(", "deadline", ")", "\n", "conn", ":=", "tls", ".", "Client", "(", "netConn", ",", "config", ")", "\n", "err", "=", "conn", ".", "Handshake", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}" ]
// tlsDial does the equivalent of tls.Dial, but obeying a context. Once // tls.DialContextWithDialer is available, switch to that.
[ "tlsDial", "does", "the", "equivalent", "of", "tls", ".", "Dial", "but", "obeying", "a", "context", ".", "Once", "tls", ".", "DialContextWithDialer", "is", "available", "switch", "to", "that", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/tlsalpn.go#L154-L174
train
letsencrypt/boulder
va/va.go
NewValidationAuthorityImpl
func NewValidationAuthorityImpl( pc *cmd.PortConfig, resolver bdns.DNSClient, remoteVAs []RemoteVA, maxRemoteFailures int, userAgent string, issuerDomain string, stats metrics.Scope, clk clock.Clock, logger blog.Logger, accountURIPrefixes []string, ) (*ValidationAuthorityImpl, error) { if pc.HTTPPort == 0 { pc.HTTPPort = 80 } if pc.HTTPSPort == 0 { pc.HTTPSPort = 443 } if pc.TLSPort == 0 { pc.TLSPort = 443 } if features.Enabled(features.CAAAccountURI) && len(accountURIPrefixes) == 0 { return nil, errors.New("no account URI prefixes configured") } return &ValidationAuthorityImpl{ log: logger, dnsClient: resolver, issuerDomain: issuerDomain, httpPort: pc.HTTPPort, httpsPort: pc.HTTPSPort, tlsPort: pc.TLSPort, userAgent: userAgent, stats: stats, clk: clk, metrics: initMetrics(stats), remoteVAs: remoteVAs, maxRemoteFailures: maxRemoteFailures, accountURIPrefixes: accountURIPrefixes, // singleDialTimeout specifies how long an individual `DialContext` operation may take // before timing out. This timeout ignores the base RPC timeout and is strictly // used for the DialContext operations that take place during an // HTTP-01 challenge validation. singleDialTimeout: 10 * time.Second, }, nil }
go
func NewValidationAuthorityImpl( pc *cmd.PortConfig, resolver bdns.DNSClient, remoteVAs []RemoteVA, maxRemoteFailures int, userAgent string, issuerDomain string, stats metrics.Scope, clk clock.Clock, logger blog.Logger, accountURIPrefixes []string, ) (*ValidationAuthorityImpl, error) { if pc.HTTPPort == 0 { pc.HTTPPort = 80 } if pc.HTTPSPort == 0 { pc.HTTPSPort = 443 } if pc.TLSPort == 0 { pc.TLSPort = 443 } if features.Enabled(features.CAAAccountURI) && len(accountURIPrefixes) == 0 { return nil, errors.New("no account URI prefixes configured") } return &ValidationAuthorityImpl{ log: logger, dnsClient: resolver, issuerDomain: issuerDomain, httpPort: pc.HTTPPort, httpsPort: pc.HTTPSPort, tlsPort: pc.TLSPort, userAgent: userAgent, stats: stats, clk: clk, metrics: initMetrics(stats), remoteVAs: remoteVAs, maxRemoteFailures: maxRemoteFailures, accountURIPrefixes: accountURIPrefixes, // singleDialTimeout specifies how long an individual `DialContext` operation may take // before timing out. This timeout ignores the base RPC timeout and is strictly // used for the DialContext operations that take place during an // HTTP-01 challenge validation. singleDialTimeout: 10 * time.Second, }, nil }
[ "func", "NewValidationAuthorityImpl", "(", "pc", "*", "cmd", ".", "PortConfig", ",", "resolver", "bdns", ".", "DNSClient", ",", "remoteVAs", "[", "]", "RemoteVA", ",", "maxRemoteFailures", "int", ",", "userAgent", "string", ",", "issuerDomain", "string", ",", "stats", "metrics", ".", "Scope", ",", "clk", "clock", ".", "Clock", ",", "logger", "blog", ".", "Logger", ",", "accountURIPrefixes", "[", "]", "string", ",", ")", "(", "*", "ValidationAuthorityImpl", ",", "error", ")", "{", "if", "pc", ".", "HTTPPort", "==", "0", "{", "pc", ".", "HTTPPort", "=", "80", "\n", "}", "\n", "if", "pc", ".", "HTTPSPort", "==", "0", "{", "pc", ".", "HTTPSPort", "=", "443", "\n", "}", "\n", "if", "pc", ".", "TLSPort", "==", "0", "{", "pc", ".", "TLSPort", "=", "443", "\n", "}", "\n\n", "if", "features", ".", "Enabled", "(", "features", ".", "CAAAccountURI", ")", "&&", "len", "(", "accountURIPrefixes", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "ValidationAuthorityImpl", "{", "log", ":", "logger", ",", "dnsClient", ":", "resolver", ",", "issuerDomain", ":", "issuerDomain", ",", "httpPort", ":", "pc", ".", "HTTPPort", ",", "httpsPort", ":", "pc", ".", "HTTPSPort", ",", "tlsPort", ":", "pc", ".", "TLSPort", ",", "userAgent", ":", "userAgent", ",", "stats", ":", "stats", ",", "clk", ":", "clk", ",", "metrics", ":", "initMetrics", "(", "stats", ")", ",", "remoteVAs", ":", "remoteVAs", ",", "maxRemoteFailures", ":", "maxRemoteFailures", ",", "accountURIPrefixes", ":", "accountURIPrefixes", ",", "// singleDialTimeout specifies how long an individual `DialContext` operation may take", "// before timing out. This timeout ignores the base RPC timeout and is strictly", "// used for the DialContext operations that take place during an", "// HTTP-01 challenge validation.", "singleDialTimeout", ":", "10", "*", "time", ".", "Second", ",", "}", ",", "nil", "\n", "}" ]
// NewValidationAuthorityImpl constructs a new VA
[ "NewValidationAuthorityImpl", "constructs", "a", "new", "VA" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/va.go#L160-L206
train
letsencrypt/boulder
va/va.go
detailedError
func detailedError(err error) *probs.ProblemDetails { // net/http wraps net.OpError in a url.Error. Unwrap them. if urlErr, ok := err.(*url.Error); ok { prob := detailedError(urlErr.Err) prob.Detail = fmt.Sprintf("Fetching %s: %s", urlErr.URL, prob.Detail) return prob } if tlsErr, ok := err.(tls.RecordHeaderError); ok && bytes.Compare(tlsErr.RecordHeader[:], badTLSHeader) == 0 { return probs.Malformed("Server only speaks HTTP, not TLS") } if netErr, ok := err.(*net.OpError); ok { if fmt.Sprintf("%T", netErr.Err) == "tls.alert" { // All the tls.alert error strings are reasonable to hand back to a // user. Confirmed against Go 1.8. return probs.TLSError(netErr.Error()) } else if syscallErr, ok := netErr.Err.(*os.SyscallError); ok && syscallErr.Err == syscall.ECONNREFUSED { return probs.ConnectionFailure("Connection refused") } else if syscallErr, ok := netErr.Err.(*os.SyscallError); ok && syscallErr.Err == syscall.ENETUNREACH { return probs.ConnectionFailure("Network unreachable") } else if syscallErr, ok := netErr.Err.(*os.SyscallError); ok && syscallErr.Err == syscall.ECONNRESET { return probs.ConnectionFailure("Connection reset by peer") } else if netErr.Timeout() && netErr.Op == "dial" { return probs.ConnectionFailure("Timeout during connect (likely firewall problem)") } else if netErr.Timeout() { return probs.ConnectionFailure("Timeout during %s (your server may be slow or overloaded)", netErr.Op) } } if err, ok := err.(net.Error); ok && err.Timeout() { return probs.ConnectionFailure("Timeout after connect (your server may be slow or overloaded)") } if berrors.Is(err, berrors.ConnectionFailure) { return probs.ConnectionFailure(err.Error()) } if berrors.Is(err, berrors.Unauthorized) { return probs.Unauthorized(err.Error()) } if h2SettingsFrameErrRegex.MatchString(err.Error()) { return probs.ConnectionFailure("Server is speaking HTTP/2 over HTTP") } return probs.ConnectionFailure("Error getting validation data") }
go
func detailedError(err error) *probs.ProblemDetails { // net/http wraps net.OpError in a url.Error. Unwrap them. if urlErr, ok := err.(*url.Error); ok { prob := detailedError(urlErr.Err) prob.Detail = fmt.Sprintf("Fetching %s: %s", urlErr.URL, prob.Detail) return prob } if tlsErr, ok := err.(tls.RecordHeaderError); ok && bytes.Compare(tlsErr.RecordHeader[:], badTLSHeader) == 0 { return probs.Malformed("Server only speaks HTTP, not TLS") } if netErr, ok := err.(*net.OpError); ok { if fmt.Sprintf("%T", netErr.Err) == "tls.alert" { // All the tls.alert error strings are reasonable to hand back to a // user. Confirmed against Go 1.8. return probs.TLSError(netErr.Error()) } else if syscallErr, ok := netErr.Err.(*os.SyscallError); ok && syscallErr.Err == syscall.ECONNREFUSED { return probs.ConnectionFailure("Connection refused") } else if syscallErr, ok := netErr.Err.(*os.SyscallError); ok && syscallErr.Err == syscall.ENETUNREACH { return probs.ConnectionFailure("Network unreachable") } else if syscallErr, ok := netErr.Err.(*os.SyscallError); ok && syscallErr.Err == syscall.ECONNRESET { return probs.ConnectionFailure("Connection reset by peer") } else if netErr.Timeout() && netErr.Op == "dial" { return probs.ConnectionFailure("Timeout during connect (likely firewall problem)") } else if netErr.Timeout() { return probs.ConnectionFailure("Timeout during %s (your server may be slow or overloaded)", netErr.Op) } } if err, ok := err.(net.Error); ok && err.Timeout() { return probs.ConnectionFailure("Timeout after connect (your server may be slow or overloaded)") } if berrors.Is(err, berrors.ConnectionFailure) { return probs.ConnectionFailure(err.Error()) } if berrors.Is(err, berrors.Unauthorized) { return probs.Unauthorized(err.Error()) } if h2SettingsFrameErrRegex.MatchString(err.Error()) { return probs.ConnectionFailure("Server is speaking HTTP/2 over HTTP") } return probs.ConnectionFailure("Error getting validation data") }
[ "func", "detailedError", "(", "err", "error", ")", "*", "probs", ".", "ProblemDetails", "{", "// net/http wraps net.OpError in a url.Error. Unwrap them.", "if", "urlErr", ",", "ok", ":=", "err", ".", "(", "*", "url", ".", "Error", ")", ";", "ok", "{", "prob", ":=", "detailedError", "(", "urlErr", ".", "Err", ")", "\n", "prob", ".", "Detail", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "urlErr", ".", "URL", ",", "prob", ".", "Detail", ")", "\n", "return", "prob", "\n", "}", "\n\n", "if", "tlsErr", ",", "ok", ":=", "err", ".", "(", "tls", ".", "RecordHeaderError", ")", ";", "ok", "&&", "bytes", ".", "Compare", "(", "tlsErr", ".", "RecordHeader", "[", ":", "]", ",", "badTLSHeader", ")", "==", "0", "{", "return", "probs", ".", "Malformed", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "netErr", ",", "ok", ":=", "err", ".", "(", "*", "net", ".", "OpError", ")", ";", "ok", "{", "if", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "netErr", ".", "Err", ")", "==", "\"", "\"", "{", "// All the tls.alert error strings are reasonable to hand back to a", "// user. Confirmed against Go 1.8.", "return", "probs", ".", "TLSError", "(", "netErr", ".", "Error", "(", ")", ")", "\n", "}", "else", "if", "syscallErr", ",", "ok", ":=", "netErr", ".", "Err", ".", "(", "*", "os", ".", "SyscallError", ")", ";", "ok", "&&", "syscallErr", ".", "Err", "==", "syscall", ".", "ECONNREFUSED", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"", "\"", ")", "\n", "}", "else", "if", "syscallErr", ",", "ok", ":=", "netErr", ".", "Err", ".", "(", "*", "os", ".", "SyscallError", ")", ";", "ok", "&&", "syscallErr", ".", "Err", "==", "syscall", ".", "ENETUNREACH", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"", "\"", ")", "\n", "}", "else", "if", "syscallErr", ",", "ok", ":=", "netErr", ".", "Err", ".", "(", "*", "os", ".", "SyscallError", ")", ";", "ok", "&&", "syscallErr", ".", "Err", "==", "syscall", ".", "ECONNRESET", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"", "\"", ")", "\n", "}", "else", "if", "netErr", ".", "Timeout", "(", ")", "&&", "netErr", ".", "Op", "==", "\"", "\"", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"", "\"", ")", "\n", "}", "else", "if", "netErr", ".", "Timeout", "(", ")", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"", "\"", ",", "netErr", ".", "Op", ")", "\n", "}", "\n", "}", "\n", "if", "err", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", ";", "ok", "&&", "err", ".", "Timeout", "(", ")", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "berrors", ".", "Is", "(", "err", ",", "berrors", ".", "ConnectionFailure", ")", "{", "return", "probs", ".", "ConnectionFailure", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "berrors", ".", "Is", "(", "err", ",", "berrors", ".", "Unauthorized", ")", "{", "return", "probs", ".", "Unauthorized", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "if", "h2SettingsFrameErrRegex", ".", "MatchString", "(", "err", ".", "Error", "(", ")", ")", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "probs", ".", "ConnectionFailure", "(", "\"", "\"", ")", "\n", "}" ]
// detailedError returns a ProblemDetails corresponding to an error // that occurred during HTTP-01 or TLS-ALPN domain validation. Specifically it // tries to unwrap known Go error types and present something a little more // meaningful. It additionally handles `berrors.ConnectionFailure` errors by // passing through the detailed message.
[ "detailedError", "returns", "a", "ProblemDetails", "corresponding", "to", "an", "error", "that", "occurred", "during", "HTTP", "-", "01", "or", "TLS", "-", "ALPN", "domain", "validation", ".", "Specifically", "it", "tries", "to", "unwrap", "known", "Go", "error", "types", "and", "present", "something", "a", "little", "more", "meaningful", ".", "It", "additionally", "handles", "berrors", ".", "ConnectionFailure", "errors", "by", "passing", "through", "the", "detailed", "message", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/va.go#L223-L270
train
letsencrypt/boulder
va/va.go
validate
func (va *ValidationAuthorityImpl) validate( ctx context.Context, identifier core.AcmeIdentifier, challenge core.Challenge, authz core.Authorization, ) ([]core.ValidationRecord, *probs.ProblemDetails) { // If the identifier is a wildcard domain we need to validate the base // domain by removing the "*." wildcard prefix. We create a separate // `baseIdentifier` here before starting the `va.checkCAA` goroutine with the // `identifier` to avoid a data race. baseIdentifier := identifier if strings.HasPrefix(identifier.Value, "*.") { baseIdentifier.Value = strings.TrimPrefix(identifier.Value, "*.") } // va.checkCAA accepts wildcard identifiers and handles them appropriately so // we can dispatch `checkCAA` with the provided `identifier` instead of // `baseIdentifier` ch := make(chan *probs.ProblemDetails, 1) go func() { params := &caaParams{ accountURIID: &authz.RegistrationID, validationMethod: &challenge.Type, } ch <- va.checkCAA(ctx, identifier, params) }() // TODO(#1292): send into another goroutine validationRecords, err := va.validateChallenge(ctx, baseIdentifier, challenge) if err != nil { return validationRecords, err } for i := 0; i < cap(ch); i++ { if extraProblem := <-ch; extraProblem != nil { return validationRecords, extraProblem } } return validationRecords, nil }
go
func (va *ValidationAuthorityImpl) validate( ctx context.Context, identifier core.AcmeIdentifier, challenge core.Challenge, authz core.Authorization, ) ([]core.ValidationRecord, *probs.ProblemDetails) { // If the identifier is a wildcard domain we need to validate the base // domain by removing the "*." wildcard prefix. We create a separate // `baseIdentifier` here before starting the `va.checkCAA` goroutine with the // `identifier` to avoid a data race. baseIdentifier := identifier if strings.HasPrefix(identifier.Value, "*.") { baseIdentifier.Value = strings.TrimPrefix(identifier.Value, "*.") } // va.checkCAA accepts wildcard identifiers and handles them appropriately so // we can dispatch `checkCAA` with the provided `identifier` instead of // `baseIdentifier` ch := make(chan *probs.ProblemDetails, 1) go func() { params := &caaParams{ accountURIID: &authz.RegistrationID, validationMethod: &challenge.Type, } ch <- va.checkCAA(ctx, identifier, params) }() // TODO(#1292): send into another goroutine validationRecords, err := va.validateChallenge(ctx, baseIdentifier, challenge) if err != nil { return validationRecords, err } for i := 0; i < cap(ch); i++ { if extraProblem := <-ch; extraProblem != nil { return validationRecords, extraProblem } } return validationRecords, nil }
[ "func", "(", "va", "*", "ValidationAuthorityImpl", ")", "validate", "(", "ctx", "context", ".", "Context", ",", "identifier", "core", ".", "AcmeIdentifier", ",", "challenge", "core", ".", "Challenge", ",", "authz", "core", ".", "Authorization", ",", ")", "(", "[", "]", "core", ".", "ValidationRecord", ",", "*", "probs", ".", "ProblemDetails", ")", "{", "// If the identifier is a wildcard domain we need to validate the base", "// domain by removing the \"*.\" wildcard prefix. We create a separate", "// `baseIdentifier` here before starting the `va.checkCAA` goroutine with the", "// `identifier` to avoid a data race.", "baseIdentifier", ":=", "identifier", "\n", "if", "strings", ".", "HasPrefix", "(", "identifier", ".", "Value", ",", "\"", "\"", ")", "{", "baseIdentifier", ".", "Value", "=", "strings", ".", "TrimPrefix", "(", "identifier", ".", "Value", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// va.checkCAA accepts wildcard identifiers and handles them appropriately so", "// we can dispatch `checkCAA` with the provided `identifier` instead of", "// `baseIdentifier`", "ch", ":=", "make", "(", "chan", "*", "probs", ".", "ProblemDetails", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "params", ":=", "&", "caaParams", "{", "accountURIID", ":", "&", "authz", ".", "RegistrationID", ",", "validationMethod", ":", "&", "challenge", ".", "Type", ",", "}", "\n", "ch", "<-", "va", ".", "checkCAA", "(", "ctx", ",", "identifier", ",", "params", ")", "\n", "}", "(", ")", "\n\n", "// TODO(#1292): send into another goroutine", "validationRecords", ",", "err", ":=", "va", ".", "validateChallenge", "(", "ctx", ",", "baseIdentifier", ",", "challenge", ")", "\n", "if", "err", "!=", "nil", "{", "return", "validationRecords", ",", "err", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "cap", "(", "ch", ")", ";", "i", "++", "{", "if", "extraProblem", ":=", "<-", "ch", ";", "extraProblem", "!=", "nil", "{", "return", "validationRecords", ",", "extraProblem", "\n", "}", "\n", "}", "\n", "return", "validationRecords", ",", "nil", "\n", "}" ]
// validate performs a challenge validation and, in parallel, // checks CAA and GSB for the identifier. If any of those steps fails, it // returns a ProblemDetails plus the validation records created during the // validation attempt.
[ "validate", "performs", "a", "challenge", "validation", "and", "in", "parallel", "checks", "CAA", "and", "GSB", "for", "the", "identifier", ".", "If", "any", "of", "those", "steps", "fails", "it", "returns", "a", "ProblemDetails", "plus", "the", "validation", "records", "created", "during", "the", "validation", "attempt", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/va.go#L276-L316
train
letsencrypt/boulder
va/va.go
processRemoteResults
func (va *ValidationAuthorityImpl) processRemoteResults( domain string, challengeType string, primaryResult *probs.ProblemDetails, remoteErrors chan *probs.ProblemDetails, numRemoteVAs int) *probs.ProblemDetails { state := "failure" start := va.clk.Now() defer func() { va.metrics.remoteValidationTime.With(prometheus.Labels{ "type": challengeType, "result": state, }).Observe(va.clk.Since(start).Seconds()) }() required := numRemoteVAs - va.maxRemoteFailures good := 0 bad := 0 var remoteProbs []*probs.ProblemDetails var firstProb *probs.ProblemDetails // Due to channel behavior this could block indefinitely and we rely on gRPC // honoring the context deadline used in client calls to prevent that from // happening. for prob := range remoteErrors { // Add the problem to the slice remoteProbs = append(remoteProbs, prob) if prob == nil { good++ } else { bad++ } // Store the first non-nil problem to return later (if `MultiVAFullResults` // is enabled). if firstProb == nil && prob != nil { firstProb = prob } // If MultiVAFullResults isn't enabled then return early whenever the // success or failure threshold is met. if !features.Enabled(features.MultiVAFullResults) { if good >= required { state = "success" return nil } else if bad > va.maxRemoteFailures { return prob } } // If we haven't returned early because of MultiVAFullResults being enabled // we need to break the loop once all of the VAs have returned a result. if len(remoteProbs) == numRemoteVAs { break } } // If we are using `features.MultiVAFullResults` then we haven't returned // early and can now log the differential between what the primary VA saw and // what all of the remote VAs saw. va.logRemoteValidationDifferentials(domain, primaryResult, remoteProbs) // Based on the threshold of good/bad return nil or a problem. if good >= required { state = "success" return nil } else if bad > va.maxRemoteFailures { return firstProb } // This condition should not occur - it indicates the good/bad counts didn't // meet either the required threshold or the maxRemoteFailures threshold. return probs.ServerInternal("Too few remote PerformValidation RPC results") }
go
func (va *ValidationAuthorityImpl) processRemoteResults( domain string, challengeType string, primaryResult *probs.ProblemDetails, remoteErrors chan *probs.ProblemDetails, numRemoteVAs int) *probs.ProblemDetails { state := "failure" start := va.clk.Now() defer func() { va.metrics.remoteValidationTime.With(prometheus.Labels{ "type": challengeType, "result": state, }).Observe(va.clk.Since(start).Seconds()) }() required := numRemoteVAs - va.maxRemoteFailures good := 0 bad := 0 var remoteProbs []*probs.ProblemDetails var firstProb *probs.ProblemDetails // Due to channel behavior this could block indefinitely and we rely on gRPC // honoring the context deadline used in client calls to prevent that from // happening. for prob := range remoteErrors { // Add the problem to the slice remoteProbs = append(remoteProbs, prob) if prob == nil { good++ } else { bad++ } // Store the first non-nil problem to return later (if `MultiVAFullResults` // is enabled). if firstProb == nil && prob != nil { firstProb = prob } // If MultiVAFullResults isn't enabled then return early whenever the // success or failure threshold is met. if !features.Enabled(features.MultiVAFullResults) { if good >= required { state = "success" return nil } else if bad > va.maxRemoteFailures { return prob } } // If we haven't returned early because of MultiVAFullResults being enabled // we need to break the loop once all of the VAs have returned a result. if len(remoteProbs) == numRemoteVAs { break } } // If we are using `features.MultiVAFullResults` then we haven't returned // early and can now log the differential between what the primary VA saw and // what all of the remote VAs saw. va.logRemoteValidationDifferentials(domain, primaryResult, remoteProbs) // Based on the threshold of good/bad return nil or a problem. if good >= required { state = "success" return nil } else if bad > va.maxRemoteFailures { return firstProb } // This condition should not occur - it indicates the good/bad counts didn't // meet either the required threshold or the maxRemoteFailures threshold. return probs.ServerInternal("Too few remote PerformValidation RPC results") }
[ "func", "(", "va", "*", "ValidationAuthorityImpl", ")", "processRemoteResults", "(", "domain", "string", ",", "challengeType", "string", ",", "primaryResult", "*", "probs", ".", "ProblemDetails", ",", "remoteErrors", "chan", "*", "probs", ".", "ProblemDetails", ",", "numRemoteVAs", "int", ")", "*", "probs", ".", "ProblemDetails", "{", "state", ":=", "\"", "\"", "\n", "start", ":=", "va", ".", "clk", ".", "Now", "(", ")", "\n\n", "defer", "func", "(", ")", "{", "va", ".", "metrics", ".", "remoteValidationTime", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "challengeType", ",", "\"", "\"", ":", "state", ",", "}", ")", ".", "Observe", "(", "va", ".", "clk", ".", "Since", "(", "start", ")", ".", "Seconds", "(", ")", ")", "\n", "}", "(", ")", "\n\n", "required", ":=", "numRemoteVAs", "-", "va", ".", "maxRemoteFailures", "\n", "good", ":=", "0", "\n", "bad", ":=", "0", "\n\n", "var", "remoteProbs", "[", "]", "*", "probs", ".", "ProblemDetails", "\n", "var", "firstProb", "*", "probs", ".", "ProblemDetails", "\n", "// Due to channel behavior this could block indefinitely and we rely on gRPC", "// honoring the context deadline used in client calls to prevent that from", "// happening.", "for", "prob", ":=", "range", "remoteErrors", "{", "// Add the problem to the slice", "remoteProbs", "=", "append", "(", "remoteProbs", ",", "prob", ")", "\n", "if", "prob", "==", "nil", "{", "good", "++", "\n", "}", "else", "{", "bad", "++", "\n", "}", "\n\n", "// Store the first non-nil problem to return later (if `MultiVAFullResults`", "// is enabled).", "if", "firstProb", "==", "nil", "&&", "prob", "!=", "nil", "{", "firstProb", "=", "prob", "\n", "}", "\n\n", "// If MultiVAFullResults isn't enabled then return early whenever the", "// success or failure threshold is met.", "if", "!", "features", ".", "Enabled", "(", "features", ".", "MultiVAFullResults", ")", "{", "if", "good", ">=", "required", "{", "state", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "else", "if", "bad", ">", "va", ".", "maxRemoteFailures", "{", "return", "prob", "\n", "}", "\n", "}", "\n\n", "// If we haven't returned early because of MultiVAFullResults being enabled", "// we need to break the loop once all of the VAs have returned a result.", "if", "len", "(", "remoteProbs", ")", "==", "numRemoteVAs", "{", "break", "\n", "}", "\n", "}", "\n\n", "// If we are using `features.MultiVAFullResults` then we haven't returned", "// early and can now log the differential between what the primary VA saw and", "// what all of the remote VAs saw.", "va", ".", "logRemoteValidationDifferentials", "(", "domain", ",", "primaryResult", ",", "remoteProbs", ")", "\n\n", "// Based on the threshold of good/bad return nil or a problem.", "if", "good", ">=", "required", "{", "state", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "else", "if", "bad", ">", "va", ".", "maxRemoteFailures", "{", "return", "firstProb", "\n", "}", "\n\n", "// This condition should not occur - it indicates the good/bad counts didn't", "// meet either the required threshold or the maxRemoteFailures threshold.", "return", "probs", ".", "ServerInternal", "(", "\"", "\"", ")", "\n", "}" ]
// processRemoteResults evaluates a primary VA result, and a channel of remote // VA problems to produce a single overall validation result based on configured // feature flags. The overall result is calculated based on the VA's configured // `maxRemoteFailures` value. // // If the `MultiVAFullResults` feature is enabled then `processRemoteResults` // will expect to read a result from the `remoteErrors` channel for each VA and // will not produce an overall result until all remote VAs have responded. In // this case `logRemoteFailureDifferentials` will also be called to describe the // differential between the primary and all of the remote VAs. // // If the `MultiVAFullResults` feature flag is not enabled then // `processRemoteResults` will potentially return before all remote VAs have had // a chance to respond. This happens if the success or failure threshold is met. // This doesn't allow for logging the differential between the primary and // remote VAs but is more performant.
[ "processRemoteResults", "evaluates", "a", "primary", "VA", "result", "and", "a", "channel", "of", "remote", "VA", "problems", "to", "produce", "a", "single", "overall", "validation", "result", "based", "on", "configured", "feature", "flags", ".", "The", "overall", "result", "is", "calculated", "based", "on", "the", "VA", "s", "configured", "maxRemoteFailures", "value", ".", "If", "the", "MultiVAFullResults", "feature", "is", "enabled", "then", "processRemoteResults", "will", "expect", "to", "read", "a", "result", "from", "the", "remoteErrors", "channel", "for", "each", "VA", "and", "will", "not", "produce", "an", "overall", "result", "until", "all", "remote", "VAs", "have", "responded", ".", "In", "this", "case", "logRemoteFailureDifferentials", "will", "also", "be", "called", "to", "describe", "the", "differential", "between", "the", "primary", "and", "all", "of", "the", "remote", "VAs", ".", "If", "the", "MultiVAFullResults", "feature", "flag", "is", "not", "enabled", "then", "processRemoteResults", "will", "potentially", "return", "before", "all", "remote", "VAs", "have", "had", "a", "chance", "to", "respond", ".", "This", "happens", "if", "the", "success", "or", "failure", "threshold", "is", "met", ".", "This", "doesn", "t", "allow", "for", "logging", "the", "differential", "between", "the", "primary", "and", "remote", "VAs", "but", "is", "more", "performant", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/va.go#L407-L482
train
letsencrypt/boulder
va/va.go
logRemoteValidationDifferentials
func (va *ValidationAuthorityImpl) logRemoteValidationDifferentials( domain string, primaryResult *probs.ProblemDetails, remoteProbs []*probs.ProblemDetails) { var successes []*probs.ProblemDetails var failures []*probs.ProblemDetails allEqual := true for _, e := range remoteProbs { if e != primaryResult { allEqual = false } if e == nil { successes = append(successes, nil) } else { failures = append(failures, e) } } if allEqual { // There's no point logging a differential line if the primary VA and remote // VAs all agree. return } // If the primary result was OK and there were more failures than the allowed // threshold increment a stat that indicates this overall validation will have // failed if features.EnforceMultiVA is enabled. if primaryResult == nil && len(failures) > va.maxRemoteFailures { va.metrics.prospectiveRemoteValidationFailures.Inc() } logOb := struct { Domain string PrimaryResult *probs.ProblemDetails RemoteSuccesses int RemoteFailures []*probs.ProblemDetails }{ Domain: domain, PrimaryResult: primaryResult, RemoteSuccesses: len(successes), RemoteFailures: failures, } logJSON, err := json.Marshal(logOb) if err != nil { // log a warning - a marshaling failure isn't expected given the data and // isn't critical enough to break validation for by returning an error to // the caller. va.log.Warningf("Could not marshal log object in "+ "logRemoteValidationDifferentials: %s", err) return } va.log.Infof("remoteVADifferentials JSON=%s", string(logJSON)) }
go
func (va *ValidationAuthorityImpl) logRemoteValidationDifferentials( domain string, primaryResult *probs.ProblemDetails, remoteProbs []*probs.ProblemDetails) { var successes []*probs.ProblemDetails var failures []*probs.ProblemDetails allEqual := true for _, e := range remoteProbs { if e != primaryResult { allEqual = false } if e == nil { successes = append(successes, nil) } else { failures = append(failures, e) } } if allEqual { // There's no point logging a differential line if the primary VA and remote // VAs all agree. return } // If the primary result was OK and there were more failures than the allowed // threshold increment a stat that indicates this overall validation will have // failed if features.EnforceMultiVA is enabled. if primaryResult == nil && len(failures) > va.maxRemoteFailures { va.metrics.prospectiveRemoteValidationFailures.Inc() } logOb := struct { Domain string PrimaryResult *probs.ProblemDetails RemoteSuccesses int RemoteFailures []*probs.ProblemDetails }{ Domain: domain, PrimaryResult: primaryResult, RemoteSuccesses: len(successes), RemoteFailures: failures, } logJSON, err := json.Marshal(logOb) if err != nil { // log a warning - a marshaling failure isn't expected given the data and // isn't critical enough to break validation for by returning an error to // the caller. va.log.Warningf("Could not marshal log object in "+ "logRemoteValidationDifferentials: %s", err) return } va.log.Infof("remoteVADifferentials JSON=%s", string(logJSON)) }
[ "func", "(", "va", "*", "ValidationAuthorityImpl", ")", "logRemoteValidationDifferentials", "(", "domain", "string", ",", "primaryResult", "*", "probs", ".", "ProblemDetails", ",", "remoteProbs", "[", "]", "*", "probs", ".", "ProblemDetails", ")", "{", "var", "successes", "[", "]", "*", "probs", ".", "ProblemDetails", "\n", "var", "failures", "[", "]", "*", "probs", ".", "ProblemDetails", "\n\n", "allEqual", ":=", "true", "\n", "for", "_", ",", "e", ":=", "range", "remoteProbs", "{", "if", "e", "!=", "primaryResult", "{", "allEqual", "=", "false", "\n", "}", "\n", "if", "e", "==", "nil", "{", "successes", "=", "append", "(", "successes", ",", "nil", ")", "\n", "}", "else", "{", "failures", "=", "append", "(", "failures", ",", "e", ")", "\n", "}", "\n", "}", "\n", "if", "allEqual", "{", "// There's no point logging a differential line if the primary VA and remote", "// VAs all agree.", "return", "\n", "}", "\n\n", "// If the primary result was OK and there were more failures than the allowed", "// threshold increment a stat that indicates this overall validation will have", "// failed if features.EnforceMultiVA is enabled.", "if", "primaryResult", "==", "nil", "&&", "len", "(", "failures", ")", ">", "va", ".", "maxRemoteFailures", "{", "va", ".", "metrics", ".", "prospectiveRemoteValidationFailures", ".", "Inc", "(", ")", "\n", "}", "\n\n", "logOb", ":=", "struct", "{", "Domain", "string", "\n", "PrimaryResult", "*", "probs", ".", "ProblemDetails", "\n", "RemoteSuccesses", "int", "\n", "RemoteFailures", "[", "]", "*", "probs", ".", "ProblemDetails", "\n", "}", "{", "Domain", ":", "domain", ",", "PrimaryResult", ":", "primaryResult", ",", "RemoteSuccesses", ":", "len", "(", "successes", ")", ",", "RemoteFailures", ":", "failures", ",", "}", "\n\n", "logJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "logOb", ")", "\n", "if", "err", "!=", "nil", "{", "// log a warning - a marshaling failure isn't expected given the data and", "// isn't critical enough to break validation for by returning an error to", "// the caller.", "va", ".", "log", ".", "Warningf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "va", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "string", "(", "logJSON", ")", ")", "\n", "}" ]
// logRemoteValidationDifferentials is called by `processRemoteResults` when the // `MultiVAFullResults` feature flag is enabled. It produces a JSON log line // that contains the primary VA result and the results each remote VA returned.
[ "logRemoteValidationDifferentials", "is", "called", "by", "processRemoteResults", "when", "the", "MultiVAFullResults", "feature", "flag", "is", "enabled", ".", "It", "produces", "a", "JSON", "log", "line", "that", "contains", "the", "primary", "VA", "result", "and", "the", "results", "each", "remote", "VA", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/va.go#L487-L542
train
letsencrypt/boulder
errors/errors.go
New
func New(errType ErrorType, msg string, args ...interface{}) error { return &BoulderError{ Type: errType, Detail: fmt.Sprintf(msg, args...), } }
go
func New(errType ErrorType, msg string, args ...interface{}) error { return &BoulderError{ Type: errType, Detail: fmt.Sprintf(msg, args...), } }
[ "func", "New", "(", "errType", "ErrorType", ",", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "return", "&", "BoulderError", "{", "Type", ":", "errType", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "msg", ",", "args", "...", ")", ",", "}", "\n", "}" ]
// New is a convenience function for creating a new BoulderError
[ "New", "is", "a", "convenience", "function", "for", "creating", "a", "new", "BoulderError" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/errors/errors.go#L36-L41
train
letsencrypt/boulder
errors/errors.go
Is
func Is(err error, errType ErrorType) bool { bErr, ok := err.(*BoulderError) if !ok { return false } return bErr.Type == errType }
go
func Is(err error, errType ErrorType) bool { bErr, ok := err.(*BoulderError) if !ok { return false } return bErr.Type == errType }
[ "func", "Is", "(", "err", "error", ",", "errType", "ErrorType", ")", "bool", "{", "bErr", ",", "ok", ":=", "err", ".", "(", "*", "BoulderError", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "return", "bErr", ".", "Type", "==", "errType", "\n", "}" ]
// Is is a convenience function for testing the internal type of an BoulderError
[ "Is", "is", "a", "convenience", "function", "for", "testing", "the", "internal", "type", "of", "an", "BoulderError" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/errors/errors.go#L44-L50
train
letsencrypt/boulder
reloader/reloader.go
New
func New(filename string, dataCallback func([]byte) error, errorCallback func(error)) (*Reloader, error) { if errorCallback == nil { errorCallback = func(e error) {} } fileInfo, err := os.Stat(filename) if err != nil { return nil, err } b, err := readFile(filename) if err != nil { return nil, err } stopChan := make(chan struct{}) tickerStop, tickChan := makeTicker() loop := func() { for { select { case <-stopChan: tickerStop() return case <-tickChan: currentFileInfo, err := os.Stat(filename) if err != nil { errorCallback(err) continue } if !currentFileInfo.ModTime().After(fileInfo.ModTime()) { continue } b, err := readFile(filename) if err != nil { errorCallback(err) continue } fileInfo = currentFileInfo err = dataCallback(b) if err != nil { errorCallback(err) } } } } err = dataCallback(b) if err != nil { tickerStop() return nil, err } go loop() return &Reloader{stopChan}, nil }
go
func New(filename string, dataCallback func([]byte) error, errorCallback func(error)) (*Reloader, error) { if errorCallback == nil { errorCallback = func(e error) {} } fileInfo, err := os.Stat(filename) if err != nil { return nil, err } b, err := readFile(filename) if err != nil { return nil, err } stopChan := make(chan struct{}) tickerStop, tickChan := makeTicker() loop := func() { for { select { case <-stopChan: tickerStop() return case <-tickChan: currentFileInfo, err := os.Stat(filename) if err != nil { errorCallback(err) continue } if !currentFileInfo.ModTime().After(fileInfo.ModTime()) { continue } b, err := readFile(filename) if err != nil { errorCallback(err) continue } fileInfo = currentFileInfo err = dataCallback(b) if err != nil { errorCallback(err) } } } } err = dataCallback(b) if err != nil { tickerStop() return nil, err } go loop() return &Reloader{stopChan}, nil }
[ "func", "New", "(", "filename", "string", ",", "dataCallback", "func", "(", "[", "]", "byte", ")", "error", ",", "errorCallback", "func", "(", "error", ")", ")", "(", "*", "Reloader", ",", "error", ")", "{", "if", "errorCallback", "==", "nil", "{", "errorCallback", "=", "func", "(", "e", "error", ")", "{", "}", "\n", "}", "\n", "fileInfo", ",", "err", ":=", "os", ".", "Stat", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b", ",", "err", ":=", "readFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stopChan", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "tickerStop", ",", "tickChan", ":=", "makeTicker", "(", ")", "\n", "loop", ":=", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "stopChan", ":", "tickerStop", "(", ")", "\n", "return", "\n", "case", "<-", "tickChan", ":", "currentFileInfo", ",", "err", ":=", "os", ".", "Stat", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "errorCallback", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "currentFileInfo", ".", "ModTime", "(", ")", ".", "After", "(", "fileInfo", ".", "ModTime", "(", ")", ")", "{", "continue", "\n", "}", "\n", "b", ",", "err", ":=", "readFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "errorCallback", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "fileInfo", "=", "currentFileInfo", "\n", "err", "=", "dataCallback", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "errorCallback", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "err", "=", "dataCallback", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "tickerStop", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "go", "loop", "(", ")", "\n", "return", "&", "Reloader", "{", "stopChan", "}", ",", "nil", "\n", "}" ]
// New loads the filename provided, and calls the callback. It then spawns a // goroutine to check for updates to that file, calling the callback again with // any new contents. The first load, and the first call to callback, are run // synchronously, so it is easy for the caller to check for errors and fail // fast. New will return an error if it occurs on the first load. Otherwise all // errors are sent to the callback.
[ "New", "loads", "the", "filename", "provided", "and", "calls", "the", "callback", ".", "It", "then", "spawns", "a", "goroutine", "to", "check", "for", "updates", "to", "that", "file", "calling", "the", "callback", "again", "with", "any", "new", "contents", ".", "The", "first", "load", "and", "the", "first", "call", "to", "callback", "are", "run", "synchronously", "so", "it", "is", "easy", "for", "the", "caller", "to", "check", "for", "errors", "and", "fail", "fast", ".", "New", "will", "return", "an", "error", "if", "it", "occurs", "on", "the", "first", "load", ".", "Otherwise", "all", "errors", "are", "sent", "to", "the", "callback", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/reloader/reloader.go#L35-L84
train
letsencrypt/boulder
va/dns.go
availableAddresses
func availableAddresses(allAddrs []net.IP) (v4 []net.IP, v6 []net.IP) { for _, addr := range allAddrs { if addr.To4() != nil { v4 = append(v4, addr) } else { v6 = append(v6, addr) } } return }
go
func availableAddresses(allAddrs []net.IP) (v4 []net.IP, v6 []net.IP) { for _, addr := range allAddrs { if addr.To4() != nil { v4 = append(v4, addr) } else { v6 = append(v6, addr) } } return }
[ "func", "availableAddresses", "(", "allAddrs", "[", "]", "net", ".", "IP", ")", "(", "v4", "[", "]", "net", ".", "IP", ",", "v6", "[", "]", "net", ".", "IP", ")", "{", "for", "_", ",", "addr", ":=", "range", "allAddrs", "{", "if", "addr", ".", "To4", "(", ")", "!=", "nil", "{", "v4", "=", "append", "(", "v4", ",", "addr", ")", "\n", "}", "else", "{", "v6", "=", "append", "(", "v6", ",", "addr", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// availableAddresses takes a ValidationRecord and splits the AddressesResolved // into a list of IPv4 and IPv6 addresses.
[ "availableAddresses", "takes", "a", "ValidationRecord", "and", "splits", "the", "AddressesResolved", "into", "a", "list", "of", "IPv4", "and", "IPv6", "addresses", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/dns.go#L35-L44
train
letsencrypt/boulder
cmd/boulder-wfe2/main.go
loadCertificateFile
func loadCertificateFile(aiaIssuerURL, certFile string) ([]byte, error) { pemBytes, err := ioutil.ReadFile(certFile) if err != nil { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - error reading contents: %s", aiaIssuerURL, certFile, err) } if bytes.Contains(pemBytes, []byte("\r\n")) { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - contents had CRLF line endings", aiaIssuerURL, certFile) } // Try to decode the contents as PEM certBlock, rest := pem.Decode(pemBytes) if certBlock == nil { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - contents did not decode as PEM", aiaIssuerURL, certFile) } // The PEM contents must be a CERTIFICATE if certBlock.Type != "CERTIFICATE" { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - PEM block type incorrect, found "+ "%q, expected \"CERTIFICATE\"", aiaIssuerURL, certFile, certBlock.Type) } // The PEM Certificate must successfully parse if _, err := x509.ParseCertificate(certBlock.Bytes); err != nil { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - certificate bytes failed to parse: %s", aiaIssuerURL, certFile, err) } // If there are bytes leftover we must reject the file otherwise these // leftover bytes will end up in a served certificate chain. if len(rest) != 0 { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - PEM contents had unused remainder "+ "input (%d bytes)", aiaIssuerURL, certFile, len(rest)) } // If the PEM contents don't end in a \n, add it. if pemBytes[len(pemBytes)-1] != '\n' { pemBytes = append(pemBytes, '\n') } return pemBytes, nil }
go
func loadCertificateFile(aiaIssuerURL, certFile string) ([]byte, error) { pemBytes, err := ioutil.ReadFile(certFile) if err != nil { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - error reading contents: %s", aiaIssuerURL, certFile, err) } if bytes.Contains(pemBytes, []byte("\r\n")) { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - contents had CRLF line endings", aiaIssuerURL, certFile) } // Try to decode the contents as PEM certBlock, rest := pem.Decode(pemBytes) if certBlock == nil { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - contents did not decode as PEM", aiaIssuerURL, certFile) } // The PEM contents must be a CERTIFICATE if certBlock.Type != "CERTIFICATE" { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - PEM block type incorrect, found "+ "%q, expected \"CERTIFICATE\"", aiaIssuerURL, certFile, certBlock.Type) } // The PEM Certificate must successfully parse if _, err := x509.ParseCertificate(certBlock.Bytes); err != nil { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - certificate bytes failed to parse: %s", aiaIssuerURL, certFile, err) } // If there are bytes leftover we must reject the file otherwise these // leftover bytes will end up in a served certificate chain. if len(rest) != 0 { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has an "+ "invalid chain file: %q - PEM contents had unused remainder "+ "input (%d bytes)", aiaIssuerURL, certFile, len(rest)) } // If the PEM contents don't end in a \n, add it. if pemBytes[len(pemBytes)-1] != '\n' { pemBytes = append(pemBytes, '\n') } return pemBytes, nil }
[ "func", "loadCertificateFile", "(", "aiaIssuerURL", ",", "certFile", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "pemBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "certFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "aiaIssuerURL", ",", "certFile", ",", "err", ")", "\n", "}", "\n", "if", "bytes", ".", "Contains", "(", "pemBytes", ",", "[", "]", "byte", "(", "\"", "\\r", "\\n", "\"", ")", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "aiaIssuerURL", ",", "certFile", ")", "\n", "}", "\n", "// Try to decode the contents as PEM", "certBlock", ",", "rest", ":=", "pem", ".", "Decode", "(", "pemBytes", ")", "\n", "if", "certBlock", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "aiaIssuerURL", ",", "certFile", ")", "\n", "}", "\n", "// The PEM contents must be a CERTIFICATE", "if", "certBlock", ".", "Type", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\\\"", "\\\"", "\"", ",", "aiaIssuerURL", ",", "certFile", ",", "certBlock", ".", "Type", ")", "\n", "}", "\n", "// The PEM Certificate must successfully parse", "if", "_", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "certBlock", ".", "Bytes", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "aiaIssuerURL", ",", "certFile", ",", "err", ")", "\n", "}", "\n", "// If there are bytes leftover we must reject the file otherwise these", "// leftover bytes will end up in a served certificate chain.", "if", "len", "(", "rest", ")", "!=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "aiaIssuerURL", ",", "certFile", ",", "len", "(", "rest", ")", ")", "\n", "}", "\n", "// If the PEM contents don't end in a \\n, add it.", "if", "pemBytes", "[", "len", "(", "pemBytes", ")", "-", "1", "]", "!=", "'\\n'", "{", "pemBytes", "=", "append", "(", "pemBytes", ",", "'\\n'", ")", "\n", "}", "\n", "return", "pemBytes", ",", "nil", "\n", "}" ]
// loadCertificateFile loads a PEM certificate from the certFile provided. It // validates that the PEM is well-formed with no leftover bytes, and contains // only a well-formed X509 certificate. If the cert file meets these // requirements the PEM bytes from the file are returned, otherwise an error is // returned. If the PEM contents of a certFile do not have a trailing newline // one is added.
[ "loadCertificateFile", "loads", "a", "PEM", "certificate", "from", "the", "certFile", "provided", ".", "It", "validates", "that", "the", "PEM", "is", "well", "-", "formed", "with", "no", "leftover", "bytes", "and", "contains", "only", "a", "well", "-", "formed", "X509", "certificate", ".", "If", "the", "cert", "file", "meets", "these", "requirements", "the", "PEM", "bytes", "from", "the", "file", "are", "returned", "otherwise", "an", "error", "is", "returned", ".", "If", "the", "PEM", "contents", "of", "a", "certFile", "do", "not", "have", "a", "trailing", "newline", "one", "is", "added", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/boulder-wfe2/main.go#L88-L139
train
letsencrypt/boulder
cmd/boulder-wfe2/main.go
loadCertificateChains
func loadCertificateChains(chainConfig map[string][]string) (map[string][]byte, error) { results := make(map[string][]byte, len(chainConfig)) // For each AIA Issuer URL we need to read the chain cert files for aiaIssuerURL, certFiles := range chainConfig { var buffer bytes.Buffer // There must be at least one chain file specified if len(certFiles) == 0 { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has no chain "+ "file names configured", aiaIssuerURL) } // certFiles are read and appended in the order they appear in the // configuration for _, c := range certFiles { // Prepend a newline before each chain entry buffer.Write([]byte("\n")) // Read and validate the chain file contents pemBytes, err := loadCertificateFile(aiaIssuerURL, c) if err != nil { return nil, err } // Write the PEM bytes to the result buffer for this AIAIssuer buffer.Write(pemBytes) } // Save the full PEM chain contents results[aiaIssuerURL] = buffer.Bytes() } return results, nil }
go
func loadCertificateChains(chainConfig map[string][]string) (map[string][]byte, error) { results := make(map[string][]byte, len(chainConfig)) // For each AIA Issuer URL we need to read the chain cert files for aiaIssuerURL, certFiles := range chainConfig { var buffer bytes.Buffer // There must be at least one chain file specified if len(certFiles) == 0 { return nil, fmt.Errorf( "CertificateChain entry for AIA issuer url %q has no chain "+ "file names configured", aiaIssuerURL) } // certFiles are read and appended in the order they appear in the // configuration for _, c := range certFiles { // Prepend a newline before each chain entry buffer.Write([]byte("\n")) // Read and validate the chain file contents pemBytes, err := loadCertificateFile(aiaIssuerURL, c) if err != nil { return nil, err } // Write the PEM bytes to the result buffer for this AIAIssuer buffer.Write(pemBytes) } // Save the full PEM chain contents results[aiaIssuerURL] = buffer.Bytes() } return results, nil }
[ "func", "loadCertificateChains", "(", "chainConfig", "map", "[", "string", "]", "[", "]", "string", ")", "(", "map", "[", "string", "]", "[", "]", "byte", ",", "error", ")", "{", "results", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "byte", ",", "len", "(", "chainConfig", ")", ")", "\n\n", "// For each AIA Issuer URL we need to read the chain cert files", "for", "aiaIssuerURL", ",", "certFiles", ":=", "range", "chainConfig", "{", "var", "buffer", "bytes", ".", "Buffer", "\n\n", "// There must be at least one chain file specified", "if", "len", "(", "certFiles", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "aiaIssuerURL", ")", "\n", "}", "\n\n", "// certFiles are read and appended in the order they appear in the", "// configuration", "for", "_", ",", "c", ":=", "range", "certFiles", "{", "// Prepend a newline before each chain entry", "buffer", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\\n", "\"", ")", ")", "\n\n", "// Read and validate the chain file contents", "pemBytes", ",", "err", ":=", "loadCertificateFile", "(", "aiaIssuerURL", ",", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Write the PEM bytes to the result buffer for this AIAIssuer", "buffer", ".", "Write", "(", "pemBytes", ")", "\n", "}", "\n\n", "// Save the full PEM chain contents", "results", "[", "aiaIssuerURL", "]", "=", "buffer", ".", "Bytes", "(", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// loadCertificateChains processes the provided chainConfig of AIA Issuer URLs // and cert filenames. For each AIA issuer URL all of its cert filenames are // read, validated as PEM certificates, and concatenated together separated by // newlines. The combined PEM certificate chain contents for each are returned // in the results map, keyed by the AIA Issuer URL.
[ "loadCertificateChains", "processes", "the", "provided", "chainConfig", "of", "AIA", "Issuer", "URLs", "and", "cert", "filenames", ".", "For", "each", "AIA", "issuer", "URL", "all", "of", "its", "cert", "filenames", "are", "read", "validated", "as", "PEM", "certificates", "and", "concatenated", "together", "separated", "by", "newlines", ".", "The", "combined", "PEM", "certificate", "chain", "contents", "for", "each", "are", "returned", "in", "the", "results", "map", "keyed", "by", "the", "AIA", "Issuer", "URL", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/cmd/boulder-wfe2/main.go#L146-L181
train
letsencrypt/boulder
publisher/mock_publisher/mock_publisher.go
NewMockPublisher
func NewMockPublisher(ctrl *gomock.Controller) *MockPublisher { mock := &MockPublisher{ctrl: ctrl} mock.recorder = &MockPublisherMockRecorder{mock} return mock }
go
func NewMockPublisher(ctrl *gomock.Controller) *MockPublisher { mock := &MockPublisher{ctrl: ctrl} mock.recorder = &MockPublisherMockRecorder{mock} return mock }
[ "func", "NewMockPublisher", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockPublisher", "{", "mock", ":=", "&", "MockPublisher", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockPublisherMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockPublisher creates a new mock instance
[ "NewMockPublisher", "creates", "a", "new", "mock", "instance" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/publisher/mock_publisher/mock_publisher.go#L26-L30
train
letsencrypt/boulder
publisher/mock_publisher/mock_publisher.go
SubmitToSingleCTWithResult
func (m *MockPublisher) SubmitToSingleCTWithResult(arg0 context.Context, arg1 *proto.Request) (*proto.Result, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SubmitToSingleCTWithResult", arg0, arg1) ret0, _ := ret[0].(*proto.Result) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockPublisher) SubmitToSingleCTWithResult(arg0 context.Context, arg1 *proto.Request) (*proto.Result, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SubmitToSingleCTWithResult", arg0, arg1) ret0, _ := ret[0].(*proto.Result) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockPublisher", ")", "SubmitToSingleCTWithResult", "(", "arg0", "context", ".", "Context", ",", "arg1", "*", "proto", ".", "Request", ")", "(", "*", "proto", ".", "Result", ",", "error", ")", "{", "m", ".", "ctrl", ".", "T", ".", "Helper", "(", ")", "\n", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "proto", ".", "Result", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// SubmitToSingleCTWithResult mocks base method
[ "SubmitToSingleCTWithResult", "mocks", "base", "method" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/publisher/mock_publisher/mock_publisher.go#L38-L44
train
letsencrypt/boulder
publisher/mock_publisher/mock_publisher.go
SubmitToSingleCTWithResult
func (mr *MockPublisherMockRecorder) SubmitToSingleCTWithResult(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitToSingleCTWithResult", reflect.TypeOf((*MockPublisher)(nil).SubmitToSingleCTWithResult), arg0, arg1) }
go
func (mr *MockPublisherMockRecorder) SubmitToSingleCTWithResult(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitToSingleCTWithResult", reflect.TypeOf((*MockPublisher)(nil).SubmitToSingleCTWithResult), arg0, arg1) }
[ "func", "(", "mr", "*", "MockPublisherMockRecorder", ")", "SubmitToSingleCTWithResult", "(", "arg0", ",", "arg1", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "mr", ".", "mock", ".", "ctrl", ".", "T", ".", "Helper", "(", ")", "\n", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockPublisher", ")", "(", "nil", ")", ".", "SubmitToSingleCTWithResult", ")", ",", "arg0", ",", "arg1", ")", "\n", "}" ]
// SubmitToSingleCTWithResult indicates an expected call of SubmitToSingleCTWithResult
[ "SubmitToSingleCTWithResult", "indicates", "an", "expected", "call", "of", "SubmitToSingleCTWithResult" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/publisher/mock_publisher/mock_publisher.go#L47-L50
train
letsencrypt/boulder
sa/sa.go
NewSQLStorageAuthority
func NewSQLStorageAuthority( dbMap *gorp.DbMap, clk clock.Clock, logger blog.Logger, scope metrics.Scope, parallelismPerRPC int, ) (*SQLStorageAuthority, error) { SetSQLDebug(dbMap, logger) ssa := &SQLStorageAuthority{ dbMap: dbMap, clk: clk, log: logger, parallelismPerRPC: parallelismPerRPC, } ssa.countCertificatesByName = ssa.countCertificatesByNameImpl ssa.countCertificatesByExactName = ssa.countCertificatesByExactNameImpl if features.Enabled(features.FasterRateLimit) { ssa.countCertificatesByName = ssa.countCertificatesFaster ssa.countCertificatesByExactName = ssa.countCertificatesFaster } ssa.getChallenges = ssa.getChallengesImpl return ssa, nil }
go
func NewSQLStorageAuthority( dbMap *gorp.DbMap, clk clock.Clock, logger blog.Logger, scope metrics.Scope, parallelismPerRPC int, ) (*SQLStorageAuthority, error) { SetSQLDebug(dbMap, logger) ssa := &SQLStorageAuthority{ dbMap: dbMap, clk: clk, log: logger, parallelismPerRPC: parallelismPerRPC, } ssa.countCertificatesByName = ssa.countCertificatesByNameImpl ssa.countCertificatesByExactName = ssa.countCertificatesByExactNameImpl if features.Enabled(features.FasterRateLimit) { ssa.countCertificatesByName = ssa.countCertificatesFaster ssa.countCertificatesByExactName = ssa.countCertificatesFaster } ssa.getChallenges = ssa.getChallengesImpl return ssa, nil }
[ "func", "NewSQLStorageAuthority", "(", "dbMap", "*", "gorp", ".", "DbMap", ",", "clk", "clock", ".", "Clock", ",", "logger", "blog", ".", "Logger", ",", "scope", "metrics", ".", "Scope", ",", "parallelismPerRPC", "int", ",", ")", "(", "*", "SQLStorageAuthority", ",", "error", ")", "{", "SetSQLDebug", "(", "dbMap", ",", "logger", ")", "\n\n", "ssa", ":=", "&", "SQLStorageAuthority", "{", "dbMap", ":", "dbMap", ",", "clk", ":", "clk", ",", "log", ":", "logger", ",", "parallelismPerRPC", ":", "parallelismPerRPC", ",", "}", "\n\n", "ssa", ".", "countCertificatesByName", "=", "ssa", ".", "countCertificatesByNameImpl", "\n", "ssa", ".", "countCertificatesByExactName", "=", "ssa", ".", "countCertificatesByExactNameImpl", "\n", "if", "features", ".", "Enabled", "(", "features", ".", "FasterRateLimit", ")", "{", "ssa", ".", "countCertificatesByName", "=", "ssa", ".", "countCertificatesFaster", "\n", "ssa", ".", "countCertificatesByExactName", "=", "ssa", ".", "countCertificatesFaster", "\n", "}", "\n", "ssa", ".", "getChallenges", "=", "ssa", ".", "getChallengesImpl", "\n\n", "return", "ssa", ",", "nil", "\n", "}" ]
// NewSQLStorageAuthority provides persistence using a SQL backend for // Boulder. It will modify the given gorp.DbMap by adding relevant tables.
[ "NewSQLStorageAuthority", "provides", "persistence", "using", "a", "SQL", "backend", "for", "Boulder", ".", "It", "will", "modify", "the", "given", "gorp", ".", "DbMap", "by", "adding", "relevant", "tables", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L93-L118
train
letsencrypt/boulder
sa/sa.go
GetRegistration
func (ssa *SQLStorageAuthority) GetRegistration(ctx context.Context, id int64) (core.Registration, error) { const query = "WHERE id = ?" model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, id) if err == sql.ErrNoRows { return core.Registration{}, berrors.NotFoundError("registration with ID '%d' not found", id) } if err != nil { return core.Registration{}, err } return modelToRegistration(model) }
go
func (ssa *SQLStorageAuthority) GetRegistration(ctx context.Context, id int64) (core.Registration, error) { const query = "WHERE id = ?" model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, id) if err == sql.ErrNoRows { return core.Registration{}, berrors.NotFoundError("registration with ID '%d' not found", id) } if err != nil { return core.Registration{}, err } return modelToRegistration(model) }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetRegistration", "(", "ctx", "context", ".", "Context", ",", "id", "int64", ")", "(", "core", ".", "Registration", ",", "error", ")", "{", "const", "query", "=", "\"", "\"", "\n", "model", ",", "err", ":=", "selectRegistration", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "query", ",", "id", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "core", ".", "Registration", "{", "}", ",", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "err", "\n", "}", "\n", "return", "modelToRegistration", "(", "model", ")", "\n", "}" ]
// GetRegistration obtains a Registration by ID
[ "GetRegistration", "obtains", "a", "Registration", "by", "ID" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L183-L193
train
letsencrypt/boulder
sa/sa.go
GetRegistrationByKey
func (ssa *SQLStorageAuthority) GetRegistrationByKey(ctx context.Context, key *jose.JSONWebKey) (core.Registration, error) { const query = "WHERE jwk_sha256 = ?" if key == nil { return core.Registration{}, fmt.Errorf("key argument to GetRegistrationByKey must not be nil") } sha, err := core.KeyDigest(key.Key) if err != nil { return core.Registration{}, err } model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, sha) if err == sql.ErrNoRows { return core.Registration{}, berrors.NotFoundError("no registrations with public key sha256 %q", sha) } if err != nil { return core.Registration{}, err } return modelToRegistration(model) }
go
func (ssa *SQLStorageAuthority) GetRegistrationByKey(ctx context.Context, key *jose.JSONWebKey) (core.Registration, error) { const query = "WHERE jwk_sha256 = ?" if key == nil { return core.Registration{}, fmt.Errorf("key argument to GetRegistrationByKey must not be nil") } sha, err := core.KeyDigest(key.Key) if err != nil { return core.Registration{}, err } model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, sha) if err == sql.ErrNoRows { return core.Registration{}, berrors.NotFoundError("no registrations with public key sha256 %q", sha) } if err != nil { return core.Registration{}, err } return modelToRegistration(model) }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetRegistrationByKey", "(", "ctx", "context", ".", "Context", ",", "key", "*", "jose", ".", "JSONWebKey", ")", "(", "core", ".", "Registration", ",", "error", ")", "{", "const", "query", "=", "\"", "\"", "\n", "if", "key", "==", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "sha", ",", "err", ":=", "core", ".", "KeyDigest", "(", "key", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "err", "\n", "}", "\n", "model", ",", "err", ":=", "selectRegistration", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "query", ",", "sha", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "core", ".", "Registration", "{", "}", ",", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "sha", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "modelToRegistration", "(", "model", ")", "\n", "}" ]
// GetRegistrationByKey obtains a Registration by JWK
[ "GetRegistrationByKey", "obtains", "a", "Registration", "by", "JWK" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L196-L214
train
letsencrypt/boulder
sa/sa.go
GetAuthorization
func (ssa *SQLStorageAuthority) GetAuthorization(ctx context.Context, id string) (core.Authorization, error) { authz := core.Authorization{} tx, err := ssa.dbMap.Begin() if err != nil { return authz, err } txWithCtx := tx.WithContext(ctx) pa, err := selectPendingAuthz(txWithCtx, "WHERE id = ?", id) if err != nil && err != sql.ErrNoRows { return authz, Rollback(tx, err) } if err == sql.ErrNoRows { var fa authzModel err := txWithCtx.SelectOne(&fa, fmt.Sprintf("SELECT %s FROM authz WHERE id = ?", authzFields), id) if err != nil && err != sql.ErrNoRows { return authz, Rollback(tx, err) } else if err == sql.ErrNoRows { // If there was no result in either the pending authz table or the authz // table then return a `berrors.NotFound` instance (or a rollback error if // the transaction rollback fails) return authz, Rollback( tx, berrors.NotFoundError("no authorization found with id %q", id)) } authz = fa.Authorization } else { authz = pa.Authorization } authz.Challenges, err = ssa.getChallenges(txWithCtx, authz.ID) if err != nil { return authz, Rollback(tx, err) } return authz, tx.Commit() }
go
func (ssa *SQLStorageAuthority) GetAuthorization(ctx context.Context, id string) (core.Authorization, error) { authz := core.Authorization{} tx, err := ssa.dbMap.Begin() if err != nil { return authz, err } txWithCtx := tx.WithContext(ctx) pa, err := selectPendingAuthz(txWithCtx, "WHERE id = ?", id) if err != nil && err != sql.ErrNoRows { return authz, Rollback(tx, err) } if err == sql.ErrNoRows { var fa authzModel err := txWithCtx.SelectOne(&fa, fmt.Sprintf("SELECT %s FROM authz WHERE id = ?", authzFields), id) if err != nil && err != sql.ErrNoRows { return authz, Rollback(tx, err) } else if err == sql.ErrNoRows { // If there was no result in either the pending authz table or the authz // table then return a `berrors.NotFound` instance (or a rollback error if // the transaction rollback fails) return authz, Rollback( tx, berrors.NotFoundError("no authorization found with id %q", id)) } authz = fa.Authorization } else { authz = pa.Authorization } authz.Challenges, err = ssa.getChallenges(txWithCtx, authz.ID) if err != nil { return authz, Rollback(tx, err) } return authz, tx.Commit() }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetAuthorization", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "(", "core", ".", "Authorization", ",", "error", ")", "{", "authz", ":=", "core", ".", "Authorization", "{", "}", "\n", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "authz", ",", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n\n", "pa", ",", "err", ":=", "selectPendingAuthz", "(", "txWithCtx", ",", "\"", "\"", ",", "id", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "sql", ".", "ErrNoRows", "{", "return", "authz", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "var", "fa", "authzModel", "\n", "err", ":=", "txWithCtx", ".", "SelectOne", "(", "&", "fa", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "authzFields", ")", ",", "id", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "sql", ".", "ErrNoRows", "{", "return", "authz", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "else", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "// If there was no result in either the pending authz table or the authz", "// table then return a `berrors.NotFound` instance (or a rollback error if", "// the transaction rollback fails)", "return", "authz", ",", "Rollback", "(", "tx", ",", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "id", ")", ")", "\n", "}", "\n", "authz", "=", "fa", ".", "Authorization", "\n", "}", "else", "{", "authz", "=", "pa", ".", "Authorization", "\n", "}", "\n\n", "authz", ".", "Challenges", ",", "err", "=", "ssa", ".", "getChallenges", "(", "txWithCtx", ",", "authz", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "authz", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "return", "authz", ",", "tx", ".", "Commit", "(", ")", "\n", "}" ]
// GetAuthorization obtains an Authorization by ID
[ "GetAuthorization", "obtains", "an", "Authorization", "by", "ID" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L217-L253
train
letsencrypt/boulder
sa/sa.go
GetValidAuthorizations
func (ssa *SQLStorageAuthority) GetValidAuthorizations( ctx context.Context, registrationID int64, names []string, now time.Time) (map[string]*core.Authorization, error) { return ssa.getAuthorizations( ctx, authorizationTable, string(core.StatusValid), registrationID, names, now, false) }
go
func (ssa *SQLStorageAuthority) GetValidAuthorizations( ctx context.Context, registrationID int64, names []string, now time.Time) (map[string]*core.Authorization, error) { return ssa.getAuthorizations( ctx, authorizationTable, string(core.StatusValid), registrationID, names, now, false) }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetValidAuthorizations", "(", "ctx", "context", ".", "Context", ",", "registrationID", "int64", ",", "names", "[", "]", "string", ",", "now", "time", ".", "Time", ")", "(", "map", "[", "string", "]", "*", "core", ".", "Authorization", ",", "error", ")", "{", "return", "ssa", ".", "getAuthorizations", "(", "ctx", ",", "authorizationTable", ",", "string", "(", "core", ".", "StatusValid", ")", ",", "registrationID", ",", "names", ",", "now", ",", "false", ")", "\n", "}" ]
// GetValidAuthorizations returns the latest authorization object for all // domain names from the parameters that the account has authorizations for.
[ "GetValidAuthorizations", "returns", "the", "latest", "authorization", "object", "for", "all", "domain", "names", "from", "the", "parameters", "that", "the", "account", "has", "authorizations", "for", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L257-L270
train
letsencrypt/boulder
sa/sa.go
incrementIP
func incrementIP(ip net.IP, index int) net.IP { bigInt := new(big.Int) bigInt.SetBytes([]byte(ip)) incr := new(big.Int).Lsh(big.NewInt(1), 128-uint(index)) bigInt.Add(bigInt, incr) // bigInt.Bytes can be shorter than 16 bytes, so stick it into a // full-sized net.IP. resultBytes := bigInt.Bytes() if len(resultBytes) > 16 { return net.ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") } result := make(net.IP, 16) copy(result[16-len(resultBytes):], resultBytes) return result }
go
func incrementIP(ip net.IP, index int) net.IP { bigInt := new(big.Int) bigInt.SetBytes([]byte(ip)) incr := new(big.Int).Lsh(big.NewInt(1), 128-uint(index)) bigInt.Add(bigInt, incr) // bigInt.Bytes can be shorter than 16 bytes, so stick it into a // full-sized net.IP. resultBytes := bigInt.Bytes() if len(resultBytes) > 16 { return net.ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") } result := make(net.IP, 16) copy(result[16-len(resultBytes):], resultBytes) return result }
[ "func", "incrementIP", "(", "ip", "net", ".", "IP", ",", "index", "int", ")", "net", ".", "IP", "{", "bigInt", ":=", "new", "(", "big", ".", "Int", ")", "\n", "bigInt", ".", "SetBytes", "(", "[", "]", "byte", "(", "ip", ")", ")", "\n", "incr", ":=", "new", "(", "big", ".", "Int", ")", ".", "Lsh", "(", "big", ".", "NewInt", "(", "1", ")", ",", "128", "-", "uint", "(", "index", ")", ")", "\n", "bigInt", ".", "Add", "(", "bigInt", ",", "incr", ")", "\n", "// bigInt.Bytes can be shorter than 16 bytes, so stick it into a", "// full-sized net.IP.", "resultBytes", ":=", "bigInt", ".", "Bytes", "(", ")", "\n", "if", "len", "(", "resultBytes", ")", ">", "16", "{", "return", "net", ".", "ParseIP", "(", "\"", "\"", ")", "\n", "}", "\n", "result", ":=", "make", "(", "net", ".", "IP", ",", "16", ")", "\n", "copy", "(", "result", "[", "16", "-", "len", "(", "resultBytes", ")", ":", "]", ",", "resultBytes", ")", "\n", "return", "result", "\n", "}" ]
// incrementIP returns a copy of `ip` incremented at a bit index `index`, // or in other words the first IP of the next highest subnet given a mask of // length `index`. // In order to easily account for overflow, we treat ip as a big.Int and add to // it. If the increment overflows the max size of a net.IP, return the highest // possible net.IP.
[ "incrementIP", "returns", "a", "copy", "of", "ip", "incremented", "at", "a", "bit", "index", "index", "or", "in", "other", "words", "the", "first", "IP", "of", "the", "next", "highest", "subnet", "given", "a", "mask", "of", "length", "index", ".", "In", "order", "to", "easily", "account", "for", "overflow", "we", "treat", "ip", "as", "a", "big", ".", "Int", "and", "add", "to", "it", ".", "If", "the", "increment", "overflows", "the", "max", "size", "of", "a", "net", ".", "IP", "return", "the", "highest", "possible", "net", ".", "IP", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L278-L292
train
letsencrypt/boulder
sa/sa.go
CountRegistrationsByIP
func (ssa *SQLStorageAuthority) CountRegistrationsByIP(ctx context.Context, ip net.IP, earliest time.Time, latest time.Time) (int, error) { var count int64 err := ssa.dbMap.WithContext(ctx).SelectOne( &count, `SELECT COUNT(1) FROM registrations WHERE initialIP = :ip AND :earliest < createdAt AND createdAt <= :latest`, map[string]interface{}{ "ip": []byte(ip), "earliest": earliest, "latest": latest, }) if err != nil { return -1, err } return int(count), nil }
go
func (ssa *SQLStorageAuthority) CountRegistrationsByIP(ctx context.Context, ip net.IP, earliest time.Time, latest time.Time) (int, error) { var count int64 err := ssa.dbMap.WithContext(ctx).SelectOne( &count, `SELECT COUNT(1) FROM registrations WHERE initialIP = :ip AND :earliest < createdAt AND createdAt <= :latest`, map[string]interface{}{ "ip": []byte(ip), "earliest": earliest, "latest": latest, }) if err != nil { return -1, err } return int(count), nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "CountRegistrationsByIP", "(", "ctx", "context", ".", "Context", ",", "ip", "net", ".", "IP", ",", "earliest", "time", ".", "Time", ",", "latest", "time", ".", "Time", ")", "(", "int", ",", "error", ")", "{", "var", "count", "int64", "\n", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", "(", "&", "count", ",", "`SELECT COUNT(1) FROM registrations\n\t\t WHERE\n\t\t initialIP = :ip AND\n\t\t :earliest < createdAt AND\n\t\t createdAt <= :latest`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "[", "]", "byte", "(", "ip", ")", ",", "\"", "\"", ":", "earliest", ",", "\"", "\"", ":", "latest", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "return", "int", "(", "count", ")", ",", "nil", "\n", "}" ]
// CountRegistrationsByIP returns the number of registrations created in the // time range for a single IP address.
[ "CountRegistrationsByIP", "returns", "the", "number", "of", "registrations", "created", "in", "the", "time", "range", "for", "a", "single", "IP", "address", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L320-L338
train
letsencrypt/boulder
sa/sa.go
CountCertificatesByNames
func (ssa *SQLStorageAuthority) CountCertificatesByNames(ctx context.Context, domains []string, earliest, latest time.Time) ([]*sapb.CountByNames_MapElement, error) { work := make(chan string, len(domains)) type result struct { err error count int domain string } results := make(chan result, len(domains)) for _, domain := range domains { work <- domain } close(work) var wg sync.WaitGroup ctx, cancel := context.WithCancel(ctx) defer cancel() // We may perform up to 100 queries, depending on what's in the certificate // request. Parallelize them so we don't hit our timeout, but limit the // parallelism so we don't consume too many threads on the database. for i := 0; i < ssa.parallelismPerRPC; i++ { wg.Add(1) go func() { defer wg.Done() for domain := range work { select { case <-ctx.Done(): results <- result{err: ctx.Err()} return default: } currentCount, err := ssa.countCertificatesByName( ssa.dbMap.WithContext(ctx), domain, earliest, latest) if err != nil { results <- result{err: err} // Skip any further work cancel() return } results <- result{ count: currentCount, domain: domain, } } }() } wg.Wait() close(results) var ret []*sapb.CountByNames_MapElement for r := range results { if r.err != nil { return nil, r.err } name := string(r.domain) pbCount := int64(r.count) ret = append(ret, &sapb.CountByNames_MapElement{ Name: &name, Count: &pbCount, }) } return ret, nil }
go
func (ssa *SQLStorageAuthority) CountCertificatesByNames(ctx context.Context, domains []string, earliest, latest time.Time) ([]*sapb.CountByNames_MapElement, error) { work := make(chan string, len(domains)) type result struct { err error count int domain string } results := make(chan result, len(domains)) for _, domain := range domains { work <- domain } close(work) var wg sync.WaitGroup ctx, cancel := context.WithCancel(ctx) defer cancel() // We may perform up to 100 queries, depending on what's in the certificate // request. Parallelize them so we don't hit our timeout, but limit the // parallelism so we don't consume too many threads on the database. for i := 0; i < ssa.parallelismPerRPC; i++ { wg.Add(1) go func() { defer wg.Done() for domain := range work { select { case <-ctx.Done(): results <- result{err: ctx.Err()} return default: } currentCount, err := ssa.countCertificatesByName( ssa.dbMap.WithContext(ctx), domain, earliest, latest) if err != nil { results <- result{err: err} // Skip any further work cancel() return } results <- result{ count: currentCount, domain: domain, } } }() } wg.Wait() close(results) var ret []*sapb.CountByNames_MapElement for r := range results { if r.err != nil { return nil, r.err } name := string(r.domain) pbCount := int64(r.count) ret = append(ret, &sapb.CountByNames_MapElement{ Name: &name, Count: &pbCount, }) } return ret, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "CountCertificatesByNames", "(", "ctx", "context", ".", "Context", ",", "domains", "[", "]", "string", ",", "earliest", ",", "latest", "time", ".", "Time", ")", "(", "[", "]", "*", "sapb", ".", "CountByNames_MapElement", ",", "error", ")", "{", "work", ":=", "make", "(", "chan", "string", ",", "len", "(", "domains", ")", ")", "\n", "type", "result", "struct", "{", "err", "error", "\n", "count", "int", "\n", "domain", "string", "\n", "}", "\n", "results", ":=", "make", "(", "chan", "result", ",", "len", "(", "domains", ")", ")", "\n", "for", "_", ",", "domain", ":=", "range", "domains", "{", "work", "<-", "domain", "\n", "}", "\n", "close", "(", "work", ")", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "defer", "cancel", "(", ")", "\n", "// We may perform up to 100 queries, depending on what's in the certificate", "// request. Parallelize them so we don't hit our timeout, but limit the", "// parallelism so we don't consume too many threads on the database.", "for", "i", ":=", "0", ";", "i", "<", "ssa", ".", "parallelismPerRPC", ";", "i", "++", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "for", "domain", ":=", "range", "work", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "results", "<-", "result", "{", "err", ":", "ctx", ".", "Err", "(", ")", "}", "\n", "return", "\n", "default", ":", "}", "\n", "currentCount", ",", "err", ":=", "ssa", ".", "countCertificatesByName", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "domain", ",", "earliest", ",", "latest", ")", "\n", "if", "err", "!=", "nil", "{", "results", "<-", "result", "{", "err", ":", "err", "}", "\n", "// Skip any further work", "cancel", "(", ")", "\n", "return", "\n", "}", "\n", "results", "<-", "result", "{", "count", ":", "currentCount", ",", "domain", ":", "domain", ",", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "results", ")", "\n", "var", "ret", "[", "]", "*", "sapb", ".", "CountByNames_MapElement", "\n", "for", "r", ":=", "range", "results", "{", "if", "r", ".", "err", "!=", "nil", "{", "return", "nil", ",", "r", ".", "err", "\n", "}", "\n", "name", ":=", "string", "(", "r", ".", "domain", ")", "\n", "pbCount", ":=", "int64", "(", "r", ".", "count", ")", "\n", "ret", "=", "append", "(", "ret", ",", "&", "sapb", ".", "CountByNames_MapElement", "{", "Name", ":", "&", "name", ",", "Count", ":", "&", "pbCount", ",", "}", ")", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// CountCertificatesByNames counts, for each input domain, the number of // certificates issued in the given time range for that domain and its // subdomains. It returns a map from domains to counts, which is guaranteed to // contain an entry for each input domain, so long as err is nil. // Queries will be run in parallel. If any of them error, only one error will // be returned.
[ "CountCertificatesByNames", "counts", "for", "each", "input", "domain", "the", "number", "of", "certificates", "issued", "in", "the", "given", "time", "range", "for", "that", "domain", "and", "its", "subdomains", ".", "It", "returns", "a", "map", "from", "domains", "to", "counts", "which", "is", "guaranteed", "to", "contain", "an", "entry", "for", "each", "input", "domain", "so", "long", "as", "err", "is", "nil", ".", "Queries", "will", "be", "run", "in", "parallel", ".", "If", "any", "of", "them", "error", "only", "one", "error", "will", "be", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L373-L432
train
letsencrypt/boulder
sa/sa.go
countCertificatesByNameImpl
func (ssa *SQLStorageAuthority) countCertificatesByNameImpl( db dbSelector, domain string, earliest, latest time.Time, ) (int, error) { return ssa.countCertificates(db, domain, earliest, latest, countCertificatesSelect) }
go
func (ssa *SQLStorageAuthority) countCertificatesByNameImpl( db dbSelector, domain string, earliest, latest time.Time, ) (int, error) { return ssa.countCertificates(db, domain, earliest, latest, countCertificatesSelect) }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "countCertificatesByNameImpl", "(", "db", "dbSelector", ",", "domain", "string", ",", "earliest", ",", "latest", "time", ".", "Time", ",", ")", "(", "int", ",", "error", ")", "{", "return", "ssa", ".", "countCertificates", "(", "db", ",", "domain", ",", "earliest", ",", "latest", ",", "countCertificatesSelect", ")", "\n", "}" ]
// countCertificatesByNames returns, for a single domain, the count of // certificates issued in the given time range for that domain and its // subdomains.
[ "countCertificatesByNames", "returns", "for", "a", "single", "domain", "the", "count", "of", "certificates", "issued", "in", "the", "given", "time", "range", "for", "that", "domain", "and", "its", "subdomains", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L474-L481
train
letsencrypt/boulder
sa/sa.go
countCertificatesByExactNameImpl
func (ssa *SQLStorageAuthority) countCertificatesByExactNameImpl( db dbSelector, domain string, earliest, latest time.Time, ) (int, error) { return ssa.countCertificates(db, domain, earliest, latest, countCertificatesExactSelect) }
go
func (ssa *SQLStorageAuthority) countCertificatesByExactNameImpl( db dbSelector, domain string, earliest, latest time.Time, ) (int, error) { return ssa.countCertificates(db, domain, earliest, latest, countCertificatesExactSelect) }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "countCertificatesByExactNameImpl", "(", "db", "dbSelector", ",", "domain", "string", ",", "earliest", ",", "latest", "time", ".", "Time", ",", ")", "(", "int", ",", "error", ")", "{", "return", "ssa", ".", "countCertificates", "(", "db", ",", "domain", ",", "earliest", ",", "latest", ",", "countCertificatesExactSelect", ")", "\n", "}" ]
// countCertificatesByExactNames returns, for a single domain, the count of // certificates issued in the given time range for that domain. In contrast to // countCertificatesByNames subdomains are NOT considered.
[ "countCertificatesByExactNames", "returns", "for", "a", "single", "domain", "the", "count", "of", "certificates", "issued", "in", "the", "given", "time", "range", "for", "that", "domain", ".", "In", "contrast", "to", "countCertificatesByNames", "subdomains", "are", "NOT", "considered", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L486-L493
train
letsencrypt/boulder
sa/sa.go
countCertificates
func (ssa *SQLStorageAuthority) countCertificates(db dbSelector, domain string, earliest, latest time.Time, query string) (int, error) { var serials []string _, err := db.Select( &serials, query, map[string]interface{}{ "reversedDomain": ReverseName(domain), "earliest": earliest, "latest": latest, }) if err == sql.ErrNoRows { return 0, nil } else if err != nil { return 0, err } // Deduplicate serials returning a count of unique serials serialMap := make(map[string]struct{}, len(serials)) for _, s := range serials { serialMap[s] = struct{}{} } return len(serialMap), nil }
go
func (ssa *SQLStorageAuthority) countCertificates(db dbSelector, domain string, earliest, latest time.Time, query string) (int, error) { var serials []string _, err := db.Select( &serials, query, map[string]interface{}{ "reversedDomain": ReverseName(domain), "earliest": earliest, "latest": latest, }) if err == sql.ErrNoRows { return 0, nil } else if err != nil { return 0, err } // Deduplicate serials returning a count of unique serials serialMap := make(map[string]struct{}, len(serials)) for _, s := range serials { serialMap[s] = struct{}{} } return len(serialMap), nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "countCertificates", "(", "db", "dbSelector", ",", "domain", "string", ",", "earliest", ",", "latest", "time", ".", "Time", ",", "query", "string", ")", "(", "int", ",", "error", ")", "{", "var", "serials", "[", "]", "string", "\n", "_", ",", "err", ":=", "db", ".", "Select", "(", "&", "serials", ",", "query", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "ReverseName", "(", "domain", ")", ",", "\"", "\"", ":", "earliest", ",", "\"", "\"", ":", "latest", ",", "}", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "0", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// Deduplicate serials returning a count of unique serials", "serialMap", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ",", "len", "(", "serials", ")", ")", "\n", "for", "_", ",", "s", ":=", "range", "serials", "{", "serialMap", "[", "s", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "return", "len", "(", "serialMap", ")", ",", "nil", "\n", "}" ]
// countCertificates returns, for a single domain, the count of certificate // issuances in the given time range for that domain using the // provided query assumed to be either `countCertificatesExactSelect`, // or `countCertificatesSelect`.
[ "countCertificates", "returns", "for", "a", "single", "domain", "the", "count", "of", "certificate", "issuances", "in", "the", "given", "time", "range", "for", "that", "domain", "using", "the", "provided", "query", "assumed", "to", "be", "either", "countCertificatesExactSelect", "or", "countCertificatesSelect", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L499-L521
train
letsencrypt/boulder
sa/sa.go
GetCertificate
func (ssa *SQLStorageAuthority) GetCertificate(ctx context.Context, serial string) (core.Certificate, error) { if !core.ValidSerial(serial) { err := fmt.Errorf("Invalid certificate serial %s", serial) return core.Certificate{}, err } cert, err := SelectCertificate(ssa.dbMap.WithContext(ctx), "WHERE serial = ?", serial) if err == sql.ErrNoRows { return core.Certificate{}, berrors.NotFoundError("certificate with serial %q not found", serial) } if err != nil { return core.Certificate{}, err } return cert, err }
go
func (ssa *SQLStorageAuthority) GetCertificate(ctx context.Context, serial string) (core.Certificate, error) { if !core.ValidSerial(serial) { err := fmt.Errorf("Invalid certificate serial %s", serial) return core.Certificate{}, err } cert, err := SelectCertificate(ssa.dbMap.WithContext(ctx), "WHERE serial = ?", serial) if err == sql.ErrNoRows { return core.Certificate{}, berrors.NotFoundError("certificate with serial %q not found", serial) } if err != nil { return core.Certificate{}, err } return cert, err }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetCertificate", "(", "ctx", "context", ".", "Context", ",", "serial", "string", ")", "(", "core", ".", "Certificate", ",", "error", ")", "{", "if", "!", "core", ".", "ValidSerial", "(", "serial", ")", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "serial", ")", "\n", "return", "core", ".", "Certificate", "{", "}", ",", "err", "\n", "}", "\n\n", "cert", ",", "err", ":=", "SelectCertificate", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "\"", "\"", ",", "serial", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "core", ".", "Certificate", "{", "}", ",", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "serial", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "core", ".", "Certificate", "{", "}", ",", "err", "\n", "}", "\n", "return", "cert", ",", "err", "\n", "}" ]
// GetCertificate takes a serial number and returns the corresponding // certificate, or error if it does not exist.
[ "GetCertificate", "takes", "a", "serial", "number", "and", "returns", "the", "corresponding", "certificate", "or", "error", "if", "it", "does", "not", "exist", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L525-L539
train
letsencrypt/boulder
sa/sa.go
GetCertificateStatus
func (ssa *SQLStorageAuthority) GetCertificateStatus(ctx context.Context, serial string) (core.CertificateStatus, error) { if !core.ValidSerial(serial) { err := fmt.Errorf("Invalid certificate serial %s", serial) return core.CertificateStatus{}, err } var status core.CertificateStatus statusObj, err := ssa.dbMap.WithContext(ctx).Get(certStatusModel{}, serial) if err != nil { return status, err } if statusObj == nil { return status, nil } statusModel := statusObj.(*certStatusModel) status = core.CertificateStatus{ Serial: statusModel.Serial, Status: statusModel.Status, OCSPLastUpdated: statusModel.OCSPLastUpdated, RevokedDate: statusModel.RevokedDate, RevokedReason: statusModel.RevokedReason, LastExpirationNagSent: statusModel.LastExpirationNagSent, OCSPResponse: statusModel.OCSPResponse, NotAfter: statusModel.NotAfter, IsExpired: statusModel.IsExpired, } return status, nil }
go
func (ssa *SQLStorageAuthority) GetCertificateStatus(ctx context.Context, serial string) (core.CertificateStatus, error) { if !core.ValidSerial(serial) { err := fmt.Errorf("Invalid certificate serial %s", serial) return core.CertificateStatus{}, err } var status core.CertificateStatus statusObj, err := ssa.dbMap.WithContext(ctx).Get(certStatusModel{}, serial) if err != nil { return status, err } if statusObj == nil { return status, nil } statusModel := statusObj.(*certStatusModel) status = core.CertificateStatus{ Serial: statusModel.Serial, Status: statusModel.Status, OCSPLastUpdated: statusModel.OCSPLastUpdated, RevokedDate: statusModel.RevokedDate, RevokedReason: statusModel.RevokedReason, LastExpirationNagSent: statusModel.LastExpirationNagSent, OCSPResponse: statusModel.OCSPResponse, NotAfter: statusModel.NotAfter, IsExpired: statusModel.IsExpired, } return status, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetCertificateStatus", "(", "ctx", "context", ".", "Context", ",", "serial", "string", ")", "(", "core", ".", "CertificateStatus", ",", "error", ")", "{", "if", "!", "core", ".", "ValidSerial", "(", "serial", ")", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "serial", ")", "\n", "return", "core", ".", "CertificateStatus", "{", "}", ",", "err", "\n", "}", "\n\n", "var", "status", "core", ".", "CertificateStatus", "\n", "statusObj", ",", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "Get", "(", "certStatusModel", "{", "}", ",", "serial", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ",", "err", "\n", "}", "\n", "if", "statusObj", "==", "nil", "{", "return", "status", ",", "nil", "\n", "}", "\n", "statusModel", ":=", "statusObj", ".", "(", "*", "certStatusModel", ")", "\n", "status", "=", "core", ".", "CertificateStatus", "{", "Serial", ":", "statusModel", ".", "Serial", ",", "Status", ":", "statusModel", ".", "Status", ",", "OCSPLastUpdated", ":", "statusModel", ".", "OCSPLastUpdated", ",", "RevokedDate", ":", "statusModel", ".", "RevokedDate", ",", "RevokedReason", ":", "statusModel", ".", "RevokedReason", ",", "LastExpirationNagSent", ":", "statusModel", ".", "LastExpirationNagSent", ",", "OCSPResponse", ":", "statusModel", ".", "OCSPResponse", ",", "NotAfter", ":", "statusModel", ".", "NotAfter", ",", "IsExpired", ":", "statusModel", ".", "IsExpired", ",", "}", "\n\n", "return", "status", ",", "nil", "\n", "}" ]
// GetCertificateStatus takes a hexadecimal string representing the full 128-bit serial // number of a certificate and returns data about that certificate's current // validity.
[ "GetCertificateStatus", "takes", "a", "hexadecimal", "string", "representing", "the", "full", "128", "-", "bit", "serial", "number", "of", "a", "certificate", "and", "returns", "data", "about", "that", "certificate", "s", "current", "validity", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L544-L572
train
letsencrypt/boulder
sa/sa.go
NewRegistration
func (ssa *SQLStorageAuthority) NewRegistration(ctx context.Context, reg core.Registration) (core.Registration, error) { reg.CreatedAt = ssa.clk.Now() rm, err := registrationToModel(&reg) if err != nil { return reg, err } err = ssa.dbMap.WithContext(ctx).Insert(rm) if err != nil { return reg, err } return modelToRegistration(rm) }
go
func (ssa *SQLStorageAuthority) NewRegistration(ctx context.Context, reg core.Registration) (core.Registration, error) { reg.CreatedAt = ssa.clk.Now() rm, err := registrationToModel(&reg) if err != nil { return reg, err } err = ssa.dbMap.WithContext(ctx).Insert(rm) if err != nil { return reg, err } return modelToRegistration(rm) }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "NewRegistration", "(", "ctx", "context", ".", "Context", ",", "reg", "core", ".", "Registration", ")", "(", "core", ".", "Registration", ",", "error", ")", "{", "reg", ".", "CreatedAt", "=", "ssa", ".", "clk", ".", "Now", "(", ")", "\n", "rm", ",", "err", ":=", "registrationToModel", "(", "&", "reg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "reg", ",", "err", "\n", "}", "\n", "err", "=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "Insert", "(", "rm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "reg", ",", "err", "\n", "}", "\n", "return", "modelToRegistration", "(", "rm", ")", "\n", "}" ]
// NewRegistration stores a new Registration
[ "NewRegistration", "stores", "a", "new", "Registration" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L575-L586
train
letsencrypt/boulder
sa/sa.go
UpdateRegistration
func (ssa *SQLStorageAuthority) UpdateRegistration(ctx context.Context, reg core.Registration) error { const query = "WHERE id = ?" model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, reg.ID) if err == sql.ErrNoRows { return berrors.NotFoundError("registration with ID '%d' not found", reg.ID) } updatedRegModel, err := registrationToModel(&reg) if err != nil { return err } // Copy the existing registration model's LockCol to the new updated // registration model's LockCol updatedRegModel.LockCol = model.LockCol n, err := ssa.dbMap.WithContext(ctx).Update(updatedRegModel) if err != nil { return err } if n == 0 { return berrors.NotFoundError("registration with ID '%d' not found", reg.ID) } return nil }
go
func (ssa *SQLStorageAuthority) UpdateRegistration(ctx context.Context, reg core.Registration) error { const query = "WHERE id = ?" model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, reg.ID) if err == sql.ErrNoRows { return berrors.NotFoundError("registration with ID '%d' not found", reg.ID) } updatedRegModel, err := registrationToModel(&reg) if err != nil { return err } // Copy the existing registration model's LockCol to the new updated // registration model's LockCol updatedRegModel.LockCol = model.LockCol n, err := ssa.dbMap.WithContext(ctx).Update(updatedRegModel) if err != nil { return err } if n == 0 { return berrors.NotFoundError("registration with ID '%d' not found", reg.ID) } return nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "UpdateRegistration", "(", "ctx", "context", ".", "Context", ",", "reg", "core", ".", "Registration", ")", "error", "{", "const", "query", "=", "\"", "\"", "\n", "model", ",", "err", ":=", "selectRegistration", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "query", ",", "reg", ".", "ID", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "reg", ".", "ID", ")", "\n", "}", "\n\n", "updatedRegModel", ",", "err", ":=", "registrationToModel", "(", "&", "reg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Copy the existing registration model's LockCol to the new updated", "// registration model's LockCol", "updatedRegModel", ".", "LockCol", "=", "model", ".", "LockCol", "\n", "n", ",", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "Update", "(", "updatedRegModel", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "n", "==", "0", "{", "return", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "reg", ".", "ID", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UpdateRegistration stores an updated Registration
[ "UpdateRegistration", "stores", "an", "updated", "Registration" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L641-L665
train
letsencrypt/boulder
sa/sa.go
NewPendingAuthorization
func (ssa *SQLStorageAuthority) NewPendingAuthorization(ctx context.Context, authz core.Authorization) (core.Authorization, error) { var output core.Authorization tx, err := ssa.dbMap.Begin() if err != nil { return output, err } txWithCtx := tx.WithContext(ctx) // Create a random ID and check that it doesn't exist already authz.ID = core.NewToken() for existingPending(txWithCtx, authz.ID) || existingFinal(txWithCtx, authz.ID) { authz.ID = core.NewToken() } // Insert a stub row in pending pendingAuthz := pendingauthzModel{Authorization: authz} err = txWithCtx.Insert(&pendingAuthz) if err != nil { err = Rollback(tx, err) return output, err } for i, c := range authz.Challenges { challModel, err := challengeToModel(&c, pendingAuthz.ID) if err != nil { err = Rollback(tx, err) return output, err } // Magic happens here: Gorp will modify challModel, setting challModel.ID // to the auto-increment primary key. This is important because we want // the challenge objects inside the Authorization we return to know their // IDs, so they can have proper URLs. // See https://godoc.org/github.com/coopernurse/gorp#DbMap.Insert err = txWithCtx.Insert(challModel) if err != nil { err = Rollback(tx, err) return output, err } challenge, err := modelToChallenge(challModel) if err != nil { err = Rollback(tx, err) return output, err } authz.Challenges[i] = challenge } err = tx.Commit() output = pendingAuthz.Authorization output.Challenges = authz.Challenges return output, err }
go
func (ssa *SQLStorageAuthority) NewPendingAuthorization(ctx context.Context, authz core.Authorization) (core.Authorization, error) { var output core.Authorization tx, err := ssa.dbMap.Begin() if err != nil { return output, err } txWithCtx := tx.WithContext(ctx) // Create a random ID and check that it doesn't exist already authz.ID = core.NewToken() for existingPending(txWithCtx, authz.ID) || existingFinal(txWithCtx, authz.ID) { authz.ID = core.NewToken() } // Insert a stub row in pending pendingAuthz := pendingauthzModel{Authorization: authz} err = txWithCtx.Insert(&pendingAuthz) if err != nil { err = Rollback(tx, err) return output, err } for i, c := range authz.Challenges { challModel, err := challengeToModel(&c, pendingAuthz.ID) if err != nil { err = Rollback(tx, err) return output, err } // Magic happens here: Gorp will modify challModel, setting challModel.ID // to the auto-increment primary key. This is important because we want // the challenge objects inside the Authorization we return to know their // IDs, so they can have proper URLs. // See https://godoc.org/github.com/coopernurse/gorp#DbMap.Insert err = txWithCtx.Insert(challModel) if err != nil { err = Rollback(tx, err) return output, err } challenge, err := modelToChallenge(challModel) if err != nil { err = Rollback(tx, err) return output, err } authz.Challenges[i] = challenge } err = tx.Commit() output = pendingAuthz.Authorization output.Challenges = authz.Challenges return output, err }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "NewPendingAuthorization", "(", "ctx", "context", ".", "Context", ",", "authz", "core", ".", "Authorization", ")", "(", "core", ".", "Authorization", ",", "error", ")", "{", "var", "output", "core", ".", "Authorization", "\n\n", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "output", ",", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n\n", "// Create a random ID and check that it doesn't exist already", "authz", ".", "ID", "=", "core", ".", "NewToken", "(", ")", "\n", "for", "existingPending", "(", "txWithCtx", ",", "authz", ".", "ID", ")", "||", "existingFinal", "(", "txWithCtx", ",", "authz", ".", "ID", ")", "{", "authz", ".", "ID", "=", "core", ".", "NewToken", "(", ")", "\n", "}", "\n\n", "// Insert a stub row in pending", "pendingAuthz", ":=", "pendingauthzModel", "{", "Authorization", ":", "authz", "}", "\n", "err", "=", "txWithCtx", ".", "Insert", "(", "&", "pendingAuthz", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "Rollback", "(", "tx", ",", "err", ")", "\n", "return", "output", ",", "err", "\n", "}", "\n\n", "for", "i", ",", "c", ":=", "range", "authz", ".", "Challenges", "{", "challModel", ",", "err", ":=", "challengeToModel", "(", "&", "c", ",", "pendingAuthz", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "Rollback", "(", "tx", ",", "err", ")", "\n", "return", "output", ",", "err", "\n", "}", "\n", "// Magic happens here: Gorp will modify challModel, setting challModel.ID", "// to the auto-increment primary key. This is important because we want", "// the challenge objects inside the Authorization we return to know their", "// IDs, so they can have proper URLs.", "// See https://godoc.org/github.com/coopernurse/gorp#DbMap.Insert", "err", "=", "txWithCtx", ".", "Insert", "(", "challModel", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "Rollback", "(", "tx", ",", "err", ")", "\n", "return", "output", ",", "err", "\n", "}", "\n", "challenge", ",", "err", ":=", "modelToChallenge", "(", "challModel", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "Rollback", "(", "tx", ",", "err", ")", "\n", "return", "output", ",", "err", "\n", "}", "\n", "authz", ".", "Challenges", "[", "i", "]", "=", "challenge", "\n", "}", "\n\n", "err", "=", "tx", ".", "Commit", "(", ")", "\n", "output", "=", "pendingAuthz", ".", "Authorization", "\n", "output", ".", "Challenges", "=", "authz", ".", "Challenges", "\n", "return", "output", ",", "err", "\n", "}" ]
// NewPendingAuthorization retrieves a pending authorization for // authz.Identifier if one exists, or creates a new one otherwise.
[ "NewPendingAuthorization", "retrieves", "a", "pending", "authorization", "for", "authz", ".", "Identifier", "if", "one", "exists", "or", "creates", "a", "new", "one", "otherwise", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L669-L721
train
letsencrypt/boulder
sa/sa.go
GetPendingAuthorization
func (ssa *SQLStorageAuthority) GetPendingAuthorization( ctx context.Context, req *sapb.GetPendingAuthorizationRequest, ) (*core.Authorization, error) { identifierJSON, err := json.Marshal(core.AcmeIdentifier{ Type: core.IdentifierType(*req.IdentifierType), Value: *req.IdentifierValue, }) if err != nil { return nil, err } // Note: This will use the index on `registrationId`, `expires`, which should // keep the amount of scanning to a minimum. That index does not include the // identifier, so accounts with huge numbers of pending authzs may result in // slow queries here. pa, err := selectPendingAuthz(ssa.dbMap.WithContext(ctx), `WHERE registrationID = :regID AND identifier = :identifierJSON AND status = :status AND expires > :validUntil ORDER BY expires ASC LIMIT 1`, map[string]interface{}{ "regID": *req.RegistrationID, "identifierJSON": identifierJSON, "status": string(core.StatusPending), "validUntil": time.Unix(0, *req.ValidUntil), }) if err == sql.ErrNoRows { return nil, berrors.NotFoundError("pending authz not found") } else if err == nil { // We found an authz, but we still need to fetch its challenges. To // simplify things, just call GetAuthorization, which takes care of that. authz, err := ssa.GetAuthorization(ctx, pa.ID) return &authz, err } else { // Any error other than ErrNoRows; return the error return nil, err } }
go
func (ssa *SQLStorageAuthority) GetPendingAuthorization( ctx context.Context, req *sapb.GetPendingAuthorizationRequest, ) (*core.Authorization, error) { identifierJSON, err := json.Marshal(core.AcmeIdentifier{ Type: core.IdentifierType(*req.IdentifierType), Value: *req.IdentifierValue, }) if err != nil { return nil, err } // Note: This will use the index on `registrationId`, `expires`, which should // keep the amount of scanning to a minimum. That index does not include the // identifier, so accounts with huge numbers of pending authzs may result in // slow queries here. pa, err := selectPendingAuthz(ssa.dbMap.WithContext(ctx), `WHERE registrationID = :regID AND identifier = :identifierJSON AND status = :status AND expires > :validUntil ORDER BY expires ASC LIMIT 1`, map[string]interface{}{ "regID": *req.RegistrationID, "identifierJSON": identifierJSON, "status": string(core.StatusPending), "validUntil": time.Unix(0, *req.ValidUntil), }) if err == sql.ErrNoRows { return nil, berrors.NotFoundError("pending authz not found") } else if err == nil { // We found an authz, but we still need to fetch its challenges. To // simplify things, just call GetAuthorization, which takes care of that. authz, err := ssa.GetAuthorization(ctx, pa.ID) return &authz, err } else { // Any error other than ErrNoRows; return the error return nil, err } }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetPendingAuthorization", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "GetPendingAuthorizationRequest", ",", ")", "(", "*", "core", ".", "Authorization", ",", "error", ")", "{", "identifierJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "core", ".", "AcmeIdentifier", "{", "Type", ":", "core", ".", "IdentifierType", "(", "*", "req", ".", "IdentifierType", ")", ",", "Value", ":", "*", "req", ".", "IdentifierValue", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Note: This will use the index on `registrationId`, `expires`, which should", "// keep the amount of scanning to a minimum. That index does not include the", "// identifier, so accounts with huge numbers of pending authzs may result in", "// slow queries here.", "pa", ",", "err", ":=", "selectPendingAuthz", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "`WHERE registrationID = :regID\n\t\t\t AND identifier = :identifierJSON\n\t\t\t AND status = :status\n\t\t\t AND expires > :validUntil\n\t\t ORDER BY expires ASC\n\t\t LIMIT 1`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "*", "req", ".", "RegistrationID", ",", "\"", "\"", ":", "identifierJSON", ",", "\"", "\"", ":", "string", "(", "core", ".", "StatusPending", ")", ",", "\"", "\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "ValidUntil", ")", ",", "}", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "nil", ",", "berrors", ".", "NotFoundError", "(", "\"", "\"", ")", "\n", "}", "else", "if", "err", "==", "nil", "{", "// We found an authz, but we still need to fetch its challenges. To", "// simplify things, just call GetAuthorization, which takes care of that.", "authz", ",", "err", ":=", "ssa", ".", "GetAuthorization", "(", "ctx", ",", "pa", ".", "ID", ")", "\n", "return", "&", "authz", ",", "err", "\n", "}", "else", "{", "// Any error other than ErrNoRows; return the error", "return", "nil", ",", "err", "\n", "}", "\n\n", "}" ]
// GetPendingAuthorization returns the most recent Pending authorization // with the given identifier, if available.
[ "GetPendingAuthorization", "returns", "the", "most", "recent", "Pending", "authorization", "with", "the", "given", "identifier", "if", "available", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L725-L766
train
letsencrypt/boulder
sa/sa.go
FinalizeAuthorization
func (ssa *SQLStorageAuthority) FinalizeAuthorization(ctx context.Context, authz core.Authorization) error { tx, err := ssa.dbMap.Begin() if err != nil { return err } txWithCtx := tx.WithContext(ctx) // Check that a pending authz exists if !existingPending(txWithCtx, authz.ID) { err = berrors.NotFoundError("authorization with ID %q not found", authz.ID) return Rollback(tx, err) } if statusIsPending(authz.Status) { err = berrors.InternalServerError("authorization to finalize is pending (ID %q)", authz.ID) return Rollback(tx, err) } auth := &authzModel{authz} pa, err := selectPendingAuthz(txWithCtx, "WHERE id = ?", authz.ID) if err == sql.ErrNoRows { return Rollback(tx, berrors.NotFoundError("authorization with ID %q not found", authz.ID)) } if err != nil { return Rollback(tx, err) } err = txWithCtx.Insert(auth) if err != nil { return Rollback(tx, err) } _, err = txWithCtx.Delete(pa) if err != nil { return Rollback(tx, err) } err = updateChallenges(txWithCtx, authz.ID, authz.Challenges) if err != nil { return Rollback(tx, err) } return tx.Commit() }
go
func (ssa *SQLStorageAuthority) FinalizeAuthorization(ctx context.Context, authz core.Authorization) error { tx, err := ssa.dbMap.Begin() if err != nil { return err } txWithCtx := tx.WithContext(ctx) // Check that a pending authz exists if !existingPending(txWithCtx, authz.ID) { err = berrors.NotFoundError("authorization with ID %q not found", authz.ID) return Rollback(tx, err) } if statusIsPending(authz.Status) { err = berrors.InternalServerError("authorization to finalize is pending (ID %q)", authz.ID) return Rollback(tx, err) } auth := &authzModel{authz} pa, err := selectPendingAuthz(txWithCtx, "WHERE id = ?", authz.ID) if err == sql.ErrNoRows { return Rollback(tx, berrors.NotFoundError("authorization with ID %q not found", authz.ID)) } if err != nil { return Rollback(tx, err) } err = txWithCtx.Insert(auth) if err != nil { return Rollback(tx, err) } _, err = txWithCtx.Delete(pa) if err != nil { return Rollback(tx, err) } err = updateChallenges(txWithCtx, authz.ID, authz.Challenges) if err != nil { return Rollback(tx, err) } return tx.Commit() }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "FinalizeAuthorization", "(", "ctx", "context", ".", "Context", ",", "authz", "core", ".", "Authorization", ")", "error", "{", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n\n", "// Check that a pending authz exists", "if", "!", "existingPending", "(", "txWithCtx", ",", "authz", ".", "ID", ")", "{", "err", "=", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "authz", ".", "ID", ")", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "if", "statusIsPending", "(", "authz", ".", "Status", ")", "{", "err", "=", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "authz", ".", "ID", ")", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "auth", ":=", "&", "authzModel", "{", "authz", "}", "\n", "pa", ",", "err", ":=", "selectPendingAuthz", "(", "txWithCtx", ",", "\"", "\"", ",", "authz", ".", "ID", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "Rollback", "(", "tx", ",", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "authz", ".", "ID", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "txWithCtx", ".", "Insert", "(", "auth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "txWithCtx", ".", "Delete", "(", "pa", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "updateChallenges", "(", "txWithCtx", ",", "authz", ".", "ID", ",", "authz", ".", "Challenges", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "return", "tx", ".", "Commit", "(", ")", "\n", "}" ]
// FinalizeAuthorization converts a Pending Authorization to a final one. If the // Authorization is not found a berrors.NotFound result is returned. If the // Authorization is status pending a berrors.InternalServer error is returned.
[ "FinalizeAuthorization", "converts", "a", "Pending", "Authorization", "to", "a", "final", "one", ".", "If", "the", "Authorization", "is", "not", "found", "a", "berrors", ".", "NotFound", "result", "is", "returned", ".", "If", "the", "Authorization", "is", "status", "pending", "a", "berrors", ".", "InternalServer", "error", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L771-L813
train
letsencrypt/boulder
sa/sa.go
RevokeAuthorizationsByDomain
func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain(ctx context.Context, ident core.AcmeIdentifier) (int64, int64, error) { identifierJSON, err := json.Marshal(ident) if err != nil { return 0, 0, err } identifier := string(identifierJSON) results := []int64{0, 0} now := ssa.clk.Now() for i, table := range authorizationTables { for { authz, err := getAuthorizationIDsByDomain(ssa.dbMap.WithContext(ctx), table, identifier, now) if err != nil { return results[0], results[1], err } numAuthz := len(authz) if numAuthz == 0 { break } numRevoked, err := revokeAuthorizations(ssa.dbMap.WithContext(ctx), table, authz) if err != nil { return results[0], results[1], err } results[i] += numRevoked if numRevoked < int64(numAuthz) { return results[0], results[1], fmt.Errorf("Didn't revoke all found authorizations") } } } return results[0], results[1], nil }
go
func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain(ctx context.Context, ident core.AcmeIdentifier) (int64, int64, error) { identifierJSON, err := json.Marshal(ident) if err != nil { return 0, 0, err } identifier := string(identifierJSON) results := []int64{0, 0} now := ssa.clk.Now() for i, table := range authorizationTables { for { authz, err := getAuthorizationIDsByDomain(ssa.dbMap.WithContext(ctx), table, identifier, now) if err != nil { return results[0], results[1], err } numAuthz := len(authz) if numAuthz == 0 { break } numRevoked, err := revokeAuthorizations(ssa.dbMap.WithContext(ctx), table, authz) if err != nil { return results[0], results[1], err } results[i] += numRevoked if numRevoked < int64(numAuthz) { return results[0], results[1], fmt.Errorf("Didn't revoke all found authorizations") } } } return results[0], results[1], nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "RevokeAuthorizationsByDomain", "(", "ctx", "context", ".", "Context", ",", "ident", "core", ".", "AcmeIdentifier", ")", "(", "int64", ",", "int64", ",", "error", ")", "{", "identifierJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "ident", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "identifier", ":=", "string", "(", "identifierJSON", ")", "\n", "results", ":=", "[", "]", "int64", "{", "0", ",", "0", "}", "\n\n", "now", ":=", "ssa", ".", "clk", ".", "Now", "(", ")", "\n", "for", "i", ",", "table", ":=", "range", "authorizationTables", "{", "for", "{", "authz", ",", "err", ":=", "getAuthorizationIDsByDomain", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "table", ",", "identifier", ",", "now", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", "[", "0", "]", ",", "results", "[", "1", "]", ",", "err", "\n", "}", "\n", "numAuthz", ":=", "len", "(", "authz", ")", "\n", "if", "numAuthz", "==", "0", "{", "break", "\n", "}", "\n\n", "numRevoked", ",", "err", ":=", "revokeAuthorizations", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "table", ",", "authz", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", "[", "0", "]", ",", "results", "[", "1", "]", ",", "err", "\n", "}", "\n", "results", "[", "i", "]", "+=", "numRevoked", "\n", "if", "numRevoked", "<", "int64", "(", "numAuthz", ")", "{", "return", "results", "[", "0", "]", ",", "results", "[", "1", "]", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "results", "[", "0", "]", ",", "results", "[", "1", "]", ",", "nil", "\n", "}" ]
// RevokeAuthorizationsByDomain invalidates all pending or finalized authorizations // for a specific domain
[ "RevokeAuthorizationsByDomain", "invalidates", "all", "pending", "or", "finalized", "authorizations", "for", "a", "specific", "domain" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L817-L849
train
letsencrypt/boulder
sa/sa.go
RevokeAuthorizationsByDomain2
func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain2(ctx context.Context, req *sapb.RevokeAuthorizationsByDomainRequest) (*corepb.Empty, error) { finalRevoked, pendingRevoked, err := ssa.RevokeAuthorizationsByDomain( ctx, core.AcmeIdentifier{ Type: core.IdentifierDNS, Value: *req.Domain, }) if err != nil { return nil, err } var revokedTotal int64 = finalRevoked + pendingRevoked for { var ids []int64 ids, err := ssa.getAuthorizationIDsByDomain2(ctx, *req.Domain) if err != nil { if err == sql.ErrNoRows { break } return nil, err } if len(ids) == 0 { break } if err = ssa.revokeAuthorizations2(ctx, ids); err != nil { return nil, err } revokedTotal += int64(len(ids)) } // If no authorizations were revoked return a NotFoundError so that the caller // can decide whether that was an expected result or not. Some callers (e.g. // the admin-revoker tool) may wish to handle this case specifically. if revokedTotal == 0 { return nil, berrors.NotFoundError( "no authorizations to revoke for %q", *req.Domain) } return &corepb.Empty{}, nil }
go
func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain2(ctx context.Context, req *sapb.RevokeAuthorizationsByDomainRequest) (*corepb.Empty, error) { finalRevoked, pendingRevoked, err := ssa.RevokeAuthorizationsByDomain( ctx, core.AcmeIdentifier{ Type: core.IdentifierDNS, Value: *req.Domain, }) if err != nil { return nil, err } var revokedTotal int64 = finalRevoked + pendingRevoked for { var ids []int64 ids, err := ssa.getAuthorizationIDsByDomain2(ctx, *req.Domain) if err != nil { if err == sql.ErrNoRows { break } return nil, err } if len(ids) == 0 { break } if err = ssa.revokeAuthorizations2(ctx, ids); err != nil { return nil, err } revokedTotal += int64(len(ids)) } // If no authorizations were revoked return a NotFoundError so that the caller // can decide whether that was an expected result or not. Some callers (e.g. // the admin-revoker tool) may wish to handle this case specifically. if revokedTotal == 0 { return nil, berrors.NotFoundError( "no authorizations to revoke for %q", *req.Domain) } return &corepb.Empty{}, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "RevokeAuthorizationsByDomain2", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "RevokeAuthorizationsByDomainRequest", ")", "(", "*", "corepb", ".", "Empty", ",", "error", ")", "{", "finalRevoked", ",", "pendingRevoked", ",", "err", ":=", "ssa", ".", "RevokeAuthorizationsByDomain", "(", "ctx", ",", "core", ".", "AcmeIdentifier", "{", "Type", ":", "core", ".", "IdentifierDNS", ",", "Value", ":", "*", "req", ".", "Domain", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "revokedTotal", "int64", "=", "finalRevoked", "+", "pendingRevoked", "\n", "for", "{", "var", "ids", "[", "]", "int64", "\n", "ids", ",", "err", ":=", "ssa", ".", "getAuthorizationIDsByDomain2", "(", "ctx", ",", "*", "req", ".", "Domain", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "break", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "ids", ")", "==", "0", "{", "break", "\n", "}", "\n", "if", "err", "=", "ssa", ".", "revokeAuthorizations2", "(", "ctx", ",", "ids", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "revokedTotal", "+=", "int64", "(", "len", "(", "ids", ")", ")", "\n", "}", "\n", "// If no authorizations were revoked return a NotFoundError so that the caller", "// can decide whether that was an expected result or not. Some callers (e.g.", "// the admin-revoker tool) may wish to handle this case specifically.", "if", "revokedTotal", "==", "0", "{", "return", "nil", ",", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "*", "req", ".", "Domain", ")", "\n", "}", "\n", "return", "&", "corepb", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// RevokeAuthorizationsByDomain2 invalidates all pending or valid authorizations for a // specific domain. This method is intended to deprecate RevokeAuthorizationsByDomain.
[ "RevokeAuthorizationsByDomain2", "invalidates", "all", "pending", "or", "valid", "authorizations", "for", "a", "specific", "domain", ".", "This", "method", "is", "intended", "to", "deprecate", "RevokeAuthorizationsByDomain", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L886-L923
train
letsencrypt/boulder
sa/sa.go
AddCertificate
func (ssa *SQLStorageAuthority) AddCertificate( ctx context.Context, certDER []byte, regID int64, ocspResponse []byte, issued *time.Time) (string, error) { parsedCertificate, err := x509.ParseCertificate(certDER) if err != nil { return "", err } digest := core.Fingerprint256(certDER) serial := core.SerialToString(parsedCertificate.SerialNumber) cert := &core.Certificate{ RegistrationID: regID, Serial: serial, Digest: digest, DER: certDER, Issued: *issued, Expires: parsedCertificate.NotAfter, } certStatus := &certStatusModel{ Status: core.OCSPStatus("good"), OCSPLastUpdated: time.Time{}, OCSPResponse: []byte{}, Serial: serial, RevokedDate: time.Time{}, RevokedReason: 0, NotAfter: parsedCertificate.NotAfter, } if len(ocspResponse) != 0 { certStatus.OCSPResponse = ocspResponse certStatus.OCSPLastUpdated = ssa.clk.Now() } tx, err := ssa.dbMap.Begin() if err != nil { return "", err } txWithCtx := tx.WithContext(ctx) // Note: will fail on duplicate serials. Extremely unlikely to happen and soon // to be fixed by redesign. Reference issue // https://github.com/letsencrypt/boulder/issues/2265 for more err = txWithCtx.Insert(cert) if err != nil { if strings.HasPrefix(err.Error(), "Error 1062: Duplicate entry") { err = berrors.DuplicateError("cannot add a duplicate cert") } return "", Rollback(tx, err) } err = txWithCtx.Insert(certStatus) if err != nil { if strings.HasPrefix(err.Error(), "Error 1062: Duplicate entry") { err = berrors.DuplicateError("cannot add a duplicate cert status") } return "", Rollback(tx, err) } // NOTE(@cpu): When we collect up names to check if an FQDN set exists (e.g. // that it is a renewal) we use just the DNSNames from the certificate and // ignore the Subject Common Name (if any). This is a safe assumption because // if a certificate we issued were to have a Subj. CN not present as a SAN it // would be a misissuance and miscalculating whether the cert is a renewal or // not for the purpose of rate limiting is the least of our troubles. isRenewal, err := ssa.checkFQDNSetExists( txWithCtx.SelectOne, parsedCertificate.DNSNames) if err != nil { return "", Rollback(tx, err) } err = addIssuedNames(txWithCtx, parsedCertificate, isRenewal) if err != nil { return "", Rollback(tx, err) } // Add to the rate limit table, but only for new certificates. Renewals // don't count against the certificatesPerName limit. if !isRenewal { timeToTheHour := parsedCertificate.NotBefore.Round(time.Hour) err = ssa.addCertificatesPerName(ctx, txWithCtx, parsedCertificate.DNSNames, timeToTheHour) if err != nil { return "", Rollback(tx, err) } } err = addFQDNSet( txWithCtx, parsedCertificate.DNSNames, serial, parsedCertificate.NotBefore, parsedCertificate.NotAfter, ) if err != nil { return "", Rollback(tx, err) } return digest, tx.Commit() }
go
func (ssa *SQLStorageAuthority) AddCertificate( ctx context.Context, certDER []byte, regID int64, ocspResponse []byte, issued *time.Time) (string, error) { parsedCertificate, err := x509.ParseCertificate(certDER) if err != nil { return "", err } digest := core.Fingerprint256(certDER) serial := core.SerialToString(parsedCertificate.SerialNumber) cert := &core.Certificate{ RegistrationID: regID, Serial: serial, Digest: digest, DER: certDER, Issued: *issued, Expires: parsedCertificate.NotAfter, } certStatus := &certStatusModel{ Status: core.OCSPStatus("good"), OCSPLastUpdated: time.Time{}, OCSPResponse: []byte{}, Serial: serial, RevokedDate: time.Time{}, RevokedReason: 0, NotAfter: parsedCertificate.NotAfter, } if len(ocspResponse) != 0 { certStatus.OCSPResponse = ocspResponse certStatus.OCSPLastUpdated = ssa.clk.Now() } tx, err := ssa.dbMap.Begin() if err != nil { return "", err } txWithCtx := tx.WithContext(ctx) // Note: will fail on duplicate serials. Extremely unlikely to happen and soon // to be fixed by redesign. Reference issue // https://github.com/letsencrypt/boulder/issues/2265 for more err = txWithCtx.Insert(cert) if err != nil { if strings.HasPrefix(err.Error(), "Error 1062: Duplicate entry") { err = berrors.DuplicateError("cannot add a duplicate cert") } return "", Rollback(tx, err) } err = txWithCtx.Insert(certStatus) if err != nil { if strings.HasPrefix(err.Error(), "Error 1062: Duplicate entry") { err = berrors.DuplicateError("cannot add a duplicate cert status") } return "", Rollback(tx, err) } // NOTE(@cpu): When we collect up names to check if an FQDN set exists (e.g. // that it is a renewal) we use just the DNSNames from the certificate and // ignore the Subject Common Name (if any). This is a safe assumption because // if a certificate we issued were to have a Subj. CN not present as a SAN it // would be a misissuance and miscalculating whether the cert is a renewal or // not for the purpose of rate limiting is the least of our troubles. isRenewal, err := ssa.checkFQDNSetExists( txWithCtx.SelectOne, parsedCertificate.DNSNames) if err != nil { return "", Rollback(tx, err) } err = addIssuedNames(txWithCtx, parsedCertificate, isRenewal) if err != nil { return "", Rollback(tx, err) } // Add to the rate limit table, but only for new certificates. Renewals // don't count against the certificatesPerName limit. if !isRenewal { timeToTheHour := parsedCertificate.NotBefore.Round(time.Hour) err = ssa.addCertificatesPerName(ctx, txWithCtx, parsedCertificate.DNSNames, timeToTheHour) if err != nil { return "", Rollback(tx, err) } } err = addFQDNSet( txWithCtx, parsedCertificate.DNSNames, serial, parsedCertificate.NotBefore, parsedCertificate.NotAfter, ) if err != nil { return "", Rollback(tx, err) } return digest, tx.Commit() }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "AddCertificate", "(", "ctx", "context", ".", "Context", ",", "certDER", "[", "]", "byte", ",", "regID", "int64", ",", "ocspResponse", "[", "]", "byte", ",", "issued", "*", "time", ".", "Time", ")", "(", "string", ",", "error", ")", "{", "parsedCertificate", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "certDER", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "digest", ":=", "core", ".", "Fingerprint256", "(", "certDER", ")", "\n", "serial", ":=", "core", ".", "SerialToString", "(", "parsedCertificate", ".", "SerialNumber", ")", "\n\n", "cert", ":=", "&", "core", ".", "Certificate", "{", "RegistrationID", ":", "regID", ",", "Serial", ":", "serial", ",", "Digest", ":", "digest", ",", "DER", ":", "certDER", ",", "Issued", ":", "*", "issued", ",", "Expires", ":", "parsedCertificate", ".", "NotAfter", ",", "}", "\n\n", "certStatus", ":=", "&", "certStatusModel", "{", "Status", ":", "core", ".", "OCSPStatus", "(", "\"", "\"", ")", ",", "OCSPLastUpdated", ":", "time", ".", "Time", "{", "}", ",", "OCSPResponse", ":", "[", "]", "byte", "{", "}", ",", "Serial", ":", "serial", ",", "RevokedDate", ":", "time", ".", "Time", "{", "}", ",", "RevokedReason", ":", "0", ",", "NotAfter", ":", "parsedCertificate", ".", "NotAfter", ",", "}", "\n", "if", "len", "(", "ocspResponse", ")", "!=", "0", "{", "certStatus", ".", "OCSPResponse", "=", "ocspResponse", "\n", "certStatus", ".", "OCSPLastUpdated", "=", "ssa", ".", "clk", ".", "Now", "(", ")", "\n", "}", "\n\n", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n\n", "// Note: will fail on duplicate serials. Extremely unlikely to happen and soon", "// to be fixed by redesign. Reference issue", "// https://github.com/letsencrypt/boulder/issues/2265 for more", "err", "=", "txWithCtx", ".", "Insert", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "if", "strings", ".", "HasPrefix", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "err", "=", "berrors", ".", "DuplicateError", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "txWithCtx", ".", "Insert", "(", "certStatus", ")", "\n", "if", "err", "!=", "nil", "{", "if", "strings", ".", "HasPrefix", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "err", "=", "berrors", ".", "DuplicateError", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "// NOTE(@cpu): When we collect up names to check if an FQDN set exists (e.g.", "// that it is a renewal) we use just the DNSNames from the certificate and", "// ignore the Subject Common Name (if any). This is a safe assumption because", "// if a certificate we issued were to have a Subj. CN not present as a SAN it", "// would be a misissuance and miscalculating whether the cert is a renewal or", "// not for the purpose of rate limiting is the least of our troubles.", "isRenewal", ",", "err", ":=", "ssa", ".", "checkFQDNSetExists", "(", "txWithCtx", ".", "SelectOne", ",", "parsedCertificate", ".", "DNSNames", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "addIssuedNames", "(", "txWithCtx", ",", "parsedCertificate", ",", "isRenewal", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "// Add to the rate limit table, but only for new certificates. Renewals", "// don't count against the certificatesPerName limit.", "if", "!", "isRenewal", "{", "timeToTheHour", ":=", "parsedCertificate", ".", "NotBefore", ".", "Round", "(", "time", ".", "Hour", ")", "\n", "err", "=", "ssa", ".", "addCertificatesPerName", "(", "ctx", ",", "txWithCtx", ",", "parsedCertificate", ".", "DNSNames", ",", "timeToTheHour", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "err", "=", "addFQDNSet", "(", "txWithCtx", ",", "parsedCertificate", ".", "DNSNames", ",", "serial", ",", "parsedCertificate", ".", "NotBefore", ",", "parsedCertificate", ".", "NotAfter", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "return", "digest", ",", "tx", ".", "Commit", "(", ")", "\n", "}" ]
// AddCertificate stores an issued certificate and returns the digest as // a string, or an error if any occurred.
[ "AddCertificate", "stores", "an", "issued", "certificate", "and", "returns", "the", "digest", "as", "a", "string", "or", "an", "error", "if", "any", "occurred", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L927-L1028
train
letsencrypt/boulder
sa/sa.go
CountPendingAuthorizations
func (ssa *SQLStorageAuthority) CountPendingAuthorizations(ctx context.Context, regID int64) (count int, err error) { err = ssa.dbMap.WithContext(ctx).SelectOne(&count, `SELECT count(1) FROM pendingAuthorizations WHERE registrationID = :regID AND expires > :now AND status = :pending`, map[string]interface{}{ "regID": regID, "now": ssa.clk.Now(), "pending": string(core.StatusPending), }) return }
go
func (ssa *SQLStorageAuthority) CountPendingAuthorizations(ctx context.Context, regID int64) (count int, err error) { err = ssa.dbMap.WithContext(ctx).SelectOne(&count, `SELECT count(1) FROM pendingAuthorizations WHERE registrationID = :regID AND expires > :now AND status = :pending`, map[string]interface{}{ "regID": regID, "now": ssa.clk.Now(), "pending": string(core.StatusPending), }) return }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "CountPendingAuthorizations", "(", "ctx", "context", ".", "Context", ",", "regID", "int64", ")", "(", "count", "int", ",", "err", "error", ")", "{", "err", "=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", "(", "&", "count", ",", "`SELECT count(1) FROM pendingAuthorizations\n\t\tWHERE registrationID = :regID AND\n\t\texpires > :now AND\n\t\tstatus = :pending`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "regID", ",", "\"", "\"", ":", "ssa", ".", "clk", ".", "Now", "(", ")", ",", "\"", "\"", ":", "string", "(", "core", ".", "StatusPending", ")", ",", "}", ")", "\n", "return", "\n", "}" ]
// CountPendingAuthorizations returns the number of pending, unexpired // authorizations for the given registration.
[ "CountPendingAuthorizations", "returns", "the", "number", "of", "pending", "unexpired", "authorizations", "for", "the", "given", "registration", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1032-L1044
train
letsencrypt/boulder
sa/sa.go
CountInvalidAuthorizations
func (ssa *SQLStorageAuthority) CountInvalidAuthorizations( ctx context.Context, req *sapb.CountInvalidAuthorizationsRequest, ) (count *sapb.Count, err error) { identifier := core.AcmeIdentifier{ Type: core.IdentifierDNS, Value: *req.Hostname, } idJSON, err := json.Marshal(identifier) if err != nil { return nil, err } count = &sapb.Count{ Count: new(int64), } err = ssa.dbMap.WithContext(ctx).SelectOne(count.Count, `SELECT COUNT(1) FROM authz WHERE registrationID = :regID AND identifier = :identifier AND expires > :earliest AND expires <= :latest AND status = :invalid`, map[string]interface{}{ "regID": *req.RegistrationID, "identifier": idJSON, "earliest": time.Unix(0, *req.Range.Earliest), "latest": time.Unix(0, *req.Range.Latest), "invalid": string(core.StatusInvalid), }) return }
go
func (ssa *SQLStorageAuthority) CountInvalidAuthorizations( ctx context.Context, req *sapb.CountInvalidAuthorizationsRequest, ) (count *sapb.Count, err error) { identifier := core.AcmeIdentifier{ Type: core.IdentifierDNS, Value: *req.Hostname, } idJSON, err := json.Marshal(identifier) if err != nil { return nil, err } count = &sapb.Count{ Count: new(int64), } err = ssa.dbMap.WithContext(ctx).SelectOne(count.Count, `SELECT COUNT(1) FROM authz WHERE registrationID = :regID AND identifier = :identifier AND expires > :earliest AND expires <= :latest AND status = :invalid`, map[string]interface{}{ "regID": *req.RegistrationID, "identifier": idJSON, "earliest": time.Unix(0, *req.Range.Earliest), "latest": time.Unix(0, *req.Range.Latest), "invalid": string(core.StatusInvalid), }) return }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "CountInvalidAuthorizations", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "CountInvalidAuthorizationsRequest", ",", ")", "(", "count", "*", "sapb", ".", "Count", ",", "err", "error", ")", "{", "identifier", ":=", "core", ".", "AcmeIdentifier", "{", "Type", ":", "core", ".", "IdentifierDNS", ",", "Value", ":", "*", "req", ".", "Hostname", ",", "}", "\n\n", "idJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "identifier", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "count", "=", "&", "sapb", ".", "Count", "{", "Count", ":", "new", "(", "int64", ")", ",", "}", "\n", "err", "=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", "(", "count", ".", "Count", ",", "`SELECT COUNT(1) FROM authz\n\t\tWHERE registrationID = :regID AND\n\t\tidentifier = :identifier AND\n\t\texpires > :earliest AND\n\t\texpires <= :latest AND\n\t\tstatus = :invalid`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "*", "req", ".", "RegistrationID", ",", "\"", "\"", ":", "idJSON", ",", "\"", "\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Range", ".", "Earliest", ")", ",", "\"", "\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Range", ".", "Latest", ")", ",", "\"", "\"", ":", "string", "(", "core", ".", "StatusInvalid", ")", ",", "}", ")", "\n", "return", "\n", "}" ]
// CountInvalidAuthorizations counts invalid authorizations for a user expiring // in a given time range. // authorizations for the give registration.
[ "CountInvalidAuthorizations", "counts", "invalid", "authorizations", "for", "a", "user", "expiring", "in", "a", "given", "time", "range", ".", "authorizations", "for", "the", "give", "registration", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1067-L1099
train
letsencrypt/boulder
sa/sa.go
addOrderFQDNSet
func addOrderFQDNSet( db dbInserter, names []string, orderID int64, regID int64, expires time.Time) error { return db.Insert(&orderFQDNSet{ SetHash: hashNames(names), OrderID: orderID, RegistrationID: regID, Expires: expires, }) }
go
func addOrderFQDNSet( db dbInserter, names []string, orderID int64, regID int64, expires time.Time) error { return db.Insert(&orderFQDNSet{ SetHash: hashNames(names), OrderID: orderID, RegistrationID: regID, Expires: expires, }) }
[ "func", "addOrderFQDNSet", "(", "db", "dbInserter", ",", "names", "[", "]", "string", ",", "orderID", "int64", ",", "regID", "int64", ",", "expires", "time", ".", "Time", ")", "error", "{", "return", "db", ".", "Insert", "(", "&", "orderFQDNSet", "{", "SetHash", ":", "hashNames", "(", "names", ")", ",", "OrderID", ":", "orderID", ",", "RegistrationID", ":", "regID", ",", "Expires", ":", "expires", ",", "}", ")", "\n", "}" ]
// addOrderFQDNSet creates a new OrderFQDNSet row using the provided // information. This function accepts a transaction so that the orderFqdnSet // addition can take place within the order addition transaction. The caller is // required to rollback the transaction if an error is returned.
[ "addOrderFQDNSet", "creates", "a", "new", "OrderFQDNSet", "row", "using", "the", "provided", "information", ".", "This", "function", "accepts", "a", "transaction", "so", "that", "the", "orderFqdnSet", "addition", "can", "take", "place", "within", "the", "order", "addition", "transaction", ".", "The", "caller", "is", "required", "to", "rollback", "the", "transaction", "if", "an", "error", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1120-L1132
train
letsencrypt/boulder
sa/sa.go
deleteOrderFQDNSet
func deleteOrderFQDNSet( db dbExecer, orderID int64) error { result, err := db.Exec(` DELETE FROM orderFqdnSets WHERE orderID = ?`, orderID) if err != nil { return err } rowsDeleted, err := result.RowsAffected() if err != nil { return err } // We always expect there to be an order FQDN set row for each // pending/processing order that is being finalized. If there isn't one then // something is amiss and should be raised as an internal server error if rowsDeleted == 0 { return berrors.InternalServerError("No orderFQDNSet exists to delete") } return nil }
go
func deleteOrderFQDNSet( db dbExecer, orderID int64) error { result, err := db.Exec(` DELETE FROM orderFqdnSets WHERE orderID = ?`, orderID) if err != nil { return err } rowsDeleted, err := result.RowsAffected() if err != nil { return err } // We always expect there to be an order FQDN set row for each // pending/processing order that is being finalized. If there isn't one then // something is amiss and should be raised as an internal server error if rowsDeleted == 0 { return berrors.InternalServerError("No orderFQDNSet exists to delete") } return nil }
[ "func", "deleteOrderFQDNSet", "(", "db", "dbExecer", ",", "orderID", "int64", ")", "error", "{", "result", ",", "err", ":=", "db", ".", "Exec", "(", "`\n\t DELETE FROM orderFqdnSets\n\t\tWHERE orderID = ?`", ",", "orderID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "rowsDeleted", ",", "err", ":=", "result", ".", "RowsAffected", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// We always expect there to be an order FQDN set row for each", "// pending/processing order that is being finalized. If there isn't one then", "// something is amiss and should be raised as an internal server error", "if", "rowsDeleted", "==", "0", "{", "return", "berrors", ".", "InternalServerError", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// deleteOrderFQDNSet deletes a OrderFQDNSet row that matches the provided // orderID. This function accepts a transaction so that the deletion can // take place within the finalization transaction. The caller is required to // rollback the transaction if an error is returned.
[ "deleteOrderFQDNSet", "deletes", "a", "OrderFQDNSet", "row", "that", "matches", "the", "provided", "orderID", ".", "This", "function", "accepts", "a", "transaction", "so", "that", "the", "deletion", "can", "take", "place", "within", "the", "finalization", "transaction", ".", "The", "caller", "is", "required", "to", "rollback", "the", "transaction", "if", "an", "error", "is", "returned", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1138-L1160
train
letsencrypt/boulder
sa/sa.go
CountFQDNSets
func (ssa *SQLStorageAuthority) CountFQDNSets(ctx context.Context, window time.Duration, names []string) (int64, error) { var count int64 err := ssa.dbMap.WithContext(ctx).SelectOne( &count, `SELECT COUNT(1) FROM fqdnSets WHERE setHash = ? AND issued > ?`, hashNames(names), ssa.clk.Now().Add(-window), ) return count, err }
go
func (ssa *SQLStorageAuthority) CountFQDNSets(ctx context.Context, window time.Duration, names []string) (int64, error) { var count int64 err := ssa.dbMap.WithContext(ctx).SelectOne( &count, `SELECT COUNT(1) FROM fqdnSets WHERE setHash = ? AND issued > ?`, hashNames(names), ssa.clk.Now().Add(-window), ) return count, err }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "CountFQDNSets", "(", "ctx", "context", ".", "Context", ",", "window", "time", ".", "Duration", ",", "names", "[", "]", "string", ")", "(", "int64", ",", "error", ")", "{", "var", "count", "int64", "\n", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", "(", "&", "count", ",", "`SELECT COUNT(1) FROM fqdnSets\n\t\tWHERE setHash = ?\n\t\tAND issued > ?`", ",", "hashNames", "(", "names", ")", ",", "ssa", ".", "clk", ".", "Now", "(", ")", ".", "Add", "(", "-", "window", ")", ",", ")", "\n", "return", "count", ",", "err", "\n", "}" ]
// CountFQDNSets returns the number of sets with hash |setHash| within the window // |window|
[ "CountFQDNSets", "returns", "the", "number", "of", "sets", "with", "hash", "|setHash|", "within", "the", "window", "|window|" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1180-L1191
train
letsencrypt/boulder
sa/sa.go
getFQDNSetsBySerials
func (ssa *SQLStorageAuthority) getFQDNSetsBySerials( db dbSelector, serials []string, ) ([]setHash, error) { var fqdnSets []setHash // It is unexpected that this function would be called with no serials if len(serials) == 0 { err := fmt.Errorf("getFQDNSetsBySerials called with no serials") ssa.log.AuditErr(err.Error()) return nil, err } qmarks := make([]string, len(serials)) params := make([]interface{}, len(serials)) for i, serial := range serials { params[i] = serial qmarks[i] = "?" } query := "SELECT setHash FROM fqdnSets " + "WHERE serial IN (" + strings.Join(qmarks, ",") + ")" _, err := db.Select( &fqdnSets, query, params...) if err != nil { return nil, err } // The serials existed when we found them in issuedNames, they should continue // to exist here. Otherwise an internal consistency violation occured and // needs to be audit logged if err == sql.ErrNoRows { err := fmt.Errorf("getFQDNSetsBySerials returned no rows - internal consistency violation") ssa.log.AuditErr(err.Error()) return nil, err } return fqdnSets, nil }
go
func (ssa *SQLStorageAuthority) getFQDNSetsBySerials( db dbSelector, serials []string, ) ([]setHash, error) { var fqdnSets []setHash // It is unexpected that this function would be called with no serials if len(serials) == 0 { err := fmt.Errorf("getFQDNSetsBySerials called with no serials") ssa.log.AuditErr(err.Error()) return nil, err } qmarks := make([]string, len(serials)) params := make([]interface{}, len(serials)) for i, serial := range serials { params[i] = serial qmarks[i] = "?" } query := "SELECT setHash FROM fqdnSets " + "WHERE serial IN (" + strings.Join(qmarks, ",") + ")" _, err := db.Select( &fqdnSets, query, params...) if err != nil { return nil, err } // The serials existed when we found them in issuedNames, they should continue // to exist here. Otherwise an internal consistency violation occured and // needs to be audit logged if err == sql.ErrNoRows { err := fmt.Errorf("getFQDNSetsBySerials returned no rows - internal consistency violation") ssa.log.AuditErr(err.Error()) return nil, err } return fqdnSets, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "getFQDNSetsBySerials", "(", "db", "dbSelector", ",", "serials", "[", "]", "string", ",", ")", "(", "[", "]", "setHash", ",", "error", ")", "{", "var", "fqdnSets", "[", "]", "setHash", "\n\n", "// It is unexpected that this function would be called with no serials", "if", "len", "(", "serials", ")", "==", "0", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "ssa", ".", "log", ".", "AuditErr", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "qmarks", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "serials", ")", ")", "\n", "params", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "serials", ")", ")", "\n", "for", "i", ",", "serial", ":=", "range", "serials", "{", "params", "[", "i", "]", "=", "serial", "\n", "qmarks", "[", "i", "]", "=", "\"", "\"", "\n", "}", "\n", "query", ":=", "\"", "\"", "+", "\"", "\"", "+", "strings", ".", "Join", "(", "qmarks", ",", "\"", "\"", ")", "+", "\"", "\"", "\n", "_", ",", "err", ":=", "db", ".", "Select", "(", "&", "fqdnSets", ",", "query", ",", "params", "...", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// The serials existed when we found them in issuedNames, they should continue", "// to exist here. Otherwise an internal consistency violation occured and", "// needs to be audit logged", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "ssa", ".", "log", ".", "AuditErr", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "fqdnSets", ",", "nil", "\n", "}" ]
// getFQDNSetsBySerials finds the setHashes corresponding to a set of // certificate serials. These serials can be used to check whether any // certificates have been issued for the same set of names previously.
[ "getFQDNSetsBySerials", "finds", "the", "setHashes", "corresponding", "to", "a", "set", "of", "certificate", "serials", ".", "These", "serials", "can", "be", "used", "to", "check", "whether", "any", "certificates", "have", "been", "issued", "for", "the", "same", "set", "of", "names", "previously", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1199-L1238
train
letsencrypt/boulder
sa/sa.go
FQDNSetExists
func (ssa *SQLStorageAuthority) FQDNSetExists(ctx context.Context, names []string) (bool, error) { exists, err := ssa.checkFQDNSetExists( ssa.dbMap.WithContext(ctx).SelectOne, names) if err != nil { return false, err } return exists, nil }
go
func (ssa *SQLStorageAuthority) FQDNSetExists(ctx context.Context, names []string) (bool, error) { exists, err := ssa.checkFQDNSetExists( ssa.dbMap.WithContext(ctx).SelectOne, names) if err != nil { return false, err } return exists, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "FQDNSetExists", "(", "ctx", "context", ".", "Context", ",", "names", "[", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "exists", ",", "err", ":=", "ssa", ".", "checkFQDNSetExists", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", ",", "names", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "exists", ",", "nil", "\n", "}" ]
// FQDNSetExists returns a bool indicating if one or more FQDN sets |names| // exists in the database
[ "FQDNSetExists", "returns", "a", "bool", "indicating", "if", "one", "or", "more", "FQDN", "sets", "|names|", "exists", "in", "the", "database" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1312-L1320
train
letsencrypt/boulder
sa/sa.go
checkFQDNSetExists
func (ssa *SQLStorageAuthority) checkFQDNSetExists(selector oneSelectorFunc, names []string) (bool, error) { var count int64 err := selector( &count, `SELECT COUNT(1) FROM fqdnSets WHERE setHash = ? LIMIT 1`, hashNames(names), ) return count > 0, err }
go
func (ssa *SQLStorageAuthority) checkFQDNSetExists(selector oneSelectorFunc, names []string) (bool, error) { var count int64 err := selector( &count, `SELECT COUNT(1) FROM fqdnSets WHERE setHash = ? LIMIT 1`, hashNames(names), ) return count > 0, err }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "checkFQDNSetExists", "(", "selector", "oneSelectorFunc", ",", "names", "[", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "var", "count", "int64", "\n", "err", ":=", "selector", "(", "&", "count", ",", "`SELECT COUNT(1) FROM fqdnSets\n\t\tWHERE setHash = ?\n\t\tLIMIT 1`", ",", "hashNames", "(", "names", ")", ",", ")", "\n", "return", "count", ">", "0", ",", "err", "\n", "}" ]
// checkFQDNSetExists uses the given oneSelectorFunc to check whether an fqdnSet // for the given names exists.
[ "checkFQDNSetExists", "uses", "the", "given", "oneSelectorFunc", "to", "check", "whether", "an", "fqdnSet", "for", "the", "given", "names", "exists", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1328-L1338
train
letsencrypt/boulder
sa/sa.go
DeactivateRegistration
func (ssa *SQLStorageAuthority) DeactivateRegistration(ctx context.Context, id int64) error { _, err := ssa.dbMap.WithContext(ctx).Exec( "UPDATE registrations SET status = ? WHERE status = ? AND id = ?", string(core.StatusDeactivated), string(core.StatusValid), id, ) return err }
go
func (ssa *SQLStorageAuthority) DeactivateRegistration(ctx context.Context, id int64) error { _, err := ssa.dbMap.WithContext(ctx).Exec( "UPDATE registrations SET status = ? WHERE status = ? AND id = ?", string(core.StatusDeactivated), string(core.StatusValid), id, ) return err }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "DeactivateRegistration", "(", "ctx", "context", ".", "Context", ",", "id", "int64", ")", "error", "{", "_", ",", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "Exec", "(", "\"", "\"", ",", "string", "(", "core", ".", "StatusDeactivated", ")", ",", "string", "(", "core", ".", "StatusValid", ")", ",", "id", ",", ")", "\n", "return", "err", "\n", "}" ]
// DeactivateRegistration deactivates a currently valid registration
[ "DeactivateRegistration", "deactivates", "a", "currently", "valid", "registration" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1399-L1407
train
letsencrypt/boulder
sa/sa.go
DeactivateAuthorization
func (ssa *SQLStorageAuthority) DeactivateAuthorization(ctx context.Context, id string) error { tx, err := ssa.dbMap.Begin() if err != nil { return err } txWithCtx := tx.WithContext(ctx) if existingPending(txWithCtx, id) { authzObj, err := txWithCtx.Get(&pendingauthzModel{}, id) if err != nil { return Rollback(tx, err) } if authzObj == nil { // InternalServerError because existingPending already told us it existed return Rollback(tx, berrors.InternalServerError("failure retrieving pending authorization")) } authz := authzObj.(*pendingauthzModel) if authz.Status != core.StatusPending { return Rollback(tx, berrors.WrongAuthorizationStateError("authorization not pending")) } authz.Status = core.StatusDeactivated err = txWithCtx.Insert(&authzModel{authz.Authorization}) if err != nil { return Rollback(tx, err) } result, err := txWithCtx.Delete(authzObj) if err != nil { return Rollback(tx, err) } if result != 1 { return Rollback(tx, berrors.InternalServerError("wrong number of rows deleted: expected 1, got %d", result)) } } else { _, err = txWithCtx.Exec( `UPDATE authz SET status = ? WHERE id = ? and status = ?`, string(core.StatusDeactivated), id, string(core.StatusValid), ) if err != nil { return Rollback(tx, err) } } return tx.Commit() }
go
func (ssa *SQLStorageAuthority) DeactivateAuthorization(ctx context.Context, id string) error { tx, err := ssa.dbMap.Begin() if err != nil { return err } txWithCtx := tx.WithContext(ctx) if existingPending(txWithCtx, id) { authzObj, err := txWithCtx.Get(&pendingauthzModel{}, id) if err != nil { return Rollback(tx, err) } if authzObj == nil { // InternalServerError because existingPending already told us it existed return Rollback(tx, berrors.InternalServerError("failure retrieving pending authorization")) } authz := authzObj.(*pendingauthzModel) if authz.Status != core.StatusPending { return Rollback(tx, berrors.WrongAuthorizationStateError("authorization not pending")) } authz.Status = core.StatusDeactivated err = txWithCtx.Insert(&authzModel{authz.Authorization}) if err != nil { return Rollback(tx, err) } result, err := txWithCtx.Delete(authzObj) if err != nil { return Rollback(tx, err) } if result != 1 { return Rollback(tx, berrors.InternalServerError("wrong number of rows deleted: expected 1, got %d", result)) } } else { _, err = txWithCtx.Exec( `UPDATE authz SET status = ? WHERE id = ? and status = ?`, string(core.StatusDeactivated), id, string(core.StatusValid), ) if err != nil { return Rollback(tx, err) } } return tx.Commit() }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "DeactivateAuthorization", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "error", "{", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n\n", "if", "existingPending", "(", "txWithCtx", ",", "id", ")", "{", "authzObj", ",", "err", ":=", "txWithCtx", ".", "Get", "(", "&", "pendingauthzModel", "{", "}", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "if", "authzObj", "==", "nil", "{", "// InternalServerError because existingPending already told us it existed", "return", "Rollback", "(", "tx", ",", "berrors", ".", "InternalServerError", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "authz", ":=", "authzObj", ".", "(", "*", "pendingauthzModel", ")", "\n", "if", "authz", ".", "Status", "!=", "core", ".", "StatusPending", "{", "return", "Rollback", "(", "tx", ",", "berrors", ".", "WrongAuthorizationStateError", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "authz", ".", "Status", "=", "core", ".", "StatusDeactivated", "\n", "err", "=", "txWithCtx", ".", "Insert", "(", "&", "authzModel", "{", "authz", ".", "Authorization", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "result", ",", "err", ":=", "txWithCtx", ".", "Delete", "(", "authzObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "if", "result", "!=", "1", "{", "return", "Rollback", "(", "tx", ",", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "result", ")", ")", "\n", "}", "\n", "}", "else", "{", "_", ",", "err", "=", "txWithCtx", ".", "Exec", "(", "`UPDATE authz SET status = ? WHERE id = ? and status = ?`", ",", "string", "(", "core", ".", "StatusDeactivated", ")", ",", "id", ",", "string", "(", "core", ".", "StatusValid", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "tx", ".", "Commit", "(", ")", "\n", "}" ]
// DeactivateAuthorization deactivates a currently valid or pending authorization
[ "DeactivateAuthorization", "deactivates", "a", "currently", "valid", "or", "pending", "authorization" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1410-L1455
train
letsencrypt/boulder
sa/sa.go
DeactivateAuthorization2
func (ssa *SQLStorageAuthority) DeactivateAuthorization2(ctx context.Context, req *sapb.AuthorizationID2) (*corepb.Empty, error) { _, err := ssa.dbMap.Exec( `UPDATE authz2 SET status = :deactivated WHERE id = :id and status IN (:valid,:pending)`, map[string]interface{}{ "deactivated": statusUint(core.StatusDeactivated), "id": *req.Id, "valid": statusUint(core.StatusValid), "pending": statusUint(core.StatusPending), }, ) if err != nil { return nil, err } return &corepb.Empty{}, nil }
go
func (ssa *SQLStorageAuthority) DeactivateAuthorization2(ctx context.Context, req *sapb.AuthorizationID2) (*corepb.Empty, error) { _, err := ssa.dbMap.Exec( `UPDATE authz2 SET status = :deactivated WHERE id = :id and status IN (:valid,:pending)`, map[string]interface{}{ "deactivated": statusUint(core.StatusDeactivated), "id": *req.Id, "valid": statusUint(core.StatusValid), "pending": statusUint(core.StatusPending), }, ) if err != nil { return nil, err } return &corepb.Empty{}, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "DeactivateAuthorization2", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "AuthorizationID2", ")", "(", "*", "corepb", ".", "Empty", ",", "error", ")", "{", "_", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Exec", "(", "`UPDATE authz2 SET status = :deactivated WHERE id = :id and status IN (:valid,:pending)`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "statusUint", "(", "core", ".", "StatusDeactivated", ")", ",", "\"", "\"", ":", "*", "req", ".", "Id", ",", "\"", "\"", ":", "statusUint", "(", "core", ".", "StatusValid", ")", ",", "\"", "\"", ":", "statusUint", "(", "core", ".", "StatusPending", ")", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "corepb", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeactivateAuthorization2 deactivates a currently valid or pending authorization. // This method is intended to deprecate DeactivateAuthorization.
[ "DeactivateAuthorization2", "deactivates", "a", "currently", "valid", "or", "pending", "authorization", ".", "This", "method", "is", "intended", "to", "deprecate", "DeactivateAuthorization", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1459-L1473
train
letsencrypt/boulder
sa/sa.go
NewOrder
func (ssa *SQLStorageAuthority) NewOrder(ctx context.Context, req *corepb.Order) (*corepb.Order, error) { order := &orderModel{ RegistrationID: *req.RegistrationID, Expires: time.Unix(0, *req.Expires), Created: ssa.clk.Now(), } tx, err := ssa.dbMap.Begin() if err != nil { return nil, err } txWithCtx := tx.WithContext(ctx) if err := txWithCtx.Insert(order); err != nil { return nil, Rollback(tx, err) } for _, id := range req.Authorizations { otoa := &orderToAuthzModel{ OrderID: order.ID, AuthzID: id, } if err := txWithCtx.Insert(otoa); err != nil { return nil, Rollback(tx, err) } } for _, id := range req.V2Authorizations { otoa := &orderToAuthz2Model{ OrderID: order.ID, AuthzID: id, } if err := txWithCtx.Insert(otoa); err != nil { return nil, Rollback(tx, err) } } for _, name := range req.Names { reqdName := &requestedNameModel{ OrderID: order.ID, ReversedName: ReverseName(name), } if err := txWithCtx.Insert(reqdName); err != nil { return nil, Rollback(tx, err) } } // Add an FQDNSet entry for the order if err := addOrderFQDNSet( txWithCtx, req.Names, order.ID, order.RegistrationID, order.Expires); err != nil { return nil, Rollback(tx, err) } if err := tx.Commit(); err != nil { return nil, err } // Update the request with the ID that the order received req.Id = &order.ID // Update the request with the created timestamp from the model createdTS := order.Created.UnixNano() req.Created = &createdTS // A new order is never processing because it can't have been finalized yet processingStatus := false req.BeganProcessing = &processingStatus // Calculate the order status before returning it. Since it may have reused all // valid authorizations the order may be "born" in a ready status. status, err := ssa.statusForOrder(ctx, req) if err != nil { return nil, err } req.Status = &status return req, nil }
go
func (ssa *SQLStorageAuthority) NewOrder(ctx context.Context, req *corepb.Order) (*corepb.Order, error) { order := &orderModel{ RegistrationID: *req.RegistrationID, Expires: time.Unix(0, *req.Expires), Created: ssa.clk.Now(), } tx, err := ssa.dbMap.Begin() if err != nil { return nil, err } txWithCtx := tx.WithContext(ctx) if err := txWithCtx.Insert(order); err != nil { return nil, Rollback(tx, err) } for _, id := range req.Authorizations { otoa := &orderToAuthzModel{ OrderID: order.ID, AuthzID: id, } if err := txWithCtx.Insert(otoa); err != nil { return nil, Rollback(tx, err) } } for _, id := range req.V2Authorizations { otoa := &orderToAuthz2Model{ OrderID: order.ID, AuthzID: id, } if err := txWithCtx.Insert(otoa); err != nil { return nil, Rollback(tx, err) } } for _, name := range req.Names { reqdName := &requestedNameModel{ OrderID: order.ID, ReversedName: ReverseName(name), } if err := txWithCtx.Insert(reqdName); err != nil { return nil, Rollback(tx, err) } } // Add an FQDNSet entry for the order if err := addOrderFQDNSet( txWithCtx, req.Names, order.ID, order.RegistrationID, order.Expires); err != nil { return nil, Rollback(tx, err) } if err := tx.Commit(); err != nil { return nil, err } // Update the request with the ID that the order received req.Id = &order.ID // Update the request with the created timestamp from the model createdTS := order.Created.UnixNano() req.Created = &createdTS // A new order is never processing because it can't have been finalized yet processingStatus := false req.BeganProcessing = &processingStatus // Calculate the order status before returning it. Since it may have reused all // valid authorizations the order may be "born" in a ready status. status, err := ssa.statusForOrder(ctx, req) if err != nil { return nil, err } req.Status = &status return req, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "NewOrder", "(", "ctx", "context", ".", "Context", ",", "req", "*", "corepb", ".", "Order", ")", "(", "*", "corepb", ".", "Order", ",", "error", ")", "{", "order", ":=", "&", "orderModel", "{", "RegistrationID", ":", "*", "req", ".", "RegistrationID", ",", "Expires", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Expires", ")", ",", "Created", ":", "ssa", ".", "clk", ".", "Now", "(", ")", ",", "}", "\n\n", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n\n", "if", "err", ":=", "txWithCtx", ".", "Insert", "(", "order", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "id", ":=", "range", "req", ".", "Authorizations", "{", "otoa", ":=", "&", "orderToAuthzModel", "{", "OrderID", ":", "order", ".", "ID", ",", "AuthzID", ":", "id", ",", "}", "\n", "if", "err", ":=", "txWithCtx", ".", "Insert", "(", "otoa", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "id", ":=", "range", "req", ".", "V2Authorizations", "{", "otoa", ":=", "&", "orderToAuthz2Model", "{", "OrderID", ":", "order", ".", "ID", ",", "AuthzID", ":", "id", ",", "}", "\n", "if", "err", ":=", "txWithCtx", ".", "Insert", "(", "otoa", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "name", ":=", "range", "req", ".", "Names", "{", "reqdName", ":=", "&", "requestedNameModel", "{", "OrderID", ":", "order", ".", "ID", ",", "ReversedName", ":", "ReverseName", "(", "name", ")", ",", "}", "\n", "if", "err", ":=", "txWithCtx", ".", "Insert", "(", "reqdName", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Add an FQDNSet entry for the order", "if", "err", ":=", "addOrderFQDNSet", "(", "txWithCtx", ",", "req", ".", "Names", ",", "order", ".", "ID", ",", "order", ".", "RegistrationID", ",", "order", ".", "Expires", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "tx", ".", "Commit", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Update the request with the ID that the order received", "req", ".", "Id", "=", "&", "order", ".", "ID", "\n", "// Update the request with the created timestamp from the model", "createdTS", ":=", "order", ".", "Created", ".", "UnixNano", "(", ")", "\n", "req", ".", "Created", "=", "&", "createdTS", "\n", "// A new order is never processing because it can't have been finalized yet", "processingStatus", ":=", "false", "\n", "req", ".", "BeganProcessing", "=", "&", "processingStatus", "\n\n", "// Calculate the order status before returning it. Since it may have reused all", "// valid authorizations the order may be \"born\" in a ready status.", "status", ",", "err", ":=", "ssa", ".", "statusForOrder", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Status", "=", "&", "status", "\n", "return", "req", ",", "nil", "\n", "}" ]
// NewOrder adds a new v2 style order to the database
[ "NewOrder", "adds", "a", "new", "v2", "style", "order", "to", "the", "database" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1476-L1549
train
letsencrypt/boulder
sa/sa.go
SetOrderError
func (ssa *SQLStorageAuthority) SetOrderError(ctx context.Context, order *corepb.Order) error { tx, err := ssa.dbMap.Begin() if err != nil { return err } txWithCtx := tx.WithContext(ctx) om, err := orderToModel(order) if err != nil { return Rollback(tx, err) } result, err := txWithCtx.Exec(` UPDATE orders SET error = ? WHERE id = ?`, om.Error, om.ID) if err != nil { err = berrors.InternalServerError("error updating order error field") return Rollback(tx, err) } n, err := result.RowsAffected() if err != nil || n == 0 { err = berrors.InternalServerError("no order updated with new error field") return Rollback(tx, err) } return tx.Commit() }
go
func (ssa *SQLStorageAuthority) SetOrderError(ctx context.Context, order *corepb.Order) error { tx, err := ssa.dbMap.Begin() if err != nil { return err } txWithCtx := tx.WithContext(ctx) om, err := orderToModel(order) if err != nil { return Rollback(tx, err) } result, err := txWithCtx.Exec(` UPDATE orders SET error = ? WHERE id = ?`, om.Error, om.ID) if err != nil { err = berrors.InternalServerError("error updating order error field") return Rollback(tx, err) } n, err := result.RowsAffected() if err != nil || n == 0 { err = berrors.InternalServerError("no order updated with new error field") return Rollback(tx, err) } return tx.Commit() }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "SetOrderError", "(", "ctx", "context", ".", "Context", ",", "order", "*", "corepb", ".", "Order", ")", "error", "{", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n\n", "om", ",", "err", ":=", "orderToModel", "(", "order", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "result", ",", "err", ":=", "txWithCtx", ".", "Exec", "(", "`\n\t\tUPDATE orders\n\t\tSET error = ?\n\t\tWHERE id = ?`", ",", "om", ".", "Error", ",", "om", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "berrors", ".", "InternalServerError", "(", "\"", "\"", ")", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "n", ",", "err", ":=", "result", ".", "RowsAffected", "(", ")", "\n", "if", "err", "!=", "nil", "||", "n", "==", "0", "{", "err", "=", "berrors", ".", "InternalServerError", "(", "\"", "\"", ")", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "return", "tx", ".", "Commit", "(", ")", "\n", "}" ]
// SetOrderError updates a provided Order's error field.
[ "SetOrderError", "updates", "a", "provided", "Order", "s", "error", "field", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1584-L1614
train
letsencrypt/boulder
sa/sa.go
GetOrder
func (ssa *SQLStorageAuthority) GetOrder(ctx context.Context, req *sapb.OrderRequest) (*corepb.Order, error) { omObj, err := ssa.dbMap.WithContext(ctx).Get(orderModel{}, *req.Id) if err == sql.ErrNoRows || omObj == nil { return nil, berrors.NotFoundError("no order found for ID %d", *req.Id) } if err != nil { return nil, err } order, err := modelToOrder(omObj.(*orderModel)) if err != nil { return nil, err } var useV2Authzs bool if req.UseV2Authorizations != nil { useV2Authzs = *req.UseV2Authorizations } v1AuthzIDs, v2AuthzIDs, err := ssa.authzForOrder(ctx, *order.Id, useV2Authzs) if err != nil { return nil, err } order.Authorizations, order.V2Authorizations = v1AuthzIDs, v2AuthzIDs names, err := ssa.namesForOrder(ctx, *order.Id) if err != nil { return nil, err } // The requested names are stored reversed to improve indexing performance. We // need to reverse the reversed names here before giving them back to the // caller. reversedNames := make([]string, len(names)) for i, n := range names { reversedNames[i] = ReverseName(n) } order.Names = reversedNames // Calculate the status for the order status, err := ssa.statusForOrder(ctx, order) if err != nil { return nil, err } order.Status = &status return order, nil }
go
func (ssa *SQLStorageAuthority) GetOrder(ctx context.Context, req *sapb.OrderRequest) (*corepb.Order, error) { omObj, err := ssa.dbMap.WithContext(ctx).Get(orderModel{}, *req.Id) if err == sql.ErrNoRows || omObj == nil { return nil, berrors.NotFoundError("no order found for ID %d", *req.Id) } if err != nil { return nil, err } order, err := modelToOrder(omObj.(*orderModel)) if err != nil { return nil, err } var useV2Authzs bool if req.UseV2Authorizations != nil { useV2Authzs = *req.UseV2Authorizations } v1AuthzIDs, v2AuthzIDs, err := ssa.authzForOrder(ctx, *order.Id, useV2Authzs) if err != nil { return nil, err } order.Authorizations, order.V2Authorizations = v1AuthzIDs, v2AuthzIDs names, err := ssa.namesForOrder(ctx, *order.Id) if err != nil { return nil, err } // The requested names are stored reversed to improve indexing performance. We // need to reverse the reversed names here before giving them back to the // caller. reversedNames := make([]string, len(names)) for i, n := range names { reversedNames[i] = ReverseName(n) } order.Names = reversedNames // Calculate the status for the order status, err := ssa.statusForOrder(ctx, order) if err != nil { return nil, err } order.Status = &status return order, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetOrder", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "OrderRequest", ")", "(", "*", "corepb", ".", "Order", ",", "error", ")", "{", "omObj", ",", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "Get", "(", "orderModel", "{", "}", ",", "*", "req", ".", "Id", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "||", "omObj", "==", "nil", "{", "return", "nil", ",", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "*", "req", ".", "Id", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "order", ",", "err", ":=", "modelToOrder", "(", "omObj", ".", "(", "*", "orderModel", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "useV2Authzs", "bool", "\n", "if", "req", ".", "UseV2Authorizations", "!=", "nil", "{", "useV2Authzs", "=", "*", "req", ".", "UseV2Authorizations", "\n", "}", "\n", "v1AuthzIDs", ",", "v2AuthzIDs", ",", "err", ":=", "ssa", ".", "authzForOrder", "(", "ctx", ",", "*", "order", ".", "Id", ",", "useV2Authzs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "order", ".", "Authorizations", ",", "order", ".", "V2Authorizations", "=", "v1AuthzIDs", ",", "v2AuthzIDs", "\n\n", "names", ",", "err", ":=", "ssa", ".", "namesForOrder", "(", "ctx", ",", "*", "order", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// The requested names are stored reversed to improve indexing performance. We", "// need to reverse the reversed names here before giving them back to the", "// caller.", "reversedNames", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "names", ")", ")", "\n", "for", "i", ",", "n", ":=", "range", "names", "{", "reversedNames", "[", "i", "]", "=", "ReverseName", "(", "n", ")", "\n", "}", "\n", "order", ".", "Names", "=", "reversedNames", "\n\n", "// Calculate the status for the order", "status", ",", "err", ":=", "ssa", ".", "statusForOrder", "(", "ctx", ",", "order", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "order", ".", "Status", "=", "&", "status", "\n\n", "return", "order", ",", "nil", "\n", "}" ]
// GetOrder is used to retrieve an already existing order object
[ "GetOrder", "is", "used", "to", "retrieve", "an", "already", "existing", "order", "object" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1695-L1738
train
letsencrypt/boulder
sa/sa.go
GetValidOrderAuthorizations
func (ssa *SQLStorageAuthority) GetValidOrderAuthorizations( ctx context.Context, req *sapb.GetValidOrderAuthorizationsRequest) (map[string]*core.Authorization, error) { now := ssa.clk.Now() // Select the full authorization data for all *valid, unexpired* // authorizations that are owned by the correct account ID and associated with // the given order ID var auths []*core.Authorization _, err := ssa.dbMap.WithContext(ctx).Select( &auths, fmt.Sprintf(`SELECT %s FROM %s AS authz LEFT JOIN orderToAuthz ON authz.ID = orderToAuthz.authzID WHERE authz.registrationID = ? AND authz.expires > ? AND authz.status = ? AND orderToAuthz.orderID = ?`, authzFields, authorizationTable), *req.AcctID, now, string(core.StatusValid), *req.Id) if err != nil { return nil, err } // Collapse & dedupe the returned authorizations into a mapping from name to // authorization byName := make(map[string]*core.Authorization) for _, auth := range auths { // We only expect to get back DNS identifiers if auth.Identifier.Type != core.IdentifierDNS { return nil, fmt.Errorf("unknown identifier type: %q on authz id %q", auth.Identifier.Type, auth.ID) } existing, present := byName[auth.Identifier.Value] if !present || auth.Expires.After(*existing.Expires) { // Retrieve challenges for the authz auth.Challenges, err = ssa.getChallenges(ssa.dbMap.WithContext(ctx), auth.ID) if err != nil { return nil, err } byName[auth.Identifier.Value] = auth } } return byName, nil }
go
func (ssa *SQLStorageAuthority) GetValidOrderAuthorizations( ctx context.Context, req *sapb.GetValidOrderAuthorizationsRequest) (map[string]*core.Authorization, error) { now := ssa.clk.Now() // Select the full authorization data for all *valid, unexpired* // authorizations that are owned by the correct account ID and associated with // the given order ID var auths []*core.Authorization _, err := ssa.dbMap.WithContext(ctx).Select( &auths, fmt.Sprintf(`SELECT %s FROM %s AS authz LEFT JOIN orderToAuthz ON authz.ID = orderToAuthz.authzID WHERE authz.registrationID = ? AND authz.expires > ? AND authz.status = ? AND orderToAuthz.orderID = ?`, authzFields, authorizationTable), *req.AcctID, now, string(core.StatusValid), *req.Id) if err != nil { return nil, err } // Collapse & dedupe the returned authorizations into a mapping from name to // authorization byName := make(map[string]*core.Authorization) for _, auth := range auths { // We only expect to get back DNS identifiers if auth.Identifier.Type != core.IdentifierDNS { return nil, fmt.Errorf("unknown identifier type: %q on authz id %q", auth.Identifier.Type, auth.ID) } existing, present := byName[auth.Identifier.Value] if !present || auth.Expires.After(*existing.Expires) { // Retrieve challenges for the authz auth.Challenges, err = ssa.getChallenges(ssa.dbMap.WithContext(ctx), auth.ID) if err != nil { return nil, err } byName[auth.Identifier.Value] = auth } } return byName, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetValidOrderAuthorizations", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "GetValidOrderAuthorizationsRequest", ")", "(", "map", "[", "string", "]", "*", "core", ".", "Authorization", ",", "error", ")", "{", "now", ":=", "ssa", ".", "clk", ".", "Now", "(", ")", "\n", "// Select the full authorization data for all *valid, unexpired*", "// authorizations that are owned by the correct account ID and associated with", "// the given order ID", "var", "auths", "[", "]", "*", "core", ".", "Authorization", "\n", "_", ",", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "Select", "(", "&", "auths", ",", "fmt", ".", "Sprintf", "(", "`SELECT %s FROM %s AS authz\n\tLEFT JOIN orderToAuthz\n\tON authz.ID = orderToAuthz.authzID\n\tWHERE authz.registrationID = ? AND\n\tauthz.expires > ? AND\n\tauthz.status = ? AND\n\torderToAuthz.orderID = ?`", ",", "authzFields", ",", "authorizationTable", ")", ",", "*", "req", ".", "AcctID", ",", "now", ",", "string", "(", "core", ".", "StatusValid", ")", ",", "*", "req", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Collapse & dedupe the returned authorizations into a mapping from name to", "// authorization", "byName", ":=", "make", "(", "map", "[", "string", "]", "*", "core", ".", "Authorization", ")", "\n", "for", "_", ",", "auth", ":=", "range", "auths", "{", "// We only expect to get back DNS identifiers", "if", "auth", ".", "Identifier", ".", "Type", "!=", "core", ".", "IdentifierDNS", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "auth", ".", "Identifier", ".", "Type", ",", "auth", ".", "ID", ")", "\n", "}", "\n", "existing", ",", "present", ":=", "byName", "[", "auth", ".", "Identifier", ".", "Value", "]", "\n", "if", "!", "present", "||", "auth", ".", "Expires", ".", "After", "(", "*", "existing", ".", "Expires", ")", "{", "// Retrieve challenges for the authz", "auth", ".", "Challenges", ",", "err", "=", "ssa", ".", "getChallenges", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "auth", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "byName", "[", "auth", ".", "Identifier", ".", "Value", "]", "=", "auth", "\n", "}", "\n", "}", "\n", "return", "byName", ",", "nil", "\n", "}" ]
// GetValidOrderAuthorizations is used to find the valid, unexpired authorizations // associated with a specific order and account ID.
[ "GetValidOrderAuthorizations", "is", "used", "to", "find", "the", "valid", "unexpired", "authorizations", "associated", "with", "a", "specific", "order", "and", "account", "ID", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L1948-L1993
train
letsencrypt/boulder
sa/sa.go
GetAuthorizations
func (ssa *SQLStorageAuthority) GetAuthorizations( ctx context.Context, req *sapb.GetAuthorizationsRequest) (*sapb.Authorizations, error) { authzMap, err := ssa.getAuthorizations( ctx, authorizationTable, string(core.StatusValid), *req.RegistrationID, req.Domains, time.Unix(0, *req.Now), *req.RequireV2Authzs, ) if err != nil { return nil, err } if len(authzMap) == len(req.Domains) { return authzMapToPB(authzMap) } // remove names we already have authz for remainingNames := []string{} for _, name := range req.Domains { if _, present := authzMap[name]; !present { remainingNames = append(remainingNames, name) } } pendingAuthz, err := ssa.getPendingAuthorizations( ctx, *req.RegistrationID, remainingNames, time.Unix(0, *req.Now), *req.RequireV2Authzs) if err != nil { return nil, err } // merge pending into valid for name, a := range pendingAuthz { authzMap[name] = a } // Wildcard domain issuance requires that the authorizations returned by this // RPC also include populated challenges such that the caller can know if the // challenges meet the wildcard issuance policy (e.g. only 1 DNS-01 // challenge). // Fetch each of the authorizations' associated challenges for _, authz := range authzMap { authz.Challenges, err = ssa.getChallenges(ssa.dbMap.WithContext(ctx), authz.ID) if err != nil { return nil, err } } return authzMapToPB(authzMap) }
go
func (ssa *SQLStorageAuthority) GetAuthorizations( ctx context.Context, req *sapb.GetAuthorizationsRequest) (*sapb.Authorizations, error) { authzMap, err := ssa.getAuthorizations( ctx, authorizationTable, string(core.StatusValid), *req.RegistrationID, req.Domains, time.Unix(0, *req.Now), *req.RequireV2Authzs, ) if err != nil { return nil, err } if len(authzMap) == len(req.Domains) { return authzMapToPB(authzMap) } // remove names we already have authz for remainingNames := []string{} for _, name := range req.Domains { if _, present := authzMap[name]; !present { remainingNames = append(remainingNames, name) } } pendingAuthz, err := ssa.getPendingAuthorizations( ctx, *req.RegistrationID, remainingNames, time.Unix(0, *req.Now), *req.RequireV2Authzs) if err != nil { return nil, err } // merge pending into valid for name, a := range pendingAuthz { authzMap[name] = a } // Wildcard domain issuance requires that the authorizations returned by this // RPC also include populated challenges such that the caller can know if the // challenges meet the wildcard issuance policy (e.g. only 1 DNS-01 // challenge). // Fetch each of the authorizations' associated challenges for _, authz := range authzMap { authz.Challenges, err = ssa.getChallenges(ssa.dbMap.WithContext(ctx), authz.ID) if err != nil { return nil, err } } return authzMapToPB(authzMap) }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetAuthorizations", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "GetAuthorizationsRequest", ")", "(", "*", "sapb", ".", "Authorizations", ",", "error", ")", "{", "authzMap", ",", "err", ":=", "ssa", ".", "getAuthorizations", "(", "ctx", ",", "authorizationTable", ",", "string", "(", "core", ".", "StatusValid", ")", ",", "*", "req", ".", "RegistrationID", ",", "req", ".", "Domains", ",", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Now", ")", ",", "*", "req", ".", "RequireV2Authzs", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "authzMap", ")", "==", "len", "(", "req", ".", "Domains", ")", "{", "return", "authzMapToPB", "(", "authzMap", ")", "\n", "}", "\n\n", "// remove names we already have authz for", "remainingNames", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "name", ":=", "range", "req", ".", "Domains", "{", "if", "_", ",", "present", ":=", "authzMap", "[", "name", "]", ";", "!", "present", "{", "remainingNames", "=", "append", "(", "remainingNames", ",", "name", ")", "\n", "}", "\n", "}", "\n", "pendingAuthz", ",", "err", ":=", "ssa", ".", "getPendingAuthorizations", "(", "ctx", ",", "*", "req", ".", "RegistrationID", ",", "remainingNames", ",", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Now", ")", ",", "*", "req", ".", "RequireV2Authzs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// merge pending into valid", "for", "name", ",", "a", ":=", "range", "pendingAuthz", "{", "authzMap", "[", "name", "]", "=", "a", "\n", "}", "\n\n", "// Wildcard domain issuance requires that the authorizations returned by this", "// RPC also include populated challenges such that the caller can know if the", "// challenges meet the wildcard issuance policy (e.g. only 1 DNS-01", "// challenge).", "// Fetch each of the authorizations' associated challenges", "for", "_", ",", "authz", ":=", "range", "authzMap", "{", "authz", ".", "Challenges", ",", "err", "=", "ssa", ".", "getChallenges", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "authz", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "authzMapToPB", "(", "authzMap", ")", "\n", "}" ]
// GetAuthorizations returns a map of valid or pending authorizations for as many names as possible
[ "GetAuthorizations", "returns", "a", "map", "of", "valid", "or", "pending", "authorizations", "for", "as", "many", "names", "as", "possible" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2143-L2195
train
letsencrypt/boulder
sa/sa.go
AddPendingAuthorizations
func (ssa *SQLStorageAuthority) AddPendingAuthorizations(ctx context.Context, req *sapb.AddPendingAuthorizationsRequest) (*sapb.AuthorizationIDs, error) { ids := []string{} for _, authPB := range req.Authz { authz, err := bgrpc.PBToAuthz(authPB) if err != nil { return nil, err } result, err := ssa.NewPendingAuthorization(ctx, authz) if err != nil { return nil, err } ids = append(ids, result.ID) } return &sapb.AuthorizationIDs{Ids: ids}, nil }
go
func (ssa *SQLStorageAuthority) AddPendingAuthorizations(ctx context.Context, req *sapb.AddPendingAuthorizationsRequest) (*sapb.AuthorizationIDs, error) { ids := []string{} for _, authPB := range req.Authz { authz, err := bgrpc.PBToAuthz(authPB) if err != nil { return nil, err } result, err := ssa.NewPendingAuthorization(ctx, authz) if err != nil { return nil, err } ids = append(ids, result.ID) } return &sapb.AuthorizationIDs{Ids: ids}, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "AddPendingAuthorizations", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "AddPendingAuthorizationsRequest", ")", "(", "*", "sapb", ".", "AuthorizationIDs", ",", "error", ")", "{", "ids", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "authPB", ":=", "range", "req", ".", "Authz", "{", "authz", ",", "err", ":=", "bgrpc", ".", "PBToAuthz", "(", "authPB", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "result", ",", "err", ":=", "ssa", ".", "NewPendingAuthorization", "(", "ctx", ",", "authz", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ids", "=", "append", "(", "ids", ",", "result", ".", "ID", ")", "\n", "}", "\n", "return", "&", "sapb", ".", "AuthorizationIDs", "{", "Ids", ":", "ids", "}", ",", "nil", "\n", "}" ]
// AddPendingAuthorizations creates a batch of pending authorizations and returns their IDs
[ "AddPendingAuthorizations", "creates", "a", "batch", "of", "pending", "authorizations", "and", "returns", "their", "IDs" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2198-L2212
train
letsencrypt/boulder
sa/sa.go
NewAuthorizations2
func (ssa *SQLStorageAuthority) NewAuthorizations2(ctx context.Context, req *sapb.AddPendingAuthorizationsRequest) (*sapb.Authorization2IDs, error) { ids := &sapb.Authorization2IDs{} for _, authz := range req.Authz { if *authz.Status != string(core.StatusPending) { return nil, berrors.InternalServerError("authorization must be pending") } am, err := authzPBToModel(authz) if err != nil { return nil, err } err = ssa.dbMap.Insert(am) if err != nil { return nil, err } ids.Ids = append(ids.Ids, am.ID) } return ids, nil }
go
func (ssa *SQLStorageAuthority) NewAuthorizations2(ctx context.Context, req *sapb.AddPendingAuthorizationsRequest) (*sapb.Authorization2IDs, error) { ids := &sapb.Authorization2IDs{} for _, authz := range req.Authz { if *authz.Status != string(core.StatusPending) { return nil, berrors.InternalServerError("authorization must be pending") } am, err := authzPBToModel(authz) if err != nil { return nil, err } err = ssa.dbMap.Insert(am) if err != nil { return nil, err } ids.Ids = append(ids.Ids, am.ID) } return ids, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "NewAuthorizations2", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "AddPendingAuthorizationsRequest", ")", "(", "*", "sapb", ".", "Authorization2IDs", ",", "error", ")", "{", "ids", ":=", "&", "sapb", ".", "Authorization2IDs", "{", "}", "\n", "for", "_", ",", "authz", ":=", "range", "req", ".", "Authz", "{", "if", "*", "authz", ".", "Status", "!=", "string", "(", "core", ".", "StatusPending", ")", "{", "return", "nil", ",", "berrors", ".", "InternalServerError", "(", "\"", "\"", ")", "\n", "}", "\n", "am", ",", "err", ":=", "authzPBToModel", "(", "authz", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "ssa", ".", "dbMap", ".", "Insert", "(", "am", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ids", ".", "Ids", "=", "append", "(", "ids", ".", "Ids", ",", "am", ".", "ID", ")", "\n", "}", "\n", "return", "ids", ",", "nil", "\n", "}" ]
// NewAuthorizations2 adds a set of new style authorizations to the database and returns // either the IDs of the authorizations or an error. It will only process corepb.Authorization // objects if the V2 field is set. This method is intended to deprecate AddPendingAuthorizations
[ "NewAuthorizations2", "adds", "a", "set", "of", "new", "style", "authorizations", "to", "the", "database", "and", "returns", "either", "the", "IDs", "of", "the", "authorizations", "or", "an", "error", ".", "It", "will", "only", "process", "corepb", ".", "Authorization", "objects", "if", "the", "V2", "field", "is", "set", ".", "This", "method", "is", "intended", "to", "deprecate", "AddPendingAuthorizations" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2238-L2255
train
letsencrypt/boulder
sa/sa.go
GetAuthorization2
func (ssa *SQLStorageAuthority) GetAuthorization2(ctx context.Context, id *sapb.AuthorizationID2) (*corepb.Authorization, error) { obj, err := ssa.dbMap.Get(authz2Model{}, *id.Id) if err != nil { return nil, err } if obj == nil { return nil, berrors.NotFoundError("authorization %d not found", *id.Id) } return modelToAuthzPB(obj.(*authz2Model)) }
go
func (ssa *SQLStorageAuthority) GetAuthorization2(ctx context.Context, id *sapb.AuthorizationID2) (*corepb.Authorization, error) { obj, err := ssa.dbMap.Get(authz2Model{}, *id.Id) if err != nil { return nil, err } if obj == nil { return nil, berrors.NotFoundError("authorization %d not found", *id.Id) } return modelToAuthzPB(obj.(*authz2Model)) }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetAuthorization2", "(", "ctx", "context", ".", "Context", ",", "id", "*", "sapb", ".", "AuthorizationID2", ")", "(", "*", "corepb", ".", "Authorization", ",", "error", ")", "{", "obj", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Get", "(", "authz2Model", "{", "}", ",", "*", "id", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "obj", "==", "nil", "{", "return", "nil", ",", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "*", "id", ".", "Id", ")", "\n", "}", "\n", "return", "modelToAuthzPB", "(", "obj", ".", "(", "*", "authz2Model", ")", ")", "\n", "}" ]
// GetAuthorization2 returns the authz2 style authorization identified by the provided ID or an error. // If no authorization is found matching the ID a berrors.NotFound type error is returned. This method // is intended to deprecate GetAuthorization.
[ "GetAuthorization2", "returns", "the", "authz2", "style", "authorization", "identified", "by", "the", "provided", "ID", "or", "an", "error", ".", "If", "no", "authorization", "is", "found", "matching", "the", "ID", "a", "berrors", ".", "NotFound", "type", "error", "is", "returned", ".", "This", "method", "is", "intended", "to", "deprecate", "GetAuthorization", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2260-L2269
train
letsencrypt/boulder
sa/sa.go
authz2ModelMapToPB
func authz2ModelMapToPB(m map[string]authz2Model) (*sapb.Authorizations, error) { resp := &sapb.Authorizations{} for k, v := range m { // Make a copy of k because it will be reassigned with each loop. kCopy := k authzPB, err := modelToAuthzPB(&v) if err != nil { return nil, err } resp.Authz = append(resp.Authz, &sapb.Authorizations_MapElement{Domain: &kCopy, Authz: authzPB}) } return resp, nil }
go
func authz2ModelMapToPB(m map[string]authz2Model) (*sapb.Authorizations, error) { resp := &sapb.Authorizations{} for k, v := range m { // Make a copy of k because it will be reassigned with each loop. kCopy := k authzPB, err := modelToAuthzPB(&v) if err != nil { return nil, err } resp.Authz = append(resp.Authz, &sapb.Authorizations_MapElement{Domain: &kCopy, Authz: authzPB}) } return resp, nil }
[ "func", "authz2ModelMapToPB", "(", "m", "map", "[", "string", "]", "authz2Model", ")", "(", "*", "sapb", ".", "Authorizations", ",", "error", ")", "{", "resp", ":=", "&", "sapb", ".", "Authorizations", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "m", "{", "// Make a copy of k because it will be reassigned with each loop.", "kCopy", ":=", "k", "\n", "authzPB", ",", "err", ":=", "modelToAuthzPB", "(", "&", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "resp", ".", "Authz", "=", "append", "(", "resp", ".", "Authz", ",", "&", "sapb", ".", "Authorizations_MapElement", "{", "Domain", ":", "&", "kCopy", ",", "Authz", ":", "authzPB", "}", ")", "\n", "}", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// authz2ModelMapToPB converts a mapping of domain name to authz2Models into a // protobuf authorizations map
[ "authz2ModelMapToPB", "converts", "a", "mapping", "of", "domain", "name", "to", "authz2Models", "into", "a", "protobuf", "authorizations", "map" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2273-L2285
train
letsencrypt/boulder
sa/sa.go
FinalizeAuthorization2
func (ssa *SQLStorageAuthority) FinalizeAuthorization2(ctx context.Context, req *sapb.FinalizeAuthorizationRequest) error { if *req.Status != string(core.StatusValid) && *req.Status != string(core.StatusInvalid) { return berrors.InternalServerError("authorization must have status valid or invalid") } query := `UPDATE authz2 SET status = :status, attempted = :attempted, validationRecord = :validationRecord, validationError = :validationError, expires = :expires WHERE id = :id AND status = :pending` var validationRecords []core.ValidationRecord for _, recordPB := range req.ValidationRecords { record, err := bgrpc.PBToValidationRecord(recordPB) if err != nil { return err } validationRecords = append(validationRecords, record) } vrJSON, err := json.Marshal(validationRecords) if err != nil { return err } var veJSON []byte if req.ValidationError != nil { validationError, err := bgrpc.PBToProblemDetails(req.ValidationError) if err != nil { return err } j, err := json.Marshal(validationError) if err != nil { return err } veJSON = j } params := map[string]interface{}{ "status": statusToUint[*req.Status], "attempted": challTypeToUint[*req.Attempted], "validationRecord": vrJSON, "id": *req.Id, "pending": statusUint(core.StatusPending), "expires": time.Unix(0, *req.Expires).UTC(), // if req.ValidationError is nil veJSON should also be nil // which should result in a NULL field "validationError": veJSON, } res, err := ssa.dbMap.Exec(query, params) if err != nil { return err } rows, err := res.RowsAffected() if err != nil { return err } if rows == 0 { return berrors.NotFoundError("authorization with id %d not found", *req.Id) } else if rows > 1 { return berrors.InternalServerError("multiple rows updated for authorization id %d", *req.Id) } return nil }
go
func (ssa *SQLStorageAuthority) FinalizeAuthorization2(ctx context.Context, req *sapb.FinalizeAuthorizationRequest) error { if *req.Status != string(core.StatusValid) && *req.Status != string(core.StatusInvalid) { return berrors.InternalServerError("authorization must have status valid or invalid") } query := `UPDATE authz2 SET status = :status, attempted = :attempted, validationRecord = :validationRecord, validationError = :validationError, expires = :expires WHERE id = :id AND status = :pending` var validationRecords []core.ValidationRecord for _, recordPB := range req.ValidationRecords { record, err := bgrpc.PBToValidationRecord(recordPB) if err != nil { return err } validationRecords = append(validationRecords, record) } vrJSON, err := json.Marshal(validationRecords) if err != nil { return err } var veJSON []byte if req.ValidationError != nil { validationError, err := bgrpc.PBToProblemDetails(req.ValidationError) if err != nil { return err } j, err := json.Marshal(validationError) if err != nil { return err } veJSON = j } params := map[string]interface{}{ "status": statusToUint[*req.Status], "attempted": challTypeToUint[*req.Attempted], "validationRecord": vrJSON, "id": *req.Id, "pending": statusUint(core.StatusPending), "expires": time.Unix(0, *req.Expires).UTC(), // if req.ValidationError is nil veJSON should also be nil // which should result in a NULL field "validationError": veJSON, } res, err := ssa.dbMap.Exec(query, params) if err != nil { return err } rows, err := res.RowsAffected() if err != nil { return err } if rows == 0 { return berrors.NotFoundError("authorization with id %d not found", *req.Id) } else if rows > 1 { return berrors.InternalServerError("multiple rows updated for authorization id %d", *req.Id) } return nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "FinalizeAuthorization2", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "FinalizeAuthorizationRequest", ")", "error", "{", "if", "*", "req", ".", "Status", "!=", "string", "(", "core", ".", "StatusValid", ")", "&&", "*", "req", ".", "Status", "!=", "string", "(", "core", ".", "StatusInvalid", ")", "{", "return", "berrors", ".", "InternalServerError", "(", "\"", "\"", ")", "\n", "}", "\n", "query", ":=", "`UPDATE authz2 SET\n\t\tstatus = :status,\n\t\tattempted = :attempted,\n\t\tvalidationRecord = :validationRecord,\n\t\tvalidationError = :validationError,\n\t\texpires = :expires\n\t\tWHERE id = :id AND status = :pending`", "\n", "var", "validationRecords", "[", "]", "core", ".", "ValidationRecord", "\n", "for", "_", ",", "recordPB", ":=", "range", "req", ".", "ValidationRecords", "{", "record", ",", "err", ":=", "bgrpc", ".", "PBToValidationRecord", "(", "recordPB", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "validationRecords", "=", "append", "(", "validationRecords", ",", "record", ")", "\n", "}", "\n", "vrJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "validationRecords", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "veJSON", "[", "]", "byte", "\n", "if", "req", ".", "ValidationError", "!=", "nil", "{", "validationError", ",", "err", ":=", "bgrpc", ".", "PBToProblemDetails", "(", "req", ".", "ValidationError", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "j", ",", "err", ":=", "json", ".", "Marshal", "(", "validationError", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "veJSON", "=", "j", "\n", "}", "\n", "params", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "statusToUint", "[", "*", "req", ".", "Status", "]", ",", "\"", "\"", ":", "challTypeToUint", "[", "*", "req", ".", "Attempted", "]", ",", "\"", "\"", ":", "vrJSON", ",", "\"", "\"", ":", "*", "req", ".", "Id", ",", "\"", "\"", ":", "statusUint", "(", "core", ".", "StatusPending", ")", ",", "\"", "\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Expires", ")", ".", "UTC", "(", ")", ",", "// if req.ValidationError is nil veJSON should also be nil", "// which should result in a NULL field", "\"", "\"", ":", "veJSON", ",", "}", "\n\n", "res", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Exec", "(", "query", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "rows", ",", "err", ":=", "res", ".", "RowsAffected", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "rows", "==", "0", "{", "return", "berrors", ".", "NotFoundError", "(", "\"", "\"", ",", "*", "req", ".", "Id", ")", "\n", "}", "else", "if", "rows", ">", "1", "{", "return", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "*", "req", ".", "Id", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FinalizeAuthorization2 moves a pending authorization to either the valid or invalid status. If // the authorization is being moved to invalid the validationError field must be set. If the // authorization is being moved to valid the validationRecord and expires fields must be set. // This method is intended to deprecate the FinalizeAuthorization method.
[ "FinalizeAuthorization2", "moves", "a", "pending", "authorization", "to", "either", "the", "valid", "or", "invalid", "status", ".", "If", "the", "authorization", "is", "being", "moved", "to", "invalid", "the", "validationError", "field", "must", "be", "set", ".", "If", "the", "authorization", "is", "being", "moved", "to", "valid", "the", "validationRecord", "and", "expires", "fields", "must", "be", "set", ".", "This", "method", "is", "intended", "to", "deprecate", "the", "FinalizeAuthorization", "method", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2371-L2432
train
letsencrypt/boulder
sa/sa.go
RevokeCertificate
func (ssa *SQLStorageAuthority) RevokeCertificate(ctx context.Context, req *sapb.RevokeCertificateRequest) error { tx, err := ssa.dbMap.Begin() if err != nil { return err } txWithCtx := tx.WithContext(ctx) status, err := SelectCertificateStatus( txWithCtx, "WHERE serial = ? AND status != ?", *req.Serial, string(core.OCSPStatusRevoked), ) if err != nil { if err == sql.ErrNoRows { // InternalServerError because we expected this certificate status to exist and // not be revoked. return Rollback(tx, berrors.InternalServerError("no certificate with serial %s and status %s", *req.Serial, string(core.OCSPStatusRevoked))) } return Rollback(tx, err) } revokedDate := time.Unix(0, *req.Date) status.Status = core.OCSPStatusRevoked status.RevokedReason = revocation.Reason(*req.Reason) status.RevokedDate = revokedDate status.OCSPLastUpdated = revokedDate status.OCSPResponse = req.Response n, err := txWithCtx.Update(&status) if err != nil { return Rollback(tx, err) } if n == 0 { return Rollback(tx, berrors.InternalServerError("no certificate updated")) } return tx.Commit() }
go
func (ssa *SQLStorageAuthority) RevokeCertificate(ctx context.Context, req *sapb.RevokeCertificateRequest) error { tx, err := ssa.dbMap.Begin() if err != nil { return err } txWithCtx := tx.WithContext(ctx) status, err := SelectCertificateStatus( txWithCtx, "WHERE serial = ? AND status != ?", *req.Serial, string(core.OCSPStatusRevoked), ) if err != nil { if err == sql.ErrNoRows { // InternalServerError because we expected this certificate status to exist and // not be revoked. return Rollback(tx, berrors.InternalServerError("no certificate with serial %s and status %s", *req.Serial, string(core.OCSPStatusRevoked))) } return Rollback(tx, err) } revokedDate := time.Unix(0, *req.Date) status.Status = core.OCSPStatusRevoked status.RevokedReason = revocation.Reason(*req.Reason) status.RevokedDate = revokedDate status.OCSPLastUpdated = revokedDate status.OCSPResponse = req.Response n, err := txWithCtx.Update(&status) if err != nil { return Rollback(tx, err) } if n == 0 { return Rollback(tx, berrors.InternalServerError("no certificate updated")) } return tx.Commit() }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "RevokeCertificate", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "RevokeCertificateRequest", ")", "error", "{", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n\n", "status", ",", "err", ":=", "SelectCertificateStatus", "(", "txWithCtx", ",", "\"", "\"", ",", "*", "req", ".", "Serial", ",", "string", "(", "core", ".", "OCSPStatusRevoked", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "// InternalServerError because we expected this certificate status to exist and", "// not be revoked.", "return", "Rollback", "(", "tx", ",", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "*", "req", ".", "Serial", ",", "string", "(", "core", ".", "OCSPStatusRevoked", ")", ")", ")", "\n", "}", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n\n", "revokedDate", ":=", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Date", ")", "\n", "status", ".", "Status", "=", "core", ".", "OCSPStatusRevoked", "\n", "status", ".", "RevokedReason", "=", "revocation", ".", "Reason", "(", "*", "req", ".", "Reason", ")", "\n", "status", ".", "RevokedDate", "=", "revokedDate", "\n", "status", ".", "OCSPLastUpdated", "=", "revokedDate", "\n", "status", ".", "OCSPResponse", "=", "req", ".", "Response", "\n\n", "n", ",", "err", ":=", "txWithCtx", ".", "Update", "(", "&", "status", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "if", "n", "==", "0", "{", "return", "Rollback", "(", "tx", ",", "berrors", ".", "InternalServerError", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "return", "tx", ".", "Commit", "(", ")", "\n", "}" ]
// RevokeCertificate stores revocation information about a certificate. It will only store this // information if the certificate is not alreay marked as revoked. This method is meant as a // replacement for MarkCertificateRevoked and the ocsp-updater database methods.
[ "RevokeCertificate", "stores", "revocation", "information", "about", "a", "certificate", ".", "It", "will", "only", "store", "this", "information", "if", "the", "certificate", "is", "not", "alreay", "marked", "as", "revoked", ".", "This", "method", "is", "meant", "as", "a", "replacement", "for", "MarkCertificateRevoked", "and", "the", "ocsp", "-", "updater", "database", "methods", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2437-L2475
train
letsencrypt/boulder
sa/sa.go
GetPendingAuthorization2
func (ssa *SQLStorageAuthority) GetPendingAuthorization2(ctx context.Context, req *sapb.GetPendingAuthorizationRequest) (*corepb.Authorization, error) { var am authz2Model err := ssa.dbMap.WithContext(ctx).SelectOne( &am, fmt.Sprintf(`SELECT %s FROM authz2 WHERE registrationID = :regID AND identifierValue = :ident AND status = :status AND expires > :validUntil ORDER BY expires ASC LIMIT 1 `, authz2Fields), map[string]interface{}{ "regID": *req.RegistrationID, "ident": *req.IdentifierValue, "status": statusUint(core.StatusPending), "validUntil": time.Unix(0, *req.ValidUntil), }, ) if err != nil { if err == sql.ErrNoRows { // there may be an old style pending authorization so look for that authz, err := ssa.GetPendingAuthorization(ctx, req) if err != nil { return nil, err } return bgrpc.AuthzToPB(*authz) } return nil, err } return modelToAuthzPB(&am) }
go
func (ssa *SQLStorageAuthority) GetPendingAuthorization2(ctx context.Context, req *sapb.GetPendingAuthorizationRequest) (*corepb.Authorization, error) { var am authz2Model err := ssa.dbMap.WithContext(ctx).SelectOne( &am, fmt.Sprintf(`SELECT %s FROM authz2 WHERE registrationID = :regID AND identifierValue = :ident AND status = :status AND expires > :validUntil ORDER BY expires ASC LIMIT 1 `, authz2Fields), map[string]interface{}{ "regID": *req.RegistrationID, "ident": *req.IdentifierValue, "status": statusUint(core.StatusPending), "validUntil": time.Unix(0, *req.ValidUntil), }, ) if err != nil { if err == sql.ErrNoRows { // there may be an old style pending authorization so look for that authz, err := ssa.GetPendingAuthorization(ctx, req) if err != nil { return nil, err } return bgrpc.AuthzToPB(*authz) } return nil, err } return modelToAuthzPB(&am) }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetPendingAuthorization2", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "GetPendingAuthorizationRequest", ")", "(", "*", "corepb", ".", "Authorization", ",", "error", ")", "{", "var", "am", "authz2Model", "\n", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", "(", "&", "am", ",", "fmt", ".", "Sprintf", "(", "`SELECT %s FROM authz2 WHERE\n\t\t\tregistrationID = :regID AND\n\t\t\tidentifierValue = :ident AND\n\t\t\tstatus = :status AND\n\t\t\texpires > :validUntil\n\t\t\tORDER BY expires ASC\n\t\t\tLIMIT 1 `", ",", "authz2Fields", ")", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "*", "req", ".", "RegistrationID", ",", "\"", "\"", ":", "*", "req", ".", "IdentifierValue", ",", "\"", "\"", ":", "statusUint", "(", "core", ".", "StatusPending", ")", ",", "\"", "\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "ValidUntil", ")", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "// there may be an old style pending authorization so look for that", "authz", ",", "err", ":=", "ssa", ".", "GetPendingAuthorization", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "bgrpc", ".", "AuthzToPB", "(", "*", "authz", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "modelToAuthzPB", "(", "&", "am", ")", "\n", "}" ]
// GetPendingAuthorization2 returns the most recent Pending authorization with // the given identifier, if available. This method is intended to deprecate // GetPendingAuthorization.
[ "GetPendingAuthorization2", "returns", "the", "most", "recent", "Pending", "authorization", "with", "the", "given", "identifier", "if", "available", ".", "This", "method", "is", "intended", "to", "deprecate", "GetPendingAuthorization", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2480-L2510
train
letsencrypt/boulder
sa/sa.go
CountPendingAuthorizations2
func (ssa *SQLStorageAuthority) CountPendingAuthorizations2(ctx context.Context, req *sapb.RegistrationID) (*sapb.Count, error) { var count int64 err := ssa.dbMap.WithContext(ctx).SelectOne(&count, `SELECT COUNT(1) FROM authz2 WHERE registrationID = :regID AND expires > :expires AND status = :status`, map[string]interface{}{ "regID": *req.Id, "expires": ssa.clk.Now(), "status": statusUint(core.StatusPending), }, ) if err != nil { return nil, err } // also count old style authorizations and add those to the count of // new authorizations oldCount, err := ssa.CountPendingAuthorizations(ctx, *req.Id) if err != nil { return nil, err } count += int64(oldCount) return &sapb.Count{Count: &count}, nil }
go
func (ssa *SQLStorageAuthority) CountPendingAuthorizations2(ctx context.Context, req *sapb.RegistrationID) (*sapb.Count, error) { var count int64 err := ssa.dbMap.WithContext(ctx).SelectOne(&count, `SELECT COUNT(1) FROM authz2 WHERE registrationID = :regID AND expires > :expires AND status = :status`, map[string]interface{}{ "regID": *req.Id, "expires": ssa.clk.Now(), "status": statusUint(core.StatusPending), }, ) if err != nil { return nil, err } // also count old style authorizations and add those to the count of // new authorizations oldCount, err := ssa.CountPendingAuthorizations(ctx, *req.Id) if err != nil { return nil, err } count += int64(oldCount) return &sapb.Count{Count: &count}, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "CountPendingAuthorizations2", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "RegistrationID", ")", "(", "*", "sapb", ".", "Count", ",", "error", ")", "{", "var", "count", "int64", "\n", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", "(", "&", "count", ",", "`SELECT COUNT(1) FROM authz2 WHERE\n\t\tregistrationID = :regID AND\n\t\texpires > :expires AND\n\t\tstatus = :status`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "*", "req", ".", "Id", ",", "\"", "\"", ":", "ssa", ".", "clk", ".", "Now", "(", ")", ",", "\"", "\"", ":", "statusUint", "(", "core", ".", "StatusPending", ")", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// also count old style authorizations and add those to the count of", "// new authorizations", "oldCount", ",", "err", ":=", "ssa", ".", "CountPendingAuthorizations", "(", "ctx", ",", "*", "req", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "count", "+=", "int64", "(", "oldCount", ")", "\n", "return", "&", "sapb", ".", "Count", "{", "Count", ":", "&", "count", "}", ",", "nil", "\n", "}" ]
// CountPendingAuthorizations2 returns the number of pending, unexpired authorizations // for the given registration. This method is intended to deprecate CountPendingAuthorizations.
[ "CountPendingAuthorizations2", "returns", "the", "number", "of", "pending", "unexpired", "authorizations", "for", "the", "given", "registration", ".", "This", "method", "is", "intended", "to", "deprecate", "CountPendingAuthorizations", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2514-L2538
train
letsencrypt/boulder
sa/sa.go
GetValidOrderAuthorizations2
func (ssa *SQLStorageAuthority) GetValidOrderAuthorizations2(ctx context.Context, req *sapb.GetValidOrderAuthorizationsRequest) (*sapb.Authorizations, error) { var ams []authz2Model _, err := ssa.dbMap.WithContext(ctx).Select( &ams, fmt.Sprintf(`SELECT %s FROM authz2 LEFT JOIN orderToAuthz2 ON authz2.ID = orderToAuthz2.authzID WHERE authz2.registrationID = :regID AND authz2.expires > :expires AND authz2.status = :status AND orderToAuthz2.orderID = :orderID`, authz2Fields, ), map[string]interface{}{ "regID": *req.AcctID, "expires": ssa.clk.Now(), "status": statusUint(core.StatusValid), "orderID": *req.Id, }, ) if err != nil { return nil, err } byName := make(map[string]authz2Model) for _, am := range ams { if uintToIdentifierType[am.IdentifierType] != string(core.IdentifierDNS) { return nil, fmt.Errorf("unknown identifier type: %q on authz id %d", am.IdentifierType, am.ID) } existing, present := byName[am.IdentifierValue] if !present || am.Expires.After(existing.Expires) { byName[am.IdentifierValue] = am } } authzsPB, err := authz2ModelMapToPB(byName) if err != nil { return nil, err } // also get any older style authorizations, as far as I can tell // there is no easy way to tell if this is needed or not as // an order may be all one style, all the other, or a mix oldAuthzMap, err := ssa.GetValidOrderAuthorizations(ctx, req) if err != nil { return nil, err } if len(oldAuthzMap) > 0 { oldAuthzsPB, err := authzMapToPB(oldAuthzMap) if err != nil { return nil, err } for _, authzPB := range oldAuthzsPB.Authz { authzsPB.Authz = append(authzsPB.Authz, authzPB) } } return authzsPB, nil }
go
func (ssa *SQLStorageAuthority) GetValidOrderAuthorizations2(ctx context.Context, req *sapb.GetValidOrderAuthorizationsRequest) (*sapb.Authorizations, error) { var ams []authz2Model _, err := ssa.dbMap.WithContext(ctx).Select( &ams, fmt.Sprintf(`SELECT %s FROM authz2 LEFT JOIN orderToAuthz2 ON authz2.ID = orderToAuthz2.authzID WHERE authz2.registrationID = :regID AND authz2.expires > :expires AND authz2.status = :status AND orderToAuthz2.orderID = :orderID`, authz2Fields, ), map[string]interface{}{ "regID": *req.AcctID, "expires": ssa.clk.Now(), "status": statusUint(core.StatusValid), "orderID": *req.Id, }, ) if err != nil { return nil, err } byName := make(map[string]authz2Model) for _, am := range ams { if uintToIdentifierType[am.IdentifierType] != string(core.IdentifierDNS) { return nil, fmt.Errorf("unknown identifier type: %q on authz id %d", am.IdentifierType, am.ID) } existing, present := byName[am.IdentifierValue] if !present || am.Expires.After(existing.Expires) { byName[am.IdentifierValue] = am } } authzsPB, err := authz2ModelMapToPB(byName) if err != nil { return nil, err } // also get any older style authorizations, as far as I can tell // there is no easy way to tell if this is needed or not as // an order may be all one style, all the other, or a mix oldAuthzMap, err := ssa.GetValidOrderAuthorizations(ctx, req) if err != nil { return nil, err } if len(oldAuthzMap) > 0 { oldAuthzsPB, err := authzMapToPB(oldAuthzMap) if err != nil { return nil, err } for _, authzPB := range oldAuthzsPB.Authz { authzsPB.Authz = append(authzsPB.Authz, authzPB) } } return authzsPB, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetValidOrderAuthorizations2", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "GetValidOrderAuthorizationsRequest", ")", "(", "*", "sapb", ".", "Authorizations", ",", "error", ")", "{", "var", "ams", "[", "]", "authz2Model", "\n", "_", ",", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "Select", "(", "&", "ams", ",", "fmt", ".", "Sprintf", "(", "`SELECT %s FROM authz2\n\t\t\tLEFT JOIN orderToAuthz2 ON authz2.ID = orderToAuthz2.authzID\n\t\t\tWHERE authz2.registrationID = :regID AND\n\t\t\tauthz2.expires > :expires AND\n\t\t\tauthz2.status = :status AND\n\t\t\torderToAuthz2.orderID = :orderID`", ",", "authz2Fields", ",", ")", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "*", "req", ".", "AcctID", ",", "\"", "\"", ":", "ssa", ".", "clk", ".", "Now", "(", ")", ",", "\"", "\"", ":", "statusUint", "(", "core", ".", "StatusValid", ")", ",", "\"", "\"", ":", "*", "req", ".", "Id", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "byName", ":=", "make", "(", "map", "[", "string", "]", "authz2Model", ")", "\n", "for", "_", ",", "am", ":=", "range", "ams", "{", "if", "uintToIdentifierType", "[", "am", ".", "IdentifierType", "]", "!=", "string", "(", "core", ".", "IdentifierDNS", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "am", ".", "IdentifierType", ",", "am", ".", "ID", ")", "\n", "}", "\n", "existing", ",", "present", ":=", "byName", "[", "am", ".", "IdentifierValue", "]", "\n", "if", "!", "present", "||", "am", ".", "Expires", ".", "After", "(", "existing", ".", "Expires", ")", "{", "byName", "[", "am", ".", "IdentifierValue", "]", "=", "am", "\n", "}", "\n", "}", "\n\n", "authzsPB", ",", "err", ":=", "authz2ModelMapToPB", "(", "byName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// also get any older style authorizations, as far as I can tell", "// there is no easy way to tell if this is needed or not as", "// an order may be all one style, all the other, or a mix", "oldAuthzMap", ",", "err", ":=", "ssa", ".", "GetValidOrderAuthorizations", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "oldAuthzMap", ")", ">", "0", "{", "oldAuthzsPB", ",", "err", ":=", "authzMapToPB", "(", "oldAuthzMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "authzPB", ":=", "range", "oldAuthzsPB", ".", "Authz", "{", "authzsPB", ".", "Authz", "=", "append", "(", "authzsPB", ".", "Authz", ",", "authzPB", ")", "\n", "}", "\n", "}", "\n\n", "return", "authzsPB", ",", "nil", "\n", "}" ]
// GetValidOrderAuthorizations2 is used to find the valid, unexpired authorizations // associated with a specific order and account ID. This method is intended to // deprecate GetValidOrderAuthorizations.
[ "GetValidOrderAuthorizations2", "is", "used", "to", "find", "the", "valid", "unexpired", "authorizations", "associated", "with", "a", "specific", "order", "and", "account", "ID", ".", "This", "method", "is", "intended", "to", "deprecate", "GetValidOrderAuthorizations", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2543-L2600
train
letsencrypt/boulder
sa/sa.go
CountInvalidAuthorizations2
func (ssa *SQLStorageAuthority) CountInvalidAuthorizations2(ctx context.Context, req *sapb.CountInvalidAuthorizationsRequest) (*sapb.Count, error) { var count int64 err := ssa.dbMap.WithContext(ctx).SelectOne( &count, `SELECT COUNT(1) FROM authz2 WHERE registrationID = :regID AND identifierValue = :ident AND expires > :expiresEarliest AND expires <= :expiresLatest AND status = :status`, map[string]interface{}{ "regID": *req.RegistrationID, "ident": *req.Hostname, "expiresEarliest": time.Unix(0, *req.Range.Earliest), "expiresLatest": time.Unix(0, *req.Range.Latest), "status": statusUint(core.StatusInvalid), }, ) if err != nil { return nil, err } // Also count old authorizations and add those to the new style // count oldCount, err := ssa.CountInvalidAuthorizations(ctx, req) if err != nil { return nil, err } count += *oldCount.Count return &sapb.Count{Count: &count}, nil }
go
func (ssa *SQLStorageAuthority) CountInvalidAuthorizations2(ctx context.Context, req *sapb.CountInvalidAuthorizationsRequest) (*sapb.Count, error) { var count int64 err := ssa.dbMap.WithContext(ctx).SelectOne( &count, `SELECT COUNT(1) FROM authz2 WHERE registrationID = :regID AND identifierValue = :ident AND expires > :expiresEarliest AND expires <= :expiresLatest AND status = :status`, map[string]interface{}{ "regID": *req.RegistrationID, "ident": *req.Hostname, "expiresEarliest": time.Unix(0, *req.Range.Earliest), "expiresLatest": time.Unix(0, *req.Range.Latest), "status": statusUint(core.StatusInvalid), }, ) if err != nil { return nil, err } // Also count old authorizations and add those to the new style // count oldCount, err := ssa.CountInvalidAuthorizations(ctx, req) if err != nil { return nil, err } count += *oldCount.Count return &sapb.Count{Count: &count}, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "CountInvalidAuthorizations2", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "CountInvalidAuthorizationsRequest", ")", "(", "*", "sapb", ".", "Count", ",", "error", ")", "{", "var", "count", "int64", "\n", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", "(", "&", "count", ",", "`SELECT COUNT(1) FROM authz2 WHERE\n\t\tregistrationID = :regID AND\n\t\tidentifierValue = :ident AND\n\t\texpires > :expiresEarliest AND\n\t\texpires <= :expiresLatest AND\n\t\tstatus = :status`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "*", "req", ".", "RegistrationID", ",", "\"", "\"", ":", "*", "req", ".", "Hostname", ",", "\"", "\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Range", ".", "Earliest", ")", ",", "\"", "\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Range", ".", "Latest", ")", ",", "\"", "\"", ":", "statusUint", "(", "core", ".", "StatusInvalid", ")", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Also count old authorizations and add those to the new style", "// count", "oldCount", ",", "err", ":=", "ssa", ".", "CountInvalidAuthorizations", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "count", "+=", "*", "oldCount", ".", "Count", "\n", "return", "&", "sapb", ".", "Count", "{", "Count", ":", "&", "count", "}", ",", "nil", "\n", "}" ]
// CountInvalidAuthorizations2 counts invalid authorizations for a user expiring // in a given time range. This method is intended to deprecate CountInvalidAuthorizations.
[ "CountInvalidAuthorizations2", "counts", "invalid", "authorizations", "for", "a", "user", "expiring", "in", "a", "given", "time", "range", ".", "This", "method", "is", "intended", "to", "deprecate", "CountInvalidAuthorizations", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2604-L2633
train
letsencrypt/boulder
sa/sa.go
GetValidAuthorizations2
func (ssa *SQLStorageAuthority) GetValidAuthorizations2(ctx context.Context, req *sapb.GetValidAuthorizationsRequest) (*sapb.Authorizations, error) { var authzModels []authz2Model params := []interface{}{ *req.RegistrationID, time.Unix(0, *req.Now), statusUint(core.StatusValid), } qmarks := make([]string, len(req.Domains)) for i, n := range req.Domains { qmarks[i] = "?" params = append(params, n) } _, err := ssa.dbMap.Select( &authzModels, fmt.Sprintf( `SELECT %s from authz2 WHERE registrationID = ? AND expires > ? AND status = ? AND identifierValue IN (%s)`, authz2Fields, strings.Join(qmarks, ","), ), params..., ) if err != nil { return nil, err } authzMap := make(map[string]authz2Model, len(authzModels)) for _, am := range authzModels { // Only allow DNS identifiers if uintToIdentifierType[am.IdentifierType] != string(core.IdentifierDNS) { continue } // If there is an existing authorization in the map only replace it with one // which has a later expiry. if existing, present := authzMap[am.IdentifierValue]; present && am.Expires.Before(existing.Expires) { continue } authzMap[am.IdentifierValue] = am } authzsPB, err := authz2ModelMapToPB(authzMap) if err != nil { return nil, err } if len(authzsPB.Authz) != len(req.Domains) { // We may still have valid old style authorizations // we want for names in the list, so we have to look // for them. var remaining []string for _, name := range req.Domains { if _, present := authzMap[name]; !present { remaining = append(remaining, name) } } now := time.Unix(0, *req.Now) oldAuthzs, err := ssa.GetValidAuthorizations( ctx, *req.RegistrationID, remaining, now, ) if err != nil { return nil, err } if len(oldAuthzs) > 0 { oldAuthzsPB, err := authzMapToPB(oldAuthzs) if err != nil { return nil, err } for _, authzPB := range oldAuthzsPB.Authz { authzsPB.Authz = append(authzsPB.Authz, authzPB) } } } return authzsPB, nil }
go
func (ssa *SQLStorageAuthority) GetValidAuthorizations2(ctx context.Context, req *sapb.GetValidAuthorizationsRequest) (*sapb.Authorizations, error) { var authzModels []authz2Model params := []interface{}{ *req.RegistrationID, time.Unix(0, *req.Now), statusUint(core.StatusValid), } qmarks := make([]string, len(req.Domains)) for i, n := range req.Domains { qmarks[i] = "?" params = append(params, n) } _, err := ssa.dbMap.Select( &authzModels, fmt.Sprintf( `SELECT %s from authz2 WHERE registrationID = ? AND expires > ? AND status = ? AND identifierValue IN (%s)`, authz2Fields, strings.Join(qmarks, ","), ), params..., ) if err != nil { return nil, err } authzMap := make(map[string]authz2Model, len(authzModels)) for _, am := range authzModels { // Only allow DNS identifiers if uintToIdentifierType[am.IdentifierType] != string(core.IdentifierDNS) { continue } // If there is an existing authorization in the map only replace it with one // which has a later expiry. if existing, present := authzMap[am.IdentifierValue]; present && am.Expires.Before(existing.Expires) { continue } authzMap[am.IdentifierValue] = am } authzsPB, err := authz2ModelMapToPB(authzMap) if err != nil { return nil, err } if len(authzsPB.Authz) != len(req.Domains) { // We may still have valid old style authorizations // we want for names in the list, so we have to look // for them. var remaining []string for _, name := range req.Domains { if _, present := authzMap[name]; !present { remaining = append(remaining, name) } } now := time.Unix(0, *req.Now) oldAuthzs, err := ssa.GetValidAuthorizations( ctx, *req.RegistrationID, remaining, now, ) if err != nil { return nil, err } if len(oldAuthzs) > 0 { oldAuthzsPB, err := authzMapToPB(oldAuthzs) if err != nil { return nil, err } for _, authzPB := range oldAuthzsPB.Authz { authzsPB.Authz = append(authzsPB.Authz, authzPB) } } } return authzsPB, nil }
[ "func", "(", "ssa", "*", "SQLStorageAuthority", ")", "GetValidAuthorizations2", "(", "ctx", "context", ".", "Context", ",", "req", "*", "sapb", ".", "GetValidAuthorizationsRequest", ")", "(", "*", "sapb", ".", "Authorizations", ",", "error", ")", "{", "var", "authzModels", "[", "]", "authz2Model", "\n", "params", ":=", "[", "]", "interface", "{", "}", "{", "*", "req", ".", "RegistrationID", ",", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Now", ")", ",", "statusUint", "(", "core", ".", "StatusValid", ")", ",", "}", "\n", "qmarks", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "req", ".", "Domains", ")", ")", "\n", "for", "i", ",", "n", ":=", "range", "req", ".", "Domains", "{", "qmarks", "[", "i", "]", "=", "\"", "\"", "\n", "params", "=", "append", "(", "params", ",", "n", ")", "\n", "}", "\n", "_", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Select", "(", "&", "authzModels", ",", "fmt", ".", "Sprintf", "(", "`SELECT %s from authz2 WHERE\n\t\t\tregistrationID = ? AND\n\t\t\texpires > ? AND\n\t\t\tstatus = ? AND\n\t\t\tidentifierValue IN (%s)`", ",", "authz2Fields", ",", "strings", ".", "Join", "(", "qmarks", ",", "\"", "\"", ")", ",", ")", ",", "params", "...", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "authzMap", ":=", "make", "(", "map", "[", "string", "]", "authz2Model", ",", "len", "(", "authzModels", ")", ")", "\n", "for", "_", ",", "am", ":=", "range", "authzModels", "{", "// Only allow DNS identifiers", "if", "uintToIdentifierType", "[", "am", ".", "IdentifierType", "]", "!=", "string", "(", "core", ".", "IdentifierDNS", ")", "{", "continue", "\n", "}", "\n", "// If there is an existing authorization in the map only replace it with one", "// which has a later expiry.", "if", "existing", ",", "present", ":=", "authzMap", "[", "am", ".", "IdentifierValue", "]", ";", "present", "&&", "am", ".", "Expires", ".", "Before", "(", "existing", ".", "Expires", ")", "{", "continue", "\n", "}", "\n", "authzMap", "[", "am", ".", "IdentifierValue", "]", "=", "am", "\n", "}", "\n", "authzsPB", ",", "err", ":=", "authz2ModelMapToPB", "(", "authzMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "authzsPB", ".", "Authz", ")", "!=", "len", "(", "req", ".", "Domains", ")", "{", "// We may still have valid old style authorizations", "// we want for names in the list, so we have to look", "// for them.", "var", "remaining", "[", "]", "string", "\n", "for", "_", ",", "name", ":=", "range", "req", ".", "Domains", "{", "if", "_", ",", "present", ":=", "authzMap", "[", "name", "]", ";", "!", "present", "{", "remaining", "=", "append", "(", "remaining", ",", "name", ")", "\n", "}", "\n", "}", "\n", "now", ":=", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Now", ")", "\n", "oldAuthzs", ",", "err", ":=", "ssa", ".", "GetValidAuthorizations", "(", "ctx", ",", "*", "req", ".", "RegistrationID", ",", "remaining", ",", "now", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "oldAuthzs", ")", ">", "0", "{", "oldAuthzsPB", ",", "err", ":=", "authzMapToPB", "(", "oldAuthzs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "authzPB", ":=", "range", "oldAuthzsPB", ".", "Authz", "{", "authzsPB", ".", "Authz", "=", "append", "(", "authzsPB", ".", "Authz", ",", "authzPB", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "authzsPB", ",", "nil", "\n", "}" ]
// GetValidAuthorizations2 returns the latest authorization for all // domain names that the account has authorizations for. This method is // intended to deprecate GetValidAuthorizations.
[ "GetValidAuthorizations2", "returns", "the", "latest", "authorization", "for", "all", "domain", "names", "that", "the", "account", "has", "authorizations", "for", ".", "This", "method", "is", "intended", "to", "deprecate", "GetValidAuthorizations", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/sa/sa.go#L2638-L2717
train
letsencrypt/boulder
va/utf8filter.go
replaceInvalidUTF8
func replaceInvalidUTF8(input []byte) string { var b strings.Builder // Ranging over a string in Go produces runes. When the range keyword // encounters an invalid UTF-8 encoding, it returns REPLACEMENT CHARACTER. for _, v := range string(input) { b.WriteRune(v) } return b.String() }
go
func replaceInvalidUTF8(input []byte) string { var b strings.Builder // Ranging over a string in Go produces runes. When the range keyword // encounters an invalid UTF-8 encoding, it returns REPLACEMENT CHARACTER. for _, v := range string(input) { b.WriteRune(v) } return b.String() }
[ "func", "replaceInvalidUTF8", "(", "input", "[", "]", "byte", ")", "string", "{", "var", "b", "strings", ".", "Builder", "\n\n", "// Ranging over a string in Go produces runes. When the range keyword", "// encounters an invalid UTF-8 encoding, it returns REPLACEMENT CHARACTER.", "for", "_", ",", "v", ":=", "range", "string", "(", "input", ")", "{", "b", ".", "WriteRune", "(", "v", ")", "\n", "}", "\n", "return", "b", ".", "String", "(", ")", "\n", "}" ]
// replaceInvalidUTF8 replaces all invalid UTF-8 encodings with // Unicode REPLACEMENT CHARACTER.
[ "replaceInvalidUTF8", "replaces", "all", "invalid", "UTF", "-", "8", "encodings", "with", "Unicode", "REPLACEMENT", "CHARACTER", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/va/utf8filter.go#L7-L16
train
letsencrypt/boulder
publisher/publisher.go
Len
func (c *logCache) Len() int { c.RLock() defer c.RUnlock() return len(c.logs) }
go
func (c *logCache) Len() int { c.RLock() defer c.RUnlock() return len(c.logs) }
[ "func", "(", "c", "*", "logCache", ")", "Len", "(", ")", "int", "{", "c", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "RUnlock", "(", ")", "\n", "return", "len", "(", "c", ".", "logs", ")", "\n", "}" ]
// Len returns the number of logs in the logCache
[ "Len", "returns", "the", "number", "of", "logs", "in", "the", "logCache" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/publisher/publisher.go#L76-L80
train
letsencrypt/boulder
publisher/publisher.go
LogURIs
func (c *logCache) LogURIs() []string { c.RLock() defer c.RUnlock() var uris []string for _, l := range c.logs { uris = append(uris, l.uri) } return uris }
go
func (c *logCache) LogURIs() []string { c.RLock() defer c.RUnlock() var uris []string for _, l := range c.logs { uris = append(uris, l.uri) } return uris }
[ "func", "(", "c", "*", "logCache", ")", "LogURIs", "(", ")", "[", "]", "string", "{", "c", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "RUnlock", "(", ")", "\n", "var", "uris", "[", "]", "string", "\n", "for", "_", ",", "l", ":=", "range", "c", ".", "logs", "{", "uris", "=", "append", "(", "uris", ",", "l", ".", "uri", ")", "\n", "}", "\n", "return", "uris", "\n", "}" ]
// LogURIs returns the URIs of all logs currently in the logCache
[ "LogURIs", "returns", "the", "URIs", "of", "all", "logs", "currently", "in", "the", "logCache" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/publisher/publisher.go#L83-L91
train
letsencrypt/boulder
publisher/publisher.go
NewLog
func NewLog(uri, b64PK string, logger blog.Logger) (*Log, error) { url, err := url.Parse(uri) if err != nil { return nil, err } url.Path = strings.TrimSuffix(url.Path, "/") pemPK := fmt.Sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----", b64PK) opts := jsonclient.Options{ Logger: logAdaptor{logger}, PublicKey: pemPK, } httpClient := &http.Client{ // We set the HTTP client timeout to about half of what we expect // the gRPC timeout to be set to. This allows us to retry the // request at least twice in the case where the server we are // talking to is simply hanging indefinitely. Timeout: time.Minute*2 + time.Second*30, // We provide a new Transport for each Client so that different logs don't // share a connection pool. This shouldn't matter, but we occasionally see a // strange bug where submission to all logs hangs for about fifteen minutes. // One possibility is that there is a strange bug in the locking on // connection pools (possibly triggered by timed-out TCP connections). If // that's the case, separate connection pools should prevent cross-log impact. // We set some fields like TLSHandshakeTimeout to the values from // DefaultTransport because the zero value for these fields means // "unlimited," which would be bad. Transport: &http.Transport{ MaxIdleConns: http.DefaultTransport.(*http.Transport).MaxIdleConns, IdleConnTimeout: http.DefaultTransport.(*http.Transport).IdleConnTimeout, TLSHandshakeTimeout: http.DefaultTransport.(*http.Transport).TLSHandshakeTimeout, }, } client, err := ctClient.New(url.String(), httpClient, opts) if err != nil { return nil, fmt.Errorf("making CT client: %s", err) } // TODO: Maybe this isn't necessary any more now that ctClient can check sigs? pkBytes, err := base64.StdEncoding.DecodeString(b64PK) if err != nil { return nil, fmt.Errorf("Failed to decode base64 log public key") } pk, err := x509.ParsePKIXPublicKey(pkBytes) if err != nil { return nil, fmt.Errorf("Failed to parse log public key") } verifier, err := ct.NewSignatureVerifier(pk) if err != nil { return nil, err } return &Log{ logID: b64PK, uri: url.String(), client: client, verifier: verifier, }, nil }
go
func NewLog(uri, b64PK string, logger blog.Logger) (*Log, error) { url, err := url.Parse(uri) if err != nil { return nil, err } url.Path = strings.TrimSuffix(url.Path, "/") pemPK := fmt.Sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----", b64PK) opts := jsonclient.Options{ Logger: logAdaptor{logger}, PublicKey: pemPK, } httpClient := &http.Client{ // We set the HTTP client timeout to about half of what we expect // the gRPC timeout to be set to. This allows us to retry the // request at least twice in the case where the server we are // talking to is simply hanging indefinitely. Timeout: time.Minute*2 + time.Second*30, // We provide a new Transport for each Client so that different logs don't // share a connection pool. This shouldn't matter, but we occasionally see a // strange bug where submission to all logs hangs for about fifteen minutes. // One possibility is that there is a strange bug in the locking on // connection pools (possibly triggered by timed-out TCP connections). If // that's the case, separate connection pools should prevent cross-log impact. // We set some fields like TLSHandshakeTimeout to the values from // DefaultTransport because the zero value for these fields means // "unlimited," which would be bad. Transport: &http.Transport{ MaxIdleConns: http.DefaultTransport.(*http.Transport).MaxIdleConns, IdleConnTimeout: http.DefaultTransport.(*http.Transport).IdleConnTimeout, TLSHandshakeTimeout: http.DefaultTransport.(*http.Transport).TLSHandshakeTimeout, }, } client, err := ctClient.New(url.String(), httpClient, opts) if err != nil { return nil, fmt.Errorf("making CT client: %s", err) } // TODO: Maybe this isn't necessary any more now that ctClient can check sigs? pkBytes, err := base64.StdEncoding.DecodeString(b64PK) if err != nil { return nil, fmt.Errorf("Failed to decode base64 log public key") } pk, err := x509.ParsePKIXPublicKey(pkBytes) if err != nil { return nil, fmt.Errorf("Failed to parse log public key") } verifier, err := ct.NewSignatureVerifier(pk) if err != nil { return nil, err } return &Log{ logID: b64PK, uri: url.String(), client: client, verifier: verifier, }, nil }
[ "func", "NewLog", "(", "uri", ",", "b64PK", "string", ",", "logger", "blog", ".", "Logger", ")", "(", "*", "Log", ",", "error", ")", "{", "url", ",", "err", ":=", "url", ".", "Parse", "(", "uri", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "url", ".", "Path", "=", "strings", ".", "TrimSuffix", "(", "url", ".", "Path", ",", "\"", "\"", ")", "\n\n", "pemPK", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "b64PK", ")", "\n", "opts", ":=", "jsonclient", ".", "Options", "{", "Logger", ":", "logAdaptor", "{", "logger", "}", ",", "PublicKey", ":", "pemPK", ",", "}", "\n", "httpClient", ":=", "&", "http", ".", "Client", "{", "// We set the HTTP client timeout to about half of what we expect", "// the gRPC timeout to be set to. This allows us to retry the", "// request at least twice in the case where the server we are", "// talking to is simply hanging indefinitely.", "Timeout", ":", "time", ".", "Minute", "*", "2", "+", "time", ".", "Second", "*", "30", ",", "// We provide a new Transport for each Client so that different logs don't", "// share a connection pool. This shouldn't matter, but we occasionally see a", "// strange bug where submission to all logs hangs for about fifteen minutes.", "// One possibility is that there is a strange bug in the locking on", "// connection pools (possibly triggered by timed-out TCP connections). If", "// that's the case, separate connection pools should prevent cross-log impact.", "// We set some fields like TLSHandshakeTimeout to the values from", "// DefaultTransport because the zero value for these fields means", "// \"unlimited,\" which would be bad.", "Transport", ":", "&", "http", ".", "Transport", "{", "MaxIdleConns", ":", "http", ".", "DefaultTransport", ".", "(", "*", "http", ".", "Transport", ")", ".", "MaxIdleConns", ",", "IdleConnTimeout", ":", "http", ".", "DefaultTransport", ".", "(", "*", "http", ".", "Transport", ")", ".", "IdleConnTimeout", ",", "TLSHandshakeTimeout", ":", "http", ".", "DefaultTransport", ".", "(", "*", "http", ".", "Transport", ")", ".", "TLSHandshakeTimeout", ",", "}", ",", "}", "\n", "client", ",", "err", ":=", "ctClient", ".", "New", "(", "url", ".", "String", "(", ")", ",", "httpClient", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// TODO: Maybe this isn't necessary any more now that ctClient can check sigs?", "pkBytes", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "b64PK", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "pk", ",", "err", ":=", "x509", ".", "ParsePKIXPublicKey", "(", "pkBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "verifier", ",", "err", ":=", "ct", ".", "NewSignatureVerifier", "(", "pk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "Log", "{", "logID", ":", "b64PK", ",", "uri", ":", "url", ".", "String", "(", ")", ",", "client", ":", "client", ",", "verifier", ":", "verifier", ",", "}", ",", "nil", "\n", "}" ]
// NewLog returns an initialized Log struct
[ "NewLog", "returns", "an", "initialized", "Log", "struct" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/publisher/publisher.go#L102-L162
train
letsencrypt/boulder
publisher/publisher.go
New
func New( bundle []ct.ASN1Cert, logger blog.Logger, stats metrics.Scope, ) *Impl { return &Impl{ issuerBundle: bundle, ctLogsCache: logCache{ logs: make(map[string]*Log), }, log: logger, metrics: initMetrics(stats), } }
go
func New( bundle []ct.ASN1Cert, logger blog.Logger, stats metrics.Scope, ) *Impl { return &Impl{ issuerBundle: bundle, ctLogsCache: logCache{ logs: make(map[string]*Log), }, log: logger, metrics: initMetrics(stats), } }
[ "func", "New", "(", "bundle", "[", "]", "ct", ".", "ASN1Cert", ",", "logger", "blog", ".", "Logger", ",", "stats", "metrics", ".", "Scope", ",", ")", "*", "Impl", "{", "return", "&", "Impl", "{", "issuerBundle", ":", "bundle", ",", "ctLogsCache", ":", "logCache", "{", "logs", ":", "make", "(", "map", "[", "string", "]", "*", "Log", ")", ",", "}", ",", "log", ":", "logger", ",", "metrics", ":", "initMetrics", "(", "stats", ")", ",", "}", "\n", "}" ]
// New creates a Publisher that will submit certificates // to requested CT logs
[ "New", "creates", "a", "Publisher", "that", "will", "submit", "certificates", "to", "requested", "CT", "logs" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/publisher/publisher.go#L210-L223
train
letsencrypt/boulder
publisher/publisher.go
ProbeLogs
func (pub *Impl) ProbeLogs() { wg := new(sync.WaitGroup) for _, log := range pub.ctLogsCache.LogURIs() { wg.Add(1) go func(uri string) { defer wg.Done() c := http.Client{ Timeout: time.Minute*2 + time.Second*30, } url, err := url.Parse(uri) if err != nil { pub.log.Errf("failed to parse log URI: %s", err) } url.Path = ct.GetSTHPath s := time.Now() resp, err := c.Get(url.String()) took := time.Since(s).Seconds() var status string if err == nil { defer func() { _ = resp.Body.Close() }() status = resp.Status } else { status = "error" } pub.metrics.probeLatency.With(prometheus.Labels{ "log": uri, "status": status, }).Observe(took) }(log) } wg.Wait() }
go
func (pub *Impl) ProbeLogs() { wg := new(sync.WaitGroup) for _, log := range pub.ctLogsCache.LogURIs() { wg.Add(1) go func(uri string) { defer wg.Done() c := http.Client{ Timeout: time.Minute*2 + time.Second*30, } url, err := url.Parse(uri) if err != nil { pub.log.Errf("failed to parse log URI: %s", err) } url.Path = ct.GetSTHPath s := time.Now() resp, err := c.Get(url.String()) took := time.Since(s).Seconds() var status string if err == nil { defer func() { _ = resp.Body.Close() }() status = resp.Status } else { status = "error" } pub.metrics.probeLatency.With(prometheus.Labels{ "log": uri, "status": status, }).Observe(took) }(log) } wg.Wait() }
[ "func", "(", "pub", "*", "Impl", ")", "ProbeLogs", "(", ")", "{", "wg", ":=", "new", "(", "sync", ".", "WaitGroup", ")", "\n", "for", "_", ",", "log", ":=", "range", "pub", ".", "ctLogsCache", ".", "LogURIs", "(", ")", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "uri", "string", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "c", ":=", "http", ".", "Client", "{", "Timeout", ":", "time", ".", "Minute", "*", "2", "+", "time", ".", "Second", "*", "30", ",", "}", "\n", "url", ",", "err", ":=", "url", ".", "Parse", "(", "uri", ")", "\n", "if", "err", "!=", "nil", "{", "pub", ".", "log", ".", "Errf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "url", ".", "Path", "=", "ct", ".", "GetSTHPath", "\n", "s", ":=", "time", ".", "Now", "(", ")", "\n", "resp", ",", "err", ":=", "c", ".", "Get", "(", "url", ".", "String", "(", ")", ")", "\n", "took", ":=", "time", ".", "Since", "(", "s", ")", ".", "Seconds", "(", ")", "\n", "var", "status", "string", "\n", "if", "err", "==", "nil", "{", "defer", "func", "(", ")", "{", "_", "=", "resp", ".", "Body", ".", "Close", "(", ")", "}", "(", ")", "\n", "status", "=", "resp", ".", "Status", "\n", "}", "else", "{", "status", "=", "\"", "\"", "\n", "}", "\n", "pub", ".", "metrics", ".", "probeLatency", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "uri", ",", "\"", "\"", ":", "status", ",", "}", ")", ".", "Observe", "(", "took", ")", "\n", "}", "(", "log", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "}" ]
// ProbeLogs sends a HTTP GET request to each of the logs in the // publisher logCache and records the latency and status of the // response.
[ "ProbeLogs", "sends", "a", "HTTP", "GET", "request", "to", "each", "of", "the", "logs", "in", "the", "publisher", "logCache", "and", "records", "the", "latency", "and", "status", "of", "the", "response", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/publisher/publisher.go#L414-L445
train
letsencrypt/boulder
csr/csr.go
VerifyCSR
func VerifyCSR(csr *x509.CertificateRequest, maxNames int, keyPolicy *goodkey.KeyPolicy, pa core.PolicyAuthority, forceCNFromSAN bool, regID int64) error { normalizeCSR(csr, forceCNFromSAN) key, ok := csr.PublicKey.(crypto.PublicKey) if !ok { return invalidPubKey } if err := keyPolicy.GoodKey(key); err != nil { return fmt.Errorf("invalid public key in CSR: %s", err) } if !goodSignatureAlgorithms[csr.SignatureAlgorithm] { return unsupportedSigAlg } if err := csr.CheckSignature(); err != nil { return invalidSig } if len(csr.EmailAddresses) > 0 { return invalidEmailPresent } if len(csr.IPAddresses) > 0 { return invalidIPPresent } if len(csr.DNSNames) == 0 && csr.Subject.CommonName == "" { return invalidNoDNS } if len(csr.Subject.CommonName) > maxCNLength { return fmt.Errorf("CN was longer than %d bytes", maxCNLength) } if len(csr.DNSNames) > maxNames { return fmt.Errorf("CSR contains more than %d DNS names", maxNames) } badNames := []string{} for _, name := range csr.DNSNames { ident := core.AcmeIdentifier{ Type: core.IdentifierDNS, Value: name, } var err error if err = pa.WillingToIssueWildcard(ident); err != nil { badNames = append(badNames, fmt.Sprintf("%q", name)) } } if len(badNames) > 0 { return fmt.Errorf("policy forbids issuing for: %s", strings.Join(badNames, ", ")) } return nil }
go
func VerifyCSR(csr *x509.CertificateRequest, maxNames int, keyPolicy *goodkey.KeyPolicy, pa core.PolicyAuthority, forceCNFromSAN bool, regID int64) error { normalizeCSR(csr, forceCNFromSAN) key, ok := csr.PublicKey.(crypto.PublicKey) if !ok { return invalidPubKey } if err := keyPolicy.GoodKey(key); err != nil { return fmt.Errorf("invalid public key in CSR: %s", err) } if !goodSignatureAlgorithms[csr.SignatureAlgorithm] { return unsupportedSigAlg } if err := csr.CheckSignature(); err != nil { return invalidSig } if len(csr.EmailAddresses) > 0 { return invalidEmailPresent } if len(csr.IPAddresses) > 0 { return invalidIPPresent } if len(csr.DNSNames) == 0 && csr.Subject.CommonName == "" { return invalidNoDNS } if len(csr.Subject.CommonName) > maxCNLength { return fmt.Errorf("CN was longer than %d bytes", maxCNLength) } if len(csr.DNSNames) > maxNames { return fmt.Errorf("CSR contains more than %d DNS names", maxNames) } badNames := []string{} for _, name := range csr.DNSNames { ident := core.AcmeIdentifier{ Type: core.IdentifierDNS, Value: name, } var err error if err = pa.WillingToIssueWildcard(ident); err != nil { badNames = append(badNames, fmt.Sprintf("%q", name)) } } if len(badNames) > 0 { return fmt.Errorf("policy forbids issuing for: %s", strings.Join(badNames, ", ")) } return nil }
[ "func", "VerifyCSR", "(", "csr", "*", "x509", ".", "CertificateRequest", ",", "maxNames", "int", ",", "keyPolicy", "*", "goodkey", ".", "KeyPolicy", ",", "pa", "core", ".", "PolicyAuthority", ",", "forceCNFromSAN", "bool", ",", "regID", "int64", ")", "error", "{", "normalizeCSR", "(", "csr", ",", "forceCNFromSAN", ")", "\n", "key", ",", "ok", ":=", "csr", ".", "PublicKey", ".", "(", "crypto", ".", "PublicKey", ")", "\n", "if", "!", "ok", "{", "return", "invalidPubKey", "\n", "}", "\n", "if", "err", ":=", "keyPolicy", ".", "GoodKey", "(", "key", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "goodSignatureAlgorithms", "[", "csr", ".", "SignatureAlgorithm", "]", "{", "return", "unsupportedSigAlg", "\n", "}", "\n", "if", "err", ":=", "csr", ".", "CheckSignature", "(", ")", ";", "err", "!=", "nil", "{", "return", "invalidSig", "\n", "}", "\n", "if", "len", "(", "csr", ".", "EmailAddresses", ")", ">", "0", "{", "return", "invalidEmailPresent", "\n", "}", "\n", "if", "len", "(", "csr", ".", "IPAddresses", ")", ">", "0", "{", "return", "invalidIPPresent", "\n", "}", "\n", "if", "len", "(", "csr", ".", "DNSNames", ")", "==", "0", "&&", "csr", ".", "Subject", ".", "CommonName", "==", "\"", "\"", "{", "return", "invalidNoDNS", "\n", "}", "\n", "if", "len", "(", "csr", ".", "Subject", ".", "CommonName", ")", ">", "maxCNLength", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "maxCNLength", ")", "\n", "}", "\n", "if", "len", "(", "csr", ".", "DNSNames", ")", ">", "maxNames", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "maxNames", ")", "\n", "}", "\n", "badNames", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "name", ":=", "range", "csr", ".", "DNSNames", "{", "ident", ":=", "core", ".", "AcmeIdentifier", "{", "Type", ":", "core", ".", "IdentifierDNS", ",", "Value", ":", "name", ",", "}", "\n", "var", "err", "error", "\n", "if", "err", "=", "pa", ".", "WillingToIssueWildcard", "(", "ident", ")", ";", "err", "!=", "nil", "{", "badNames", "=", "append", "(", "badNames", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "badNames", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "badNames", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// VerifyCSR checks the validity of a x509.CertificateRequest. Before doing checks it normalizes // the CSR which lowers the case of DNS names and subject CN, and if forceCNFromSAN is true it // will hoist a DNS name into the CN if it is empty.
[ "VerifyCSR", "checks", "the", "validity", "of", "a", "x509", ".", "CertificateRequest", ".", "Before", "doing", "checks", "it", "normalizes", "the", "CSR", "which", "lowers", "the", "case", "of", "DNS", "names", "and", "subject", "CN", "and", "if", "forceCNFromSAN", "is", "true", "it", "will", "hoist", "a", "DNS", "name", "into", "the", "CN", "if", "it", "is", "empty", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/csr/csr.go#L46-L91
train
letsencrypt/boulder
csr/csr.go
normalizeCSR
func normalizeCSR(csr *x509.CertificateRequest, forceCNFromSAN bool) { if forceCNFromSAN && csr.Subject.CommonName == "" { if len(csr.DNSNames) > 0 { csr.Subject.CommonName = csr.DNSNames[0] } } else if csr.Subject.CommonName != "" { csr.DNSNames = append(csr.DNSNames, csr.Subject.CommonName) } csr.Subject.CommonName = strings.ToLower(csr.Subject.CommonName) csr.DNSNames = core.UniqueLowerNames(csr.DNSNames) }
go
func normalizeCSR(csr *x509.CertificateRequest, forceCNFromSAN bool) { if forceCNFromSAN && csr.Subject.CommonName == "" { if len(csr.DNSNames) > 0 { csr.Subject.CommonName = csr.DNSNames[0] } } else if csr.Subject.CommonName != "" { csr.DNSNames = append(csr.DNSNames, csr.Subject.CommonName) } csr.Subject.CommonName = strings.ToLower(csr.Subject.CommonName) csr.DNSNames = core.UniqueLowerNames(csr.DNSNames) }
[ "func", "normalizeCSR", "(", "csr", "*", "x509", ".", "CertificateRequest", ",", "forceCNFromSAN", "bool", ")", "{", "if", "forceCNFromSAN", "&&", "csr", ".", "Subject", ".", "CommonName", "==", "\"", "\"", "{", "if", "len", "(", "csr", ".", "DNSNames", ")", ">", "0", "{", "csr", ".", "Subject", ".", "CommonName", "=", "csr", ".", "DNSNames", "[", "0", "]", "\n", "}", "\n", "}", "else", "if", "csr", ".", "Subject", ".", "CommonName", "!=", "\"", "\"", "{", "csr", ".", "DNSNames", "=", "append", "(", "csr", ".", "DNSNames", ",", "csr", ".", "Subject", ".", "CommonName", ")", "\n", "}", "\n", "csr", ".", "Subject", ".", "CommonName", "=", "strings", ".", "ToLower", "(", "csr", ".", "Subject", ".", "CommonName", ")", "\n", "csr", ".", "DNSNames", "=", "core", ".", "UniqueLowerNames", "(", "csr", ".", "DNSNames", ")", "\n", "}" ]
// normalizeCSR deduplicates and lowers the case of dNSNames and the subject CN. // If forceCNFromSAN is true it will also hoist a dNSName into the CN if it is empty.
[ "normalizeCSR", "deduplicates", "and", "lowers", "the", "case", "of", "dNSNames", "and", "the", "subject", "CN", ".", "If", "forceCNFromSAN", "is", "true", "it", "will", "also", "hoist", "a", "dNSName", "into", "the", "CN", "if", "it", "is", "empty", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/csr/csr.go#L95-L105
train
letsencrypt/boulder
goodkey/good_key.go
NewKeyPolicy
func NewKeyPolicy(weakKeyFile string) (KeyPolicy, error) { kp := KeyPolicy{ AllowRSA: true, AllowECDSANISTP256: true, AllowECDSANISTP384: true, } if weakKeyFile != "" { keyList, err := LoadWeakRSASuffixes(weakKeyFile) if err != nil { return KeyPolicy{}, err } kp.weakRSAList = keyList } return kp, nil }
go
func NewKeyPolicy(weakKeyFile string) (KeyPolicy, error) { kp := KeyPolicy{ AllowRSA: true, AllowECDSANISTP256: true, AllowECDSANISTP384: true, } if weakKeyFile != "" { keyList, err := LoadWeakRSASuffixes(weakKeyFile) if err != nil { return KeyPolicy{}, err } kp.weakRSAList = keyList } return kp, nil }
[ "func", "NewKeyPolicy", "(", "weakKeyFile", "string", ")", "(", "KeyPolicy", ",", "error", ")", "{", "kp", ":=", "KeyPolicy", "{", "AllowRSA", ":", "true", ",", "AllowECDSANISTP256", ":", "true", ",", "AllowECDSANISTP384", ":", "true", ",", "}", "\n", "if", "weakKeyFile", "!=", "\"", "\"", "{", "keyList", ",", "err", ":=", "LoadWeakRSASuffixes", "(", "weakKeyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "KeyPolicy", "{", "}", ",", "err", "\n", "}", "\n", "kp", ".", "weakRSAList", "=", "keyList", "\n", "}", "\n", "return", "kp", ",", "nil", "\n", "}" ]
// NewKeyPolicy returns a KeyPolicy that allows RSA, ECDSA256 and ECDSA384. // weakKeyFile contains the path to a JSON file containing truncated modulus // hashes of known weak RSA keys. If this argument is empty RSA modulus hash // checking will be disabled.
[ "NewKeyPolicy", "returns", "a", "KeyPolicy", "that", "allows", "RSA", "ECDSA256", "and", "ECDSA384", ".", "weakKeyFile", "contains", "the", "path", "to", "a", "JSON", "file", "containing", "truncated", "modulus", "hashes", "of", "known", "weak", "RSA", "keys", ".", "If", "this", "argument", "is", "empty", "RSA", "modulus", "hash", "checking", "will", "be", "disabled", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/goodkey/good_key.go#L50-L64
train
letsencrypt/boulder
goodkey/good_key.go
checkSmallPrimes
func checkSmallPrimes(i *big.Int) bool { smallPrimesSingleton.Do(func() { for _, prime := range smallPrimeInts { smallPrimes = append(smallPrimes, big.NewInt(prime)) } }) for _, prime := range smallPrimes { var result big.Int result.Mod(i, prime) if result.Sign() == 0 { return true } } return false }
go
func checkSmallPrimes(i *big.Int) bool { smallPrimesSingleton.Do(func() { for _, prime := range smallPrimeInts { smallPrimes = append(smallPrimes, big.NewInt(prime)) } }) for _, prime := range smallPrimes { var result big.Int result.Mod(i, prime) if result.Sign() == 0 { return true } } return false }
[ "func", "checkSmallPrimes", "(", "i", "*", "big", ".", "Int", ")", "bool", "{", "smallPrimesSingleton", ".", "Do", "(", "func", "(", ")", "{", "for", "_", ",", "prime", ":=", "range", "smallPrimeInts", "{", "smallPrimes", "=", "append", "(", "smallPrimes", ",", "big", ".", "NewInt", "(", "prime", ")", ")", "\n", "}", "\n", "}", ")", "\n\n", "for", "_", ",", "prime", ":=", "range", "smallPrimes", "{", "var", "result", "big", ".", "Int", "\n", "result", ".", "Mod", "(", "i", ",", "prime", ")", "\n", "if", "result", ".", "Sign", "(", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Returns true iff integer i is divisible by any of the primes in smallPrimes. // // Short circuits; execution time is dependent on i. Do not use this on secret // values.
[ "Returns", "true", "iff", "integer", "i", "is", "divisible", "by", "any", "of", "the", "primes", "in", "smallPrimes", ".", "Short", "circuits", ";", "execution", "time", "is", "dependent", "on", "i", ".", "Do", "not", "use", "this", "on", "secret", "values", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/goodkey/good_key.go#L249-L265
train
letsencrypt/boulder
metrics/mock_metrics/mock_scope.go
NewMockScope
func NewMockScope(ctrl *gomock.Controller) *MockScope { mock := &MockScope{ctrl: ctrl} mock.recorder = &MockScopeMockRecorder{mock} return mock }
go
func NewMockScope(ctrl *gomock.Controller) *MockScope { mock := &MockScope{ctrl: ctrl} mock.recorder = &MockScopeMockRecorder{mock} return mock }
[ "func", "NewMockScope", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockScope", "{", "mock", ":=", "&", "MockScope", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockScopeMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockScope creates a new mock instance
[ "NewMockScope", "creates", "a", "new", "mock", "instance" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/mock_metrics/mock_scope.go#L27-L31
train
letsencrypt/boulder
metrics/mock_metrics/mock_scope.go
MustRegister
func (m *MockScope) MustRegister(arg0 ...prometheus.Collector) { m.ctrl.T.Helper() varargs := []interface{}{} for _, a := range arg0 { varargs = append(varargs, a) } m.ctrl.Call(m, "MustRegister", varargs...) }
go
func (m *MockScope) MustRegister(arg0 ...prometheus.Collector) { m.ctrl.T.Helper() varargs := []interface{}{} for _, a := range arg0 { varargs = append(varargs, a) } m.ctrl.Call(m, "MustRegister", varargs...) }
[ "func", "(", "m", "*", "MockScope", ")", "MustRegister", "(", "arg0", "...", "prometheus", ".", "Collector", ")", "{", "m", ".", "ctrl", ".", "T", ".", "Helper", "(", ")", "\n", "varargs", ":=", "[", "]", "interface", "{", "}", "{", "}", "\n", "for", "_", ",", "a", ":=", "range", "arg0", "{", "varargs", "=", "append", "(", "varargs", ",", "a", ")", "\n", "}", "\n", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "varargs", "...", ")", "\n", "}" ]
// MustRegister mocks base method
[ "MustRegister", "mocks", "base", "method" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/metrics/mock_metrics/mock_scope.go#L75-L82
train
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", ",", "\"", "\"", ",", "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", ",", "\"", "\"", ",", "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", "{", "// 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", "\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", "// De-duplicate the base domains.", "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\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\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\n", "// 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", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "attrs", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// 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", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "var", "pub", "crypto", ".", "PublicKey", "\n", "var", "keyType", "pkcs11helpers", ".", "KeyType", "\n", "switch", "{", "// 0x00000000, CKK_RSA", "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", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// 0x00000003, CKK_ECDSA", "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", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\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", ":=", "\"", "\"", "\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\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\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\n", "sigAlg", ",", "ok", ":=", "AllowedSigAlgs", "[", "profile", ".", "SignatureAlgorithm", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "profile", ".", "SignatureAlgorithm", ")", "\n", "}", "\n\n", "subjectKeyID", ":=", "sha256", ".", "Sum256", "(", "pubKey", ")", "\n\n", "serial", ",", "err", ":=", "ctx", ".", "GenerateRandom", "(", "session", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\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\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\n", "signRequest", ":=", "core", ".", "OCSPSigningRequest", "{", "CertDER", ":", "cert", ".", "DER", ",", "Status", ":", "string", "(", "core", ".", "OCSPStatusRevoked", ")", ",", "Reason", ":", "status", ".", "RevokedReason", ",", "RevokedAt", ":", "status", ".", "RevokedDate", ",", "}", "\n\n", "ocspResponse", ",", "err", ":=", "updater", ".", "cac", ".", "GenerateOCSP", "(", "ctx", ",", "signRequest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "now", ":=", "updater", ".", "clk", ".", "Now", "(", ")", "\n", "status", ".", "OCSPLastUpdated", "=", "now", "\n", "status", ".", "OCSPResponse", "=", "ocspResponse", "\n\n", "// If cache client is populated generate purge URLs", "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\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\n \t\tSET isExpired = TRUE\n \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", ")", "{", "// Create a dbMetrics instance and register prometheus metrics", "dbm", ":=", "newDbMetrics", "(", "dbMap", ",", "scope", ")", "\n\n", "// Start the metric reporting goroutine to update the metrics periodically.", "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", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ")", "\n", "scope", ".", "MustRegister", "(", "maxOpenConns", ")", "\n\n", "openConns", ":=", "prometheus", ".", "NewGauge", "(", "prometheus", ".", "GaugeOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ")", "\n", "scope", ".", "MustRegister", "(", "openConns", ")", "\n\n", "inUse", ":=", "prometheus", ".", "NewGauge", "(", "prometheus", ".", "GaugeOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ")", "\n", "scope", ".", "MustRegister", "(", "inUse", ")", "\n\n", "idle", ":=", "prometheus", ".", "NewGauge", "(", "prometheus", ".", "GaugeOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ")", "\n", "scope", ".", "MustRegister", "(", "idle", ")", "\n\n", "waitCount", ":=", "prometheus", ".", "NewCounter", "(", "prometheus", ".", "CounterOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ")", "\n", "scope", ".", "MustRegister", "(", "waitCount", ")", "\n\n", "waitDuration", ":=", "prometheus", ".", "NewCounter", "(", "prometheus", ".", "CounterOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ")", "\n", "scope", ".", "MustRegister", "(", "waitDuration", ")", "\n\n", "maxIdleClosed", ":=", "prometheus", ".", "NewCounter", "(", "prometheus", ".", "CounterOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ")", "\n", "scope", ".", "MustRegister", "(", "maxIdleClosed", ")", "\n\n", "maxLifetimeClosed", ":=", "prometheus", ".", "NewCounter", "(", "prometheus", ".", "CounterOpts", "{", "Name", ":", "\"", "\"", ",", "Help", ":", "\"", "\"", ",", "}", ")", "\n", "scope", ".", "MustRegister", "(", "maxLifetimeClosed", ")", "\n\n", "// 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", ",", "}", "\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", "[", "\"", "\"", "]", ";", "ok", "{", "unwrappedErr", ":=", "grpc", ".", "ErrorDesc", "(", "err", ")", "\n", "if", "len", "(", "errTypeStrs", ")", "!=", "1", "{", "return", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "unwrappedErr", ",", ")", "\n", "}", "\n", "errType", ",", "decErr", ":=", "strconv", ".", "Atoi", "(", "errTypeStrs", "[", "0", "]", ")", "\n", "if", "decErr", "!=", "nil", "{", "return", "berrors", ".", "InternalServerError", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ")", ",", "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", "(", "\"", "\"", ",", "1", ")", "\n\n", "for", "{", "err", ":=", "m", ".", "sendOne", "(", "to", ",", "subject", ",", "msg", ")", "\n", "if", "err", "==", "nil", "{", "// If the error is nil, we sent the mail without issue. nice!", "break", "\n", "}", "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", "(", "\"", "\"", ",", "1", ")", "\n", "m", ".", "reconnect", "(", ")", "\n", "// After reconnecting, loop around and try `sendOne` again.", "m", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "continue", "\n", "}", "else", "if", "protoErr", ",", "ok", ":=", "err", ".", "(", "*", "textproto", ".", "Error", ")", ";", "ok", "&&", "protoErr", ".", "Code", "==", "421", "{", "/*\n\t\t\t * If the error is an instance of `textproto.Error` with a SMTP error code,\n\t\t\t * and that error code is 421 then treat this as a reconnect-able event.\n\t\t\t *\n\t\t\t * The SMTP RFC defines this error code as:\n\t\t\t * 421 <domain> Service not available, closing transmission channel\n\t\t\t * (This may be a reply to any command if the service knows it\n\t\t\t * must shut down)\n\t\t\t *\n\t\t\t * In practice we see this code being used by our production SMTP server\n\t\t\t * when the connection has gone idle for too long. For more information\n\t\t\t * see issue #2249[0].\n\t\t\t *\n\t\t\t * [0] - https://github.com/letsencrypt/boulder/issues/2249\n\t\t\t */", "m", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "m", ".", "reconnect", "(", ")", "\n", "m", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "1", ")", "\n", "}", "else", "if", "protoErr", ",", "ok", ":=", "err", ".", "(", "*", "textproto", ".", "Error", ")", ";", "ok", "&&", "recoverableErrorCodes", "[", "protoErr", ".", "Code", "]", "{", "m", ".", "stats", ".", "Inc", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "protoErr", ".", "Code", ")", ",", "1", ")", "\n", "return", "RecoverableSMTPError", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "protoErr", ".", "Code", ",", "protoErr", ".", "Msg", ")", "}", "\n", "}", "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", "(", "\"", "\"", ",", "1", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "m", ".", "stats", ".", "Inc", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "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\n", "signRequest", ":=", "ocsp", ".", "SignRequest", "{", "Certificate", ":", "cert", ",", "Status", ":", "xferObj", ".", "Status", ",", "Reason", ":", "int", "(", "xferObj", ".", "Reason", ")", ",", "RevokedAt", ":", "xferObj", ".", "RevokedAt", ",", "}", "\n\n", "cn", ":=", "cert", ".", "Issuer", ".", "CommonName", "\n", "issuer", ":=", "ca", ".", "issuers", "[", "cn", "]", "\n", "if", "issuer", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cn", ")", "\n", "}", "\n\n", "err", "=", "cert", ".", "CheckSignatureFrom", "(", "issuer", ".", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "core", ".", "SerialToString", "(", "cert", ".", "SerialNumber", ")", ",", "cn", ",", "err", ")", "\n", "}", "\n\n", "ocspResponse", ",", "err", ":=", "issuer", ".", "ocspSigner", ".", "Sign", "(", "signRequest", ")", "\n", "ca", ".", "noteSignError", "(", "err", ")", "\n", "if", "err", "==", "nil", "{", "ca", ".", "signatureCount", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"", "\"", ":", "\"", "\"", "}", ")", ".", "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", "!=", "\"", "\"", "{", "err", "=", "berrors", ".", "InternalServerError", "(", "\"", "\"", ")", "\n", "ca", ".", "log", ".", "AuditErrf", "(", "\"", "\"", ",", "serialHex", ",", "certPEM", ",", "err", ")", "\n", "return", "emptyCert", ",", "err", "\n", "}", "\n", "certDER", ":=", "block", ".", "Bytes", "\n", "ca", ".", "log", ".", "AuditInfof", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "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