repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
letsencrypt/boulder
probs/probs.go
ProblemDetailsToStatusCode
func ProblemDetailsToStatusCode(prob *ProblemDetails) int { if prob.HTTPStatus != 0 { return prob.HTTPStatus } switch prob.Type { case ConnectionProblem, MalformedProblem, BadSignatureAlgorithmProblem, BadPublicKeyProblem, TLSProblem, UnknownHostProblem, BadNonceProblem, InvalidEmailProblem, RejectedIdentifierProblem, AccountDoesNotExistProblem: return http.StatusBadRequest case ServerInternalProblem: return http.StatusInternalServerError case UnauthorizedProblem, CAAProblem: return http.StatusForbidden case RateLimitedProblem: return statusTooManyRequests default: return http.StatusInternalServerError } }
go
func ProblemDetailsToStatusCode(prob *ProblemDetails) int { if prob.HTTPStatus != 0 { return prob.HTTPStatus } switch prob.Type { case ConnectionProblem, MalformedProblem, BadSignatureAlgorithmProblem, BadPublicKeyProblem, TLSProblem, UnknownHostProblem, BadNonceProblem, InvalidEmailProblem, RejectedIdentifierProblem, AccountDoesNotExistProblem: return http.StatusBadRequest case ServerInternalProblem: return http.StatusInternalServerError case UnauthorizedProblem, CAAProblem: return http.StatusForbidden case RateLimitedProblem: return statusTooManyRequests default: return http.StatusInternalServerError } }
[ "func", "ProblemDetailsToStatusCode", "(", "prob", "*", "ProblemDetails", ")", "int", "{", "if", "prob", ".", "HTTPStatus", "!=", "0", "{", "return", "prob", ".", "HTTPStatus", "\n", "}", "\n", "switch", "prob", ".", "Type", "{", "case", "ConnectionProblem", ",", "MalformedProblem", ",", "BadSignatureAlgorithmProblem", ",", "BadPublicKeyProblem", ",", "TLSProblem", ",", "UnknownHostProblem", ",", "BadNonceProblem", ",", "InvalidEmailProblem", ",", "RejectedIdentifierProblem", ",", "AccountDoesNotExistProblem", ":", "return", "http", ".", "StatusBadRequest", "\n", "case", "ServerInternalProblem", ":", "return", "http", ".", "StatusInternalServerError", "\n", "case", "UnauthorizedProblem", ",", "CAAProblem", ":", "return", "http", ".", "StatusForbidden", "\n", "case", "RateLimitedProblem", ":", "return", "statusTooManyRequests", "\n", "default", ":", "return", "http", ".", "StatusInternalServerError", "\n", "}", "\n", "}" ]
// ProblemDetailsToStatusCode inspects the given ProblemDetails to figure out // what HTTP status code it should represent. It should only be used by the WFE // but is included in this package because of its reliance on ProblemTypes.
[ "ProblemDetailsToStatusCode", "inspects", "the", "given", "ProblemDetails", "to", "figure", "out", "what", "HTTP", "status", "code", "it", "should", "represent", ".", "It", "should", "only", "be", "used", "by", "the", "WFE", "but", "is", "included", "in", "this", "package", "because", "of", "its", "reliance", "on", "ProblemTypes", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L56-L84
train
letsencrypt/boulder
probs/probs.go
BadNonce
func BadNonce(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: BadNonceProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func BadNonce(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: BadNonceProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "BadNonce", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "BadNonceProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// BadNonce returns a ProblemDetails with a BadNonceProblem and a 400 Bad // Request status code.
[ "BadNonce", "returns", "a", "ProblemDetails", "with", "a", "BadNonceProblem", "and", "a", "400", "Bad", "Request", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L88-L94
train
letsencrypt/boulder
probs/probs.go
RejectedIdentifier
func RejectedIdentifier(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: RejectedIdentifierProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func RejectedIdentifier(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: RejectedIdentifierProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "RejectedIdentifier", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "RejectedIdentifierProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// RejectedIdentifier returns a ProblemDetails with a RejectedIdentifierProblem and a 400 Bad // Request status code.
[ "RejectedIdentifier", "returns", "a", "ProblemDetails", "with", "a", "RejectedIdentifierProblem", "and", "a", "400", "Bad", "Request", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L98-L104
train
letsencrypt/boulder
probs/probs.go
Conflict
func Conflict(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: MalformedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusConflict, } }
go
func Conflict(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: MalformedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusConflict, } }
[ "func", "Conflict", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "MalformedProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusConflict", ",", "}", "\n", "}" ]
// Conflict returns a ProblemDetails with a MalformedProblem and a 409 Conflict // status code.
[ "Conflict", "returns", "a", "ProblemDetails", "with", "a", "MalformedProblem", "and", "a", "409", "Conflict", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L108-L114
train
letsencrypt/boulder
probs/probs.go
AlreadyRevoked
func AlreadyRevoked(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: AlreadyRevokedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func AlreadyRevoked(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: AlreadyRevokedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "AlreadyRevoked", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "AlreadyRevokedProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// AlreadyRevoked returns a ProblemDetails with a AlreadyRevokedProblem and a 400 Bad // Request status code.
[ "AlreadyRevoked", "returns", "a", "ProblemDetails", "with", "a", "AlreadyRevokedProblem", "and", "a", "400", "Bad", "Request", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L118-L124
train
letsencrypt/boulder
probs/probs.go
Malformed
func Malformed(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: MalformedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func Malformed(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: MalformedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "Malformed", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "MalformedProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// Malformed returns a ProblemDetails with a MalformedProblem and a 400 Bad // Request status code.
[ "Malformed", "returns", "a", "ProblemDetails", "with", "a", "MalformedProblem", "and", "a", "400", "Bad", "Request", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L128-L134
train
letsencrypt/boulder
probs/probs.go
BadSignatureAlgorithm
func BadSignatureAlgorithm(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: BadSignatureAlgorithmProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func BadSignatureAlgorithm(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: BadSignatureAlgorithmProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "BadSignatureAlgorithm", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "BadSignatureAlgorithmProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// BadSignatureAlgorithm returns a ProblemDetails with a BadSignatureAlgorithmProblem // and a 400 Bad Request status code.
[ "BadSignatureAlgorithm", "returns", "a", "ProblemDetails", "with", "a", "BadSignatureAlgorithmProblem", "and", "a", "400", "Bad", "Request", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L138-L144
train
letsencrypt/boulder
probs/probs.go
BadPublicKey
func BadPublicKey(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: BadPublicKeyProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func BadPublicKey(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: BadPublicKeyProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "BadPublicKey", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "BadPublicKeyProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// BadPublicKey returns a ProblemDetails with a BadPublicKeyProblem and a 400 Bad // Request status code.
[ "BadPublicKey", "returns", "a", "ProblemDetails", "with", "a", "BadPublicKeyProblem", "and", "a", "400", "Bad", "Request", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L148-L154
train
letsencrypt/boulder
probs/probs.go
NotFound
func NotFound(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: MalformedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusNotFound, } }
go
func NotFound(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: MalformedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusNotFound, } }
[ "func", "NotFound", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "MalformedProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusNotFound", ",", "}", "\n", "}" ]
// NotFound returns a ProblemDetails with a MalformedProblem and a 404 Not Found // status code.
[ "NotFound", "returns", "a", "ProblemDetails", "with", "a", "MalformedProblem", "and", "a", "404", "Not", "Found", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L158-L164
train
letsencrypt/boulder
probs/probs.go
ServerInternal
func ServerInternal(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: ServerInternalProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusInternalServerError, } }
go
func ServerInternal(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: ServerInternalProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusInternalServerError, } }
[ "func", "ServerInternal", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "ServerInternalProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusInternalServerError", ",", "}", "\n", "}" ]
// ServerInternal returns a ProblemDetails with a ServerInternalProblem and a // 500 Internal Server Failure status code.
[ "ServerInternal", "returns", "a", "ProblemDetails", "with", "a", "ServerInternalProblem", "and", "a", "500", "Internal", "Server", "Failure", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L168-L174
train
letsencrypt/boulder
probs/probs.go
Unauthorized
func Unauthorized(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: UnauthorizedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusForbidden, } }
go
func Unauthorized(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: UnauthorizedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusForbidden, } }
[ "func", "Unauthorized", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "UnauthorizedProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusForbidden", ",", "}", "\n", "}" ]
// Unauthorized returns a ProblemDetails with an UnauthorizedProblem and a 403 // Forbidden status code.
[ "Unauthorized", "returns", "a", "ProblemDetails", "with", "an", "UnauthorizedProblem", "and", "a", "403", "Forbidden", "status", "code", "." ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L178-L184
train
letsencrypt/boulder
probs/probs.go
InvalidContentType
func InvalidContentType(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: MalformedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusUnsupportedMediaType, } }
go
func InvalidContentType(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: MalformedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusUnsupportedMediaType, } }
[ "func", "InvalidContentType", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "MalformedProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusUnsupportedMediaType", ",", "}", "\n", "}" ]
// InvalidContentType returns a ProblemDetails suitable for a missing // ContentType header, or an incorrect ContentType header
[ "InvalidContentType", "returns", "a", "ProblemDetails", "suitable", "for", "a", "missing", "ContentType", "header", "or", "an", "incorrect", "ContentType", "header" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L208-L214
train
letsencrypt/boulder
probs/probs.go
InvalidEmail
func InvalidEmail(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: InvalidEmailProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func InvalidEmail(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: InvalidEmailProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "InvalidEmail", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "InvalidEmailProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// InvalidEmail returns a ProblemDetails representing an invalid email address // error
[ "InvalidEmail", "returns", "a", "ProblemDetails", "representing", "an", "invalid", "email", "address", "error" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L218-L224
train
letsencrypt/boulder
probs/probs.go
ConnectionFailure
func ConnectionFailure(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: ConnectionProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func ConnectionFailure(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: ConnectionProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "ConnectionFailure", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "ConnectionProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// ConnectionFailure returns a ProblemDetails representing a ConnectionProblem // error
[ "ConnectionFailure", "returns", "a", "ProblemDetails", "representing", "a", "ConnectionProblem", "error" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L228-L234
train
letsencrypt/boulder
probs/probs.go
UnknownHost
func UnknownHost(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: UnknownHostProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func UnknownHost(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: UnknownHostProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "UnknownHost", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "UnknownHostProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// UnknownHost returns a ProblemDetails representing an UnknownHostProblem error
[ "UnknownHost", "returns", "a", "ProblemDetails", "representing", "an", "UnknownHostProblem", "error" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L237-L243
train
letsencrypt/boulder
probs/probs.go
RateLimited
func RateLimited(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: RateLimitedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: statusTooManyRequests, } }
go
func RateLimited(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: RateLimitedProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: statusTooManyRequests, } }
[ "func", "RateLimited", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "RateLimitedProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "statusTooManyRequests", ",", "}", "\n", "}" ]
// RateLimited returns a ProblemDetails representing a RateLimitedProblem error
[ "RateLimited", "returns", "a", "ProblemDetails", "representing", "a", "RateLimitedProblem", "error" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L246-L252
train
letsencrypt/boulder
probs/probs.go
TLSError
func TLSError(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: TLSProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func TLSError(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: TLSProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "TLSError", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "TLSProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// TLSError returns a ProblemDetails representing a TLSProblem error
[ "TLSError", "returns", "a", "ProblemDetails", "representing", "a", "TLSProblem", "error" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L255-L261
train
letsencrypt/boulder
probs/probs.go
AccountDoesNotExist
func AccountDoesNotExist(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: AccountDoesNotExistProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func AccountDoesNotExist(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: AccountDoesNotExistProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "AccountDoesNotExist", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "AccountDoesNotExistProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// AccountDoesNotExist returns a ProblemDetails representing an // AccountDoesNotExistProblem error
[ "AccountDoesNotExist", "returns", "a", "ProblemDetails", "representing", "an", "AccountDoesNotExistProblem", "error" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L265-L271
train
letsencrypt/boulder
probs/probs.go
CAA
func CAA(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: CAAProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusForbidden, } }
go
func CAA(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: CAAProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusForbidden, } }
[ "func", "CAA", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "CAAProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusForbidden", ",", "}", "\n", "}" ]
// CAA returns a ProblemDetails representing a CAAProblem
[ "CAA", "returns", "a", "ProblemDetails", "representing", "a", "CAAProblem" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L274-L280
train
letsencrypt/boulder
probs/probs.go
DNS
func DNS(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: DNSProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
go
func DNS(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: DNSProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusBadRequest, } }
[ "func", "DNS", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "DNSProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusBadRequest", ",", "}", "\n", "}" ]
// DNS returns a ProblemDetails representing a DNSProblem
[ "DNS", "returns", "a", "ProblemDetails", "representing", "a", "DNSProblem" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L283-L289
train
letsencrypt/boulder
probs/probs.go
OrderNotReady
func OrderNotReady(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: OrderNotReadyProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusForbidden, } }
go
func OrderNotReady(detail string, a ...interface{}) *ProblemDetails { return &ProblemDetails{ Type: OrderNotReadyProblem, Detail: fmt.Sprintf(detail, a...), HTTPStatus: http.StatusForbidden, } }
[ "func", "OrderNotReady", "(", "detail", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "ProblemDetails", "{", "return", "&", "ProblemDetails", "{", "Type", ":", "OrderNotReadyProblem", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "detail", ",", "a", "...", ")", ",", "HTTPStatus", ":", "http", ".", "StatusForbidden", ",", "}", "\n", "}" ]
// OrderNotReady returns a ProblemDetails representing a OrderNotReadyProblem
[ "OrderNotReady", "returns", "a", "ProblemDetails", "representing", "a", "OrderNotReadyProblem" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/probs/probs.go#L292-L298
train
letsencrypt/boulder
mocks/ca.go
IssueCertificate
func (ca *MockCA) IssueCertificate(ctx context.Context, _ *caPB.IssueCertificateRequest) (core.Certificate, error) { if ca.PEM == nil { return core.Certificate{}, 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 core.Certificate{}, err } return core.Certificate{ DER: cert.Raw, }, nil }
go
func (ca *MockCA) IssueCertificate(ctx context.Context, _ *caPB.IssueCertificateRequest) (core.Certificate, error) { if ca.PEM == nil { return core.Certificate{}, 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 core.Certificate{}, err } return core.Certificate{ DER: cert.Raw, }, nil }
[ "func", "(", "ca", "*", "MockCA", ")", "IssueCertificate", "(", "ctx", "context", ".", "Context", ",", "_", "*", "caPB", ".", "IssueCertificateRequest", ")", "(", "core", ".", "Certificate", ",", "error", ")", "{", "if", "ca", ".", "PEM", "==", "nil", "{", "return", "core", ".", "Certificate", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"MockCA's PEM field must be set before calling IssueCertificate\"", ")", "\n", "}", "\n", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "ca", ".", "PEM", ")", "\n", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "block", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "core", ".", "Certificate", "{", "}", ",", "err", "\n", "}", "\n", "return", "core", ".", "Certificate", "{", "DER", ":", "cert", ".", "Raw", ",", "}", ",", "nil", "\n", "}" ]
// IssueCertificate is a mock
[ "IssueCertificate", "is", "a", "mock" ]
a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf
https://github.com/letsencrypt/boulder/blob/a3d35f51ff716e0d4916ac2c8ce5b6df16a95baf/mocks/ca.go#L22-L34
train
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", "(", "\"MockCA's PEM field must be set before calling IssueCertificate\"", ")", "\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", ",", "\"tcp\"", ",", "hostPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "deadline", ",", "ok", ":=", "ctx", ".", "Deadline", "(", ")", "\n", "if", "!", "ok", "{", "va", ".", "log", ".", "AuditErr", "(", "\"tlsDial was called without a deadline\"", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"tlsDial was called without a deadline\"", ")", "\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", "if", "features", ".", "Enabled", "(", "features", ".", "CAAAccountURI", ")", "&&", "len", "(", "accountURIPrefixes", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"no account URI prefixes configured\"", ")", "\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", ":", "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", "{", "if", "urlErr", ",", "ok", ":=", "err", ".", "(", "*", "url", ".", "Error", ")", ";", "ok", "{", "prob", ":=", "detailedError", "(", "urlErr", ".", "Err", ")", "\n", "prob", ".", "Detail", "=", "fmt", ".", "Sprintf", "(", "\"Fetching %s: %s\"", ",", "urlErr", ".", "URL", ",", "prob", ".", "Detail", ")", "\n", "return", "prob", "\n", "}", "\n", "if", "tlsErr", ",", "ok", ":=", "err", ".", "(", "tls", ".", "RecordHeaderError", ")", ";", "ok", "&&", "bytes", ".", "Compare", "(", "tlsErr", ".", "RecordHeader", "[", ":", "]", ",", "badTLSHeader", ")", "==", "0", "{", "return", "probs", ".", "Malformed", "(", "\"Server only speaks HTTP, not TLS\"", ")", "\n", "}", "\n", "if", "netErr", ",", "ok", ":=", "err", ".", "(", "*", "net", ".", "OpError", ")", ";", "ok", "{", "if", "fmt", ".", "Sprintf", "(", "\"%T\"", ",", "netErr", ".", "Err", ")", "==", "\"tls.alert\"", "{", "return", "probs", ".", "TLSError", "(", "netErr", ".", "Error", "(", ")", ")", "\n", "}", "else", "if", "syscallErr", ",", "ok", ":=", "netErr", ".", "Err", ".", "(", "*", "os", ".", "SyscallError", ")", ";", "ok", "&&", "syscallErr", ".", "Err", "==", "syscall", ".", "ECONNREFUSED", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"Connection refused\"", ")", "\n", "}", "else", "if", "syscallErr", ",", "ok", ":=", "netErr", ".", "Err", ".", "(", "*", "os", ".", "SyscallError", ")", ";", "ok", "&&", "syscallErr", ".", "Err", "==", "syscall", ".", "ENETUNREACH", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"Network unreachable\"", ")", "\n", "}", "else", "if", "syscallErr", ",", "ok", ":=", "netErr", ".", "Err", ".", "(", "*", "os", ".", "SyscallError", ")", ";", "ok", "&&", "syscallErr", ".", "Err", "==", "syscall", ".", "ECONNRESET", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"Connection reset by peer\"", ")", "\n", "}", "else", "if", "netErr", ".", "Timeout", "(", ")", "&&", "netErr", ".", "Op", "==", "\"dial\"", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"Timeout during connect (likely firewall problem)\"", ")", "\n", "}", "else", "if", "netErr", ".", "Timeout", "(", ")", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"Timeout during %s (your server may be slow or overloaded)\"", ",", "netErr", ".", "Op", ")", "\n", "}", "\n", "}", "\n", "if", "err", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", ";", "ok", "&&", "err", ".", "Timeout", "(", ")", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"Timeout after connect (your server may be slow or overloaded)\"", ")", "\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", "if", "h2SettingsFrameErrRegex", ".", "MatchString", "(", "err", ".", "Error", "(", ")", ")", "{", "return", "probs", ".", "ConnectionFailure", "(", "\"Server is speaking HTTP/2 over HTTP\"", ")", "\n", "}", "\n", "return", "probs", ".", "ConnectionFailure", "(", "\"Error getting validation data\"", ")", "\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", ")", "{", "baseIdentifier", ":=", "identifier", "\n", "if", "strings", ".", "HasPrefix", "(", "identifier", ".", "Value", ",", "\"*.\"", ")", "{", "baseIdentifier", ".", "Value", "=", "strings", ".", "TrimPrefix", "(", "identifier", ".", "Value", ",", "\"*.\"", ")", "\n", "}", "\n", "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", "validationRecords", ",", "err", ":=", "va", ".", "validateChallenge", "(", "ctx", ",", "baseIdentifier", ",", "challenge", ")", "\n", "if", "err", "!=", "nil", "{", "return", "validationRecords", ",", "err", "\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", ":=", "\"failure\"", "\n", "start", ":=", "va", ".", "clk", ".", "Now", "(", ")", "\n", "defer", "func", "(", ")", "{", "va", ".", "metrics", ".", "remoteValidationTime", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"type\"", ":", "challengeType", ",", "\"result\"", ":", "state", ",", "}", ")", ".", "Observe", "(", "va", ".", "clk", ".", "Since", "(", "start", ")", ".", "Seconds", "(", ")", ")", "\n", "}", "(", ")", "\n", "required", ":=", "numRemoteVAs", "-", "va", ".", "maxRemoteFailures", "\n", "good", ":=", "0", "\n", "bad", ":=", "0", "\n", "var", "remoteProbs", "[", "]", "*", "probs", ".", "ProblemDetails", "\n", "var", "firstProb", "*", "probs", ".", "ProblemDetails", "\n", "for", "prob", ":=", "range", "remoteErrors", "{", "remoteProbs", "=", "append", "(", "remoteProbs", ",", "prob", ")", "\n", "if", "prob", "==", "nil", "{", "good", "++", "\n", "}", "else", "{", "bad", "++", "\n", "}", "\n", "if", "firstProb", "==", "nil", "&&", "prob", "!=", "nil", "{", "firstProb", "=", "prob", "\n", "}", "\n", "if", "!", "features", ".", "Enabled", "(", "features", ".", "MultiVAFullResults", ")", "{", "if", "good", ">=", "required", "{", "state", "=", "\"success\"", "\n", "return", "nil", "\n", "}", "else", "if", "bad", ">", "va", ".", "maxRemoteFailures", "{", "return", "prob", "\n", "}", "\n", "}", "\n", "if", "len", "(", "remoteProbs", ")", "==", "numRemoteVAs", "{", "break", "\n", "}", "\n", "}", "\n", "va", ".", "logRemoteValidationDifferentials", "(", "domain", ",", "primaryResult", ",", "remoteProbs", ")", "\n", "if", "good", ">=", "required", "{", "state", "=", "\"success\"", "\n", "return", "nil", "\n", "}", "else", "if", "bad", ">", "va", ".", "maxRemoteFailures", "{", "return", "firstProb", "\n", "}", "\n", "return", "probs", ".", "ServerInternal", "(", "\"Too few remote PerformValidation RPC results\"", ")", "\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", "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", "{", "return", "\n", "}", "\n", "if", "primaryResult", "==", "nil", "&&", "len", "(", "failures", ")", ">", "va", ".", "maxRemoteFailures", "{", "va", ".", "metrics", ".", "prospectiveRemoteValidationFailures", ".", "Inc", "(", ")", "\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", "logJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "logOb", ")", "\n", "if", "err", "!=", "nil", "{", "va", ".", "log", ".", "Warningf", "(", "\"Could not marshal log object in \"", "+", "\"logRemoteValidationDifferentials: %s\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "va", ".", "log", ".", "Infof", "(", "\"remoteVADifferentials JSON=%s\"", ",", "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", "(", "\"CertificateChain entry for AIA issuer url %q has an \"", "+", "\"invalid chain file: %q - error reading contents: %s\"", ",", "aiaIssuerURL", ",", "certFile", ",", "err", ")", "\n", "}", "\n", "if", "bytes", ".", "Contains", "(", "pemBytes", ",", "[", "]", "byte", "(", "\"\\r\\n\"", ")", ")", "\\r", "\n", "\\n", "\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", ")", "\n", "}", "\n", "certBlock", ",", "rest", ":=", "pem", ".", "Decode", "(", "pemBytes", ")", "\n", "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", ")", "\n", "}", "\n", "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", ")", "\n", "}", "\n", "certFile", "\n", "certBlock", ".", "Type", "\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", "for", "aiaIssuerURL", ",", "certFiles", ":=", "range", "chainConfig", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "if", "len", "(", "certFiles", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"CertificateChain entry for AIA issuer url %q has no chain \"", "+", "\"file names configured\"", ",", "aiaIssuerURL", ")", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "certFiles", "{", "buffer", ".", "Write", "(", "[", "]", "byte", "(", "\"\\n\"", ")", ")", "\n", "\\n", "\n", "pemBytes", ",", "err", ":=", "loadCertificateFile", "(", "aiaIssuerURL", ",", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "buffer", ".", "Write", "(", "pemBytes", ")", "\n", "}", "\n", "results", "[", "aiaIssuerURL", "]", "=", "buffer", ".", "Bytes", "(", ")", "\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", ",", "\"SubmitToSingleCTWithResult\"", ",", "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", ",", "\"SubmitToSingleCTWithResult\"", ",", "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", "ssa", ":=", "&", "SQLStorageAuthority", "{", "dbMap", ":", "dbMap", ",", "clk", ":", "clk", ",", "log", ":", "logger", ",", "parallelismPerRPC", ":", "parallelismPerRPC", ",", "}", "\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", "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", "=", "\"WHERE id = ?\"", "\n", "model", ",", "err", ":=", "selectRegistration", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "query", ",", "id", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "core", ".", "Registration", "{", "}", ",", "berrors", ".", "NotFoundError", "(", "\"registration with ID '%d' not found\"", ",", "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", "=", "\"WHERE jwk_sha256 = ?\"", "\n", "if", "key", "==", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"key argument to GetRegistrationByKey must not be nil\"", ")", "\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", "(", "\"no registrations with public key sha256 %q\"", ",", "sha", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "core", ".", "Registration", "{", "}", ",", "err", "\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", "pa", ",", "err", ":=", "selectPendingAuthz", "(", "txWithCtx", ",", "\"WHERE id = ?\"", ",", "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", "(", "\"SELECT %s FROM authz WHERE id = ?\"", ",", "authzFields", ")", ",", "id", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "sql", ".", "ErrNoRows", "{", "return", "authz", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "else", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "authz", ",", "Rollback", "(", "tx", ",", "berrors", ".", "NotFoundError", "(", "\"no authorization found with id %q\"", ",", "id", ")", ")", "\n", "}", "\n", "authz", "=", "fa", ".", "Authorization", "\n", "}", "else", "{", "authz", "=", "pa", ".", "Authorization", "\n", "}", "\n", "authz", ".", "Challenges", ",", "err", "=", "ssa", ".", "getChallenges", "(", "txWithCtx", ",", "authz", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "authz", ",", "Rollback", "(", "tx", ",", "err", ")", "\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", "resultBytes", ":=", "bigInt", ".", "Bytes", "(", ")", "\n", "if", "len", "(", "resultBytes", ")", ">", "16", "{", "return", "net", ".", "ParseIP", "(", "\"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff\"", ")", "\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\t\t WHERE\t\t initialIP = :ip AND\t\t :earliest < createdAt AND\t\t createdAt <= :latest`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"ip\"", ":", "[", "]", "byte", "(", "ip", ")", ",", "\"earliest\"", ":", "earliest", ",", "\"latest\"", ":", "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", "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", "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", "{", "}", "{", "\"reversedDomain\"", ":", "ReverseName", "(", "domain", ")", ",", "\"earliest\"", ":", "earliest", ",", "\"latest\"", ":", "latest", ",", "}", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "0", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "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", "(", "\"Invalid certificate serial %s\"", ",", "serial", ")", "\n", "return", "core", ".", "Certificate", "{", "}", ",", "err", "\n", "}", "\n", "cert", ",", "err", ":=", "SelectCertificate", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "\"WHERE serial = ?\"", ",", "serial", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "core", ".", "Certificate", "{", "}", ",", "berrors", ".", "NotFoundError", "(", "\"certificate with serial %q not found\"", ",", "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", "(", "\"Invalid certificate serial %s\"", ",", "serial", ")", "\n", "return", "core", ".", "CertificateStatus", "{", "}", ",", "err", "\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", "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", "=", "\"WHERE id = ?\"", "\n", "model", ",", "err", ":=", "selectRegistration", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "query", ",", "reg", ".", "ID", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "berrors", ".", "NotFoundError", "(", "\"registration with ID '%d' not found\"", ",", "reg", ".", "ID", ")", "\n", "}", "\n", "updatedRegModel", ",", "err", ":=", "registrationToModel", "(", "&", "reg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "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", "(", "\"registration with ID '%d' not found\"", ",", "reg", ".", "ID", ")", "\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", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "output", ",", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n", "authz", ".", "ID", "=", "core", ".", "NewToken", "(", ")", "\n", "for", "existingPending", "(", "txWithCtx", ",", "authz", ".", "ID", ")", "||", "existingFinal", "(", "txWithCtx", ",", "authz", ".", "ID", ")", "{", "authz", ".", "ID", "=", "core", ".", "NewToken", "(", ")", "\n", "}", "\n", "pendingAuthz", ":=", "pendingauthzModel", "{", "Authorization", ":", "authz", "}", "\n", "err", "=", "txWithCtx", ".", "Insert", "(", "&", "pendingAuthz", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "Rollback", "(", "tx", ",", "err", ")", "\n", "return", "output", ",", "err", "\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", "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", "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", "pa", ",", "err", ":=", "selectPendingAuthz", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "`WHERE registrationID = :regID\t\t\t AND identifier = :identifierJSON\t\t\t AND status = :status\t\t\t AND expires > :validUntil\t\t ORDER BY expires ASC\t\t LIMIT 1`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"regID\"", ":", "*", "req", ".", "RegistrationID", ",", "\"identifierJSON\"", ":", "identifierJSON", ",", "\"status\"", ":", "string", "(", "core", ".", "StatusPending", ")", ",", "\"validUntil\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "ValidUntil", ")", ",", "}", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "nil", ",", "berrors", ".", "NotFoundError", "(", "\"pending authz not found\"", ")", "\n", "}", "else", "if", "err", "==", "nil", "{", "authz", ",", "err", ":=", "ssa", ".", "GetAuthorization", "(", "ctx", ",", "pa", ".", "ID", ")", "\n", "return", "&", "authz", ",", "err", "\n", "}", "else", "{", "return", "nil", ",", "err", "\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", "if", "!", "existingPending", "(", "txWithCtx", ",", "authz", ".", "ID", ")", "{", "err", "=", "berrors", ".", "NotFoundError", "(", "\"authorization with ID %q not found\"", ",", "authz", ".", "ID", ")", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "if", "statusIsPending", "(", "authz", ".", "Status", ")", "{", "err", "=", "berrors", ".", "InternalServerError", "(", "\"authorization to finalize is pending (ID %q)\"", ",", "authz", ".", "ID", ")", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "auth", ":=", "&", "authzModel", "{", "authz", "}", "\n", "pa", ",", "err", ":=", "selectPendingAuthz", "(", "txWithCtx", ",", "\"WHERE id = ?\"", ",", "authz", ".", "ID", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "Rollback", "(", "tx", ",", "berrors", ".", "NotFoundError", "(", "\"authorization with ID %q not found\"", ",", "authz", ".", "ID", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "err", "=", "txWithCtx", ".", "Insert", "(", "auth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "txWithCtx", ".", "Delete", "(", "pa", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "err", "=", "updateChallenges", "(", "txWithCtx", ",", "authz", ".", "ID", ",", "authz", ".", "Challenges", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\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", "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", "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", "(", "\"Didn't revoke all found authorizations\"", ")", "\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", "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", "revokedTotal", "==", "0", "{", "return", "nil", ",", "berrors", ".", "NotFoundError", "(", "\"no authorizations to revoke for %q\"", ",", "*", "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", "cert", ":=", "&", "core", ".", "Certificate", "{", "RegistrationID", ":", "regID", ",", "Serial", ":", "serial", ",", "Digest", ":", "digest", ",", "DER", ":", "certDER", ",", "Issued", ":", "*", "issued", ",", "Expires", ":", "parsedCertificate", ".", "NotAfter", ",", "}", "\n", "certStatus", ":=", "&", "certStatusModel", "{", "Status", ":", "core", ".", "OCSPStatus", "(", "\"good\"", ")", ",", "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", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n", "err", "=", "txWithCtx", ".", "Insert", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "if", "strings", ".", "HasPrefix", "(", "err", ".", "Error", "(", ")", ",", "\"Error 1062: Duplicate entry\"", ")", "{", "err", "=", "berrors", ".", "DuplicateError", "(", "\"cannot add a duplicate cert\"", ")", "\n", "}", "\n", "return", "\"\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "err", "=", "txWithCtx", ".", "Insert", "(", "certStatus", ")", "\n", "if", "err", "!=", "nil", "{", "if", "strings", ".", "HasPrefix", "(", "err", ".", "Error", "(", ")", ",", "\"Error 1062: Duplicate entry\"", ")", "{", "err", "=", "berrors", ".", "DuplicateError", "(", "\"cannot add a duplicate cert status\"", ")", "\n", "}", "\n", "return", "\"\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "isRenewal", ",", "err", ":=", "ssa", ".", "checkFQDNSetExists", "(", "txWithCtx", ".", "SelectOne", ",", "parsedCertificate", ".", "DNSNames", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "err", "=", "addIssuedNames", "(", "txWithCtx", ",", "parsedCertificate", ",", "isRenewal", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "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", "err", "=", "addFQDNSet", "(", "txWithCtx", ",", "parsedCertificate", ".", "DNSNames", ",", "serial", ",", "parsedCertificate", ".", "NotBefore", ",", "parsedCertificate", ".", "NotAfter", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "Rollback", "(", "tx", ",", "err", ")", "\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\t\tWHERE registrationID = :regID AND\t\texpires > :now AND\t\tstatus = :pending`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"regID\"", ":", "regID", ",", "\"now\"", ":", "ssa", ".", "clk", ".", "Now", "(", ")", ",", "\"pending\"", ":", "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", "idJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "identifier", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "count", "=", "&", "sapb", ".", "Count", "{", "Count", ":", "new", "(", "int64", ")", ",", "}", "\n", "err", "=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "SelectOne", "(", "count", ".", "Count", ",", "`SELECT COUNT(1) FROM authz\t\tWHERE registrationID = :regID AND\t\tidentifier = :identifier AND\t\texpires > :earliest AND\t\texpires <= :latest AND\t\tstatus = :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", ")", ",", "}", ")", "\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", "(", "`\t DELETE FROM orderFqdnSets\t\tWHERE orderID = ?`", ",", "orderID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "rowsDeleted", ",", "err", ":=", "result", ".", "RowsAffected", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "rowsDeleted", "==", "0", "{", "return", "berrors", ".", "InternalServerError", "(", "\"No orderFQDNSet exists to delete\"", ")", "\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\t\tWHERE setHash = ?\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", "if", "len", "(", "serials", ")", "==", "0", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"getFQDNSetsBySerials called with no serials\"", ")", "\n", "ssa", ".", "log", ".", "AuditErr", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "nil", ",", "err", "\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", ":=", "\"SELECT setHash FROM fqdnSets \"", "+", "\"WHERE serial IN (\"", "+", "strings", ".", "Join", "(", "qmarks", ",", "\",\"", ")", "+", "\")\"", "\n", "_", ",", "err", ":=", "db", ".", "Select", "(", "&", "fqdnSets", ",", "query", ",", "params", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"getFQDNSetsBySerials returned no rows - internal consistency violation\"", ")", "\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\t\tWHERE setHash = ?\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", "(", "\"UPDATE registrations SET status = ? WHERE status = ? AND id = ?\"", ",", "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", "if", "existingPending", "(", "txWithCtx", ",", "id", ")", "{", "authzObj", ",", "err", ":=", "txWithCtx", ".", "Get", "(", "&", "pendingauthzModel", "{", "}", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "if", "authzObj", "==", "nil", "{", "return", "Rollback", "(", "tx", ",", "berrors", ".", "InternalServerError", "(", "\"failure retrieving pending authorization\"", ")", ")", "\n", "}", "\n", "authz", ":=", "authzObj", ".", "(", "*", "pendingauthzModel", ")", "\n", "if", "authz", ".", "Status", "!=", "core", ".", "StatusPending", "{", "return", "Rollback", "(", "tx", ",", "berrors", ".", "WrongAuthorizationStateError", "(", "\"authorization not pending\"", ")", ")", "\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", "(", "\"wrong number of rows deleted: expected 1, got %d\"", ",", "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", "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", "{", "}", "{", "\"deactivated\"", ":", "statusUint", "(", "core", ".", "StatusDeactivated", ")", ",", "\"id\"", ":", "*", "req", ".", "Id", ",", "\"valid\"", ":", "statusUint", "(", "core", ".", "StatusValid", ")", ",", "\"pending\"", ":", "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", "tx", ",", "err", ":=", "ssa", ".", "dbMap", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "txWithCtx", ":=", "tx", ".", "WithContext", "(", "ctx", ")", "\n", "if", "err", ":=", "txWithCtx", ".", "Insert", "(", "order", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "Rollback", "(", "tx", ",", "err", ")", "\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", "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", "if", "err", ":=", "addOrderFQDNSet", "(", "txWithCtx", ",", "req", ".", "Names", ",", "order", ".", "ID", ",", "order", ".", "RegistrationID", ",", "order", ".", "Expires", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "tx", ".", "Commit", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Id", "=", "&", "order", ".", "ID", "\n", "createdTS", ":=", "order", ".", "Created", ".", "UnixNano", "(", ")", "\n", "req", ".", "Created", "=", "&", "createdTS", "\n", "processingStatus", ":=", "false", "\n", "req", ".", "BeganProcessing", "=", "&", "processingStatus", "\n", "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", "om", ",", "err", ":=", "orderToModel", "(", "order", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "result", ",", "err", ":=", "txWithCtx", ".", "Exec", "(", "`\t\tUPDATE orders\t\tSET error = ?\t\tWHERE id = ?`", ",", "om", ".", "Error", ",", "om", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "berrors", ".", "InternalServerError", "(", "\"error updating order error field\"", ")", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "n", ",", "err", ":=", "result", ".", "RowsAffected", "(", ")", "\n", "if", "err", "!=", "nil", "||", "n", "==", "0", "{", "err", "=", "berrors", ".", "InternalServerError", "(", "\"no order updated with new error field\"", ")", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\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", "(", "\"no order found for ID %d\"", ",", "*", "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", "names", ",", "err", ":=", "ssa", ".", "namesForOrder", "(", "ctx", ",", "*", "order", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "reversedNames", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "names", ")", ")", "\n", "for", "i", ",", "n", ":=", "range", "names", "{", "reversedNames", "[", "i", "]", "=", "ReverseName", "(", "n", ")", "\n", "}", "\n", "order", ".", "Names", "=", "reversedNames", "\n", "status", ",", "err", ":=", "ssa", ".", "statusForOrder", "(", "ctx", ",", "order", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "order", ".", "Status", "=", "&", "status", "\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", "var", "auths", "[", "]", "*", "core", ".", "Authorization", "\n", "_", ",", "err", ":=", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ".", "Select", "(", "&", "auths", ",", "fmt", ".", "Sprintf", "(", "`SELECT %s FROM %s AS authz\tLEFT JOIN orderToAuthz\tON authz.ID = orderToAuthz.authzID\tWHERE authz.registrationID = ? AND\tauthz.expires > ? AND\tauthz.status = ? AND\torderToAuthz.orderID = ?`", ",", "authzFields", ",", "authorizationTable", ")", ",", "*", "req", ".", "AcctID", ",", "now", ",", "string", "(", "core", ".", "StatusValid", ")", ",", "*", "req", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "byName", ":=", "make", "(", "map", "[", "string", "]", "*", "core", ".", "Authorization", ")", "\n", "for", "_", ",", "auth", ":=", "range", "auths", "{", "if", "auth", ".", "Identifier", ".", "Type", "!=", "core", ".", "IdentifierDNS", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"unknown identifier type: %q on authz id %q\"", ",", "auth", ".", "Identifier", ".", "Type", ",", "auth", ".", "ID", ")", "\n", "}", "\n", "existing", ",", "present", ":=", "byName", "[", "auth", ".", "Identifier", ".", "Value", "]", "\n", "if", "!", "present", "||", "auth", ".", "Expires", ".", "After", "(", "*", "existing", ".", "Expires", ")", "{", "auth", ".", "Challenges", ",", "err", "=", "ssa", ".", "getChallenges", "(", "ssa", ".", "dbMap", ".", "WithContext", "(", "ctx", ")", ",", "auth", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\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", "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", "for", "name", ",", "a", ":=", "range", "pendingAuthz", "{", "authzMap", "[", "name", "]", "=", "a", "\n", "}", "\n", "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", "(", "\"authorization must be pending\"", ")", "\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", "(", "\"authorization %d not found\"", ",", "*", "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", "{", "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", "(", "\"authorization must have status valid or invalid\"", ")", "\n", "}", "\n", "query", ":=", "`UPDATE authz2 SET\t\tstatus = :status,\t\tattempted = :attempted,\t\tvalidationRecord = :validationRecord,\t\tvalidationError = :validationError,\t\texpires = :expires\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", "{", "}", "{", "\"status\"", ":", "statusToUint", "[", "*", "req", ".", "Status", "]", ",", "\"attempted\"", ":", "challTypeToUint", "[", "*", "req", ".", "Attempted", "]", ",", "\"validationRecord\"", ":", "vrJSON", ",", "\"id\"", ":", "*", "req", ".", "Id", ",", "\"pending\"", ":", "statusUint", "(", "core", ".", "StatusPending", ")", ",", "\"expires\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "Expires", ")", ".", "UTC", "(", ")", ",", "\"validationError\"", ":", "veJSON", ",", "}", "\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", "(", "\"authorization with id %d not found\"", ",", "*", "req", ".", "Id", ")", "\n", "}", "else", "if", "rows", ">", "1", "{", "return", "berrors", ".", "InternalServerError", "(", "\"multiple rows updated for authorization id %d\"", ",", "*", "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", "status", ",", "err", ":=", "SelectCertificateStatus", "(", "txWithCtx", ",", "\"WHERE serial = ? AND status != ?\"", ",", "*", "req", ".", "Serial", ",", "string", "(", "core", ".", "OCSPStatusRevoked", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "Rollback", "(", "tx", ",", "berrors", ".", "InternalServerError", "(", "\"no certificate with serial %s and status %s\"", ",", "*", "req", ".", "Serial", ",", "string", "(", "core", ".", "OCSPStatusRevoked", ")", ")", ")", "\n", "}", "\n", "return", "Rollback", "(", "tx", ",", "err", ")", "\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", ",", "err", ":=", "txWithCtx", ".", "Update", "(", "&", "status", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "if", "n", "==", "0", "{", "return", "Rollback", "(", "tx", ",", "berrors", ".", "InternalServerError", "(", "\"no certificate updated\"", ")", ")", "\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\t\t\tregistrationID = :regID AND\t\t\tidentifierValue = :ident AND\t\t\tstatus = :status AND\t\t\texpires > :validUntil\t\t\tORDER BY expires ASC\t\t\tLIMIT 1 `", ",", "authz2Fields", ")", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"regID\"", ":", "*", "req", ".", "RegistrationID", ",", "\"ident\"", ":", "*", "req", ".", "IdentifierValue", ",", "\"status\"", ":", "statusUint", "(", "core", ".", "StatusPending", ")", ",", "\"validUntil\"", ":", "time", ".", "Unix", "(", "0", ",", "*", "req", ".", "ValidUntil", ")", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "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\t\tregistrationID = :regID AND\t\texpires > :expires AND\t\tstatus = :status`", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"regID\"", ":", "*", "req", ".", "Id", ",", "\"expires\"", ":", "ssa", ".", "clk", ".", "Now", "(", ")", ",", "\"status\"", ":", "statusUint", "(", "core", ".", "StatusPending", ")", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "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\t\t\tLEFT JOIN orderToAuthz2 ON authz2.ID = orderToAuthz2.authzID\t\t\tWHERE authz2.registrationID = :regID AND\t\t\tauthz2.expires > :expires AND\t\t\tauthz2.status = :status AND\t\t\torderToAuthz2.orderID = :orderID`", ",", "authz2Fields", ",", ")", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"regID\"", ":", "*", "req", ".", "AcctID", ",", "\"expires\"", ":", "ssa", ".", "clk", ".", "Now", "(", ")", ",", "\"status\"", ":", "statusUint", "(", "core", ".", "StatusValid", ")", ",", "\"orderID\"", ":", "*", "req", ".", "Id", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "byName", ":=", "make", "(", "map", "[", "string", "]", "authz2Model", ")", "\n", "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", ")", "\n", "}", "\n", "existing", ",", "present", ":=", "byName", "[", "am", ".", "IdentifierValue", "]", "\n", "if", "!", "present", "||", "am", ".", "Expires", ".", "After", "(", "existing", ".", "Expires", ")", "{", "byName", "[", "am", ".", "IdentifierValue", "]", "=", "am", "\n", "}", "\n", "}", "\n", "authzsPB", ",", "err", ":=", "authz2ModelMapToPB", "(", "byName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "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", "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\t\tregistrationID = :regID AND\t\tidentifierValue = :ident AND\t\texpires > :expiresEarliest AND\t\texpires <= :expiresLatest AND\t\tstatus = :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", ")", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "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\t\t\tregistrationID = ? AND\t\t\texpires > ? AND\t\t\tstatus = ? AND\t\t\tidentifierValue IN (%s)`", ",", "authz2Fields", ",", "strings", ".", "Join", "(", "qmarks", ",", "\",\"", ")", ",", ")", ",", "params", "...", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "authzMap", ":=", "make", "(", "map", "[", "string", "]", "authz2Model", ",", "len", "(", "authzModels", ")", ")", "\n", "for", "_", ",", "am", ":=", "range", "authzModels", "{", "if", "uintToIdentifierType", "[", "am", ".", "IdentifierType", "]", "!=", "string", "(", "core", ".", "IdentifierDNS", ")", "{", "continue", "\n", "}", "\n", "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", "if", "len", "(", "authzsPB", ".", "Authz", ")", "!=", "len", "(", "req", ".", "Domains", ")", "{", "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", "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", "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", "pemPK", ":=", "fmt", ".", "Sprintf", "(", "\"-----BEGIN PUBLIC KEY-----\\n%s\\n-----END PUBLIC KEY-----\"", ",", "\\n", ")", "\n", "\\n", "\n", "b64PK", "\n", "opts", ":=", "jsonclient", ".", "Options", "{", "Logger", ":", "logAdaptor", "{", "logger", "}", ",", "PublicKey", ":", "pemPK", ",", "}", "\n", "httpClient", ":=", "&", "http", ".", "Client", "{", "Timeout", ":", "time", ".", "Minute", "*", "2", "+", "time", ".", "Second", "*", "30", ",", "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", "(", "\"making CT client: %s\"", ",", "err", ")", "\n", "}", "\n", "pkBytes", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "b64PK", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Failed to decode base64 log public key\"", ")", "\n", "}", "\n", "pk", ",", "err", ":=", "x509", ".", "ParsePKIXPublicKey", "(", "pkBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Failed to parse log public key\"", ")", "\n", "}", "\n", "verifier", ",", "err", ":=", "ct", ".", "NewSignatureVerifier", "(", "pk", ")", "\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", "(", "\"failed to parse log URI: %s\"", ",", "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", "=", "\"error\"", "\n", "}", "\n", "pub", ".", "metrics", ".", "probeLatency", ".", "With", "(", "prometheus", ".", "Labels", "{", "\"log\"", ":", "uri", ",", "\"status\"", ":", "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", "(", "\"invalid public key in CSR: %s\"", ",", "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", "(", "\"CN was longer than %d bytes\"", ",", "maxCNLength", ")", "\n", "}", "\n", "if", "len", "(", "csr", ".", "DNSNames", ")", ">", "maxNames", "{", "return", "fmt", ".", "Errorf", "(", "\"CSR contains more than %d DNS names\"", ",", "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", "(", "\"%q\"", ",", "name", ")", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "badNames", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"policy forbids issuing for: %s\"", ",", "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", "for", "_", ",", "prime", ":=", "range", "smallPrimes", "{", "var", "result", "big", ".", "Int", "\n", "result", ".", "Mod", "(", "i", ",", "prime", ")", "\n", "if", "result", ".", "Sign", "(", ")", "==", "0", "{", "return", "true", "\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", ",", "\"MustRegister\"", ",", "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