4
0

order.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. package acme
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/subtle"
  6. "crypto/x509"
  7. "encoding/asn1"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "net"
  12. "net/url"
  13. "sort"
  14. "strings"
  15. "time"
  16. "go.step.sm/crypto/keyutil"
  17. "go.step.sm/crypto/x509util"
  18. "github.com/smallstep/certificates/acme/wire"
  19. "github.com/smallstep/certificates/authority/provisioner"
  20. "github.com/smallstep/certificates/webhook"
  21. )
  22. type IdentifierType string
  23. const (
  24. // IP is the ACME ip identifier type
  25. IP IdentifierType = "ip"
  26. // DNS is the ACME dns identifier type
  27. DNS IdentifierType = "dns"
  28. // PermanentIdentifier is the ACME permanent-identifier identifier type
  29. // defined in https://datatracker.ietf.org/doc/html/draft-bweeks-acme-device-attest-00
  30. PermanentIdentifier IdentifierType = "permanent-identifier"
  31. // WireUser is the Wire user identifier type
  32. WireUser IdentifierType = "wireapp-user"
  33. // WireDevice is the Wire device identifier type
  34. WireDevice IdentifierType = "wireapp-device"
  35. )
  36. // Identifier encodes the type that an order pertains to.
  37. type Identifier struct {
  38. Type IdentifierType `json:"type"`
  39. Value string `json:"value"`
  40. }
  41. // Order contains order metadata for the ACME protocol order type.
  42. type Order struct {
  43. ID string `json:"id"`
  44. AccountID string `json:"-"`
  45. ProvisionerID string `json:"-"`
  46. Status Status `json:"status"`
  47. ExpiresAt time.Time `json:"expires"`
  48. Identifiers []Identifier `json:"identifiers"`
  49. NotBefore time.Time `json:"notBefore"`
  50. NotAfter time.Time `json:"notAfter"`
  51. Error *Error `json:"error,omitempty"`
  52. AuthorizationIDs []string `json:"-"`
  53. AuthorizationURLs []string `json:"authorizations"`
  54. FinalizeURL string `json:"finalize"`
  55. CertificateID string `json:"-"`
  56. CertificateURL string `json:"certificate,omitempty"`
  57. }
  58. // ToLog enables response logging.
  59. func (o *Order) ToLog() (interface{}, error) {
  60. b, err := json.Marshal(o)
  61. if err != nil {
  62. return nil, WrapErrorISE(err, "error marshaling order for logging")
  63. }
  64. return string(b), nil
  65. }
  66. // UpdateStatus updates the ACME Order Status if necessary.
  67. // Changes to the order are saved using the database interface.
  68. func (o *Order) UpdateStatus(ctx context.Context, db DB) error {
  69. now := clock.Now()
  70. switch o.Status {
  71. case StatusInvalid:
  72. return nil
  73. case StatusValid:
  74. return nil
  75. case StatusReady:
  76. // Check expiry
  77. if now.After(o.ExpiresAt) {
  78. o.Status = StatusInvalid
  79. o.Error = NewError(ErrorMalformedType, "order has expired")
  80. break
  81. }
  82. return nil
  83. case StatusPending:
  84. // Check expiry
  85. if now.After(o.ExpiresAt) {
  86. o.Status = StatusInvalid
  87. o.Error = NewError(ErrorMalformedType, "order has expired")
  88. break
  89. }
  90. var count = map[Status]int{
  91. StatusValid: 0,
  92. StatusInvalid: 0,
  93. StatusPending: 0,
  94. }
  95. for _, azID := range o.AuthorizationIDs {
  96. az, err := db.GetAuthorization(ctx, azID)
  97. if err != nil {
  98. return WrapErrorISE(err, "error getting authorization ID %s", azID)
  99. }
  100. if err = az.UpdateStatus(ctx, db); err != nil {
  101. return WrapErrorISE(err, "error updating authorization ID %s", azID)
  102. }
  103. st := az.Status
  104. count[st]++
  105. }
  106. switch {
  107. case count[StatusInvalid] > 0:
  108. o.Status = StatusInvalid
  109. // No change in the order status, so just return the order as is -
  110. // without writing any changes.
  111. case count[StatusPending] > 0:
  112. return nil
  113. case count[StatusValid] == len(o.AuthorizationIDs):
  114. o.Status = StatusReady
  115. default:
  116. return NewErrorISE("unexpected authz status")
  117. }
  118. default:
  119. return NewErrorISE("unrecognized order status: %s", o.Status)
  120. }
  121. if err := db.UpdateOrder(ctx, o); err != nil {
  122. return WrapErrorISE(err, "error updating order")
  123. }
  124. return nil
  125. }
  126. // getAuthorizationFingerprint returns a fingerprint from the list of authorizations. This
  127. // fingerprint is used on the device-attest-01 flow to verify the attestation
  128. // certificate public key with the CSR public key.
  129. //
  130. // There's no point on reading all the authorizations as there will be only one
  131. // for a permanent identifier.
  132. func (o *Order) getAuthorizationFingerprint(ctx context.Context, db DB) (string, error) {
  133. for _, azID := range o.AuthorizationIDs {
  134. az, err := db.GetAuthorization(ctx, azID)
  135. if err != nil {
  136. return "", WrapErrorISE(err, "error getting authorization %q", azID)
  137. }
  138. // There's no point on reading all the authorizations as there will
  139. // be only one for a permanent identifier.
  140. if az.Fingerprint != "" {
  141. return az.Fingerprint, nil
  142. }
  143. }
  144. return "", nil
  145. }
  146. // Finalize signs a certificate if the necessary conditions for Order completion
  147. // have been met.
  148. //
  149. // TODO(mariano): Here or in the challenge validation we should perform some
  150. // external validation using the identifier value and the attestation data. From
  151. // a validation service we can get the list of SANs to set in the final
  152. // certificate.
  153. func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateRequest, auth CertificateAuthority, p Provisioner) error {
  154. if err := o.UpdateStatus(ctx, db); err != nil {
  155. return err
  156. }
  157. switch o.Status {
  158. case StatusInvalid:
  159. return NewError(ErrorOrderNotReadyType, "order %s has been abandoned", o.ID)
  160. case StatusValid:
  161. return nil
  162. case StatusPending:
  163. return NewError(ErrorOrderNotReadyType, "order %s is not ready", o.ID)
  164. case StatusReady:
  165. break
  166. default:
  167. return NewErrorISE("unexpected status %s for order %s", o.Status, o.ID)
  168. }
  169. // Get key fingerprint if any. And then compare it with the CSR fingerprint.
  170. //
  171. // In device-attest-01 challenges we should check that the keys in the CSR
  172. // and the attestation certificate are the same.
  173. fingerprint, err := o.getAuthorizationFingerprint(ctx, db)
  174. if err != nil {
  175. return err
  176. }
  177. if fingerprint != "" {
  178. fp, err := keyutil.Fingerprint(csr.PublicKey)
  179. if err != nil {
  180. return WrapErrorISE(err, "error calculating key fingerprint")
  181. }
  182. if subtle.ConstantTimeCompare([]byte(fingerprint), []byte(fp)) == 0 {
  183. return NewError(ErrorUnauthorizedType, "order %s csr does not match the attested key", o.ID)
  184. }
  185. }
  186. // canonicalize the CSR to allow for comparison
  187. csr = canonicalize(csr)
  188. // Template data
  189. data := x509util.NewTemplateData()
  190. if o.containsWireIdentifiers() {
  191. wireDB, ok := db.(WireDB)
  192. if !ok {
  193. return fmt.Errorf("db %T is not a WireDB", db)
  194. }
  195. subject, err := createWireSubject(o, csr)
  196. if err != nil {
  197. return fmt.Errorf("failed creating Wire subject: %w", err)
  198. }
  199. data.SetSubject(subject)
  200. // Inject Wire's custom challenges into the template once they have been validated
  201. dpop, err := wireDB.GetDpopToken(ctx, o.ID)
  202. if err != nil {
  203. return fmt.Errorf("failed getting Wire DPoP token: %w", err)
  204. }
  205. data.Set("Dpop", dpop)
  206. oidc, err := wireDB.GetOidcToken(ctx, o.ID)
  207. if err != nil {
  208. return fmt.Errorf("failed getting Wire OIDC token: %w", err)
  209. }
  210. data.Set("Oidc", oidc)
  211. } else {
  212. data.SetCommonName(csr.Subject.CommonName)
  213. }
  214. // Custom sign options passed to authority.Sign
  215. var extraOptions []provisioner.SignOption
  216. // TODO: support for multiple identifiers?
  217. var permanentIdentifier string
  218. for i := range o.Identifiers {
  219. if o.Identifiers[i].Type == PermanentIdentifier {
  220. permanentIdentifier = o.Identifiers[i].Value
  221. // the first (and only) Permanent Identifier that gets added to the certificate
  222. // should be equal to the Subject Common Name if it's set. If not equal, the CSR
  223. // is rejected, because the Common Name hasn't been challenged in that case. This
  224. // could result in unauthorized access if a relying system relies on the Common
  225. // Name in its authorization logic.
  226. if csr.Subject.CommonName != "" && csr.Subject.CommonName != permanentIdentifier {
  227. return NewError(ErrorBadCSRType, "CSR Subject Common Name does not match identifiers exactly: "+
  228. "CSR Subject Common Name = %s, Order Permanent Identifier = %s", csr.Subject.CommonName, permanentIdentifier)
  229. }
  230. break
  231. }
  232. }
  233. var defaultTemplate string
  234. if permanentIdentifier != "" {
  235. defaultTemplate = x509util.DefaultAttestedLeafTemplate
  236. data.SetSubjectAlternativeNames(x509util.SubjectAlternativeName{
  237. Type: x509util.PermanentIdentifierType,
  238. Value: permanentIdentifier,
  239. })
  240. extraOptions = append(extraOptions, provisioner.AttestationData{
  241. PermanentIdentifier: permanentIdentifier,
  242. })
  243. } else {
  244. defaultTemplate = x509util.DefaultLeafTemplate
  245. sans, err := o.sans(csr)
  246. if err != nil {
  247. return err
  248. }
  249. data.SetSubjectAlternativeNames(sans...)
  250. }
  251. // Get authorizations from the ACME provisioner.
  252. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  253. signOps, err := p.AuthorizeSign(ctx, "")
  254. if err != nil {
  255. return WrapErrorISE(err, "error retrieving authorization options from ACME provisioner")
  256. }
  257. // Unlike most of the provisioners, ACME's AuthorizeSign method doesn't
  258. // define the templates, and the template data used in WebHooks is not
  259. // available.
  260. for _, signOp := range signOps {
  261. if wc, ok := signOp.(*provisioner.WebhookController); ok {
  262. wc.TemplateData = data
  263. }
  264. }
  265. templateOptions, err := provisioner.CustomTemplateOptions(p.GetOptions(), data, defaultTemplate)
  266. if err != nil {
  267. return WrapErrorISE(err, "error creating template options from ACME provisioner")
  268. }
  269. // Build extra signing options.
  270. signOps = append(signOps, templateOptions)
  271. signOps = append(signOps, extraOptions...)
  272. // Sign a new certificate.
  273. certChain, err := auth.SignWithContext(ctx, csr, provisioner.SignOptions{
  274. NotBefore: provisioner.NewTimeDuration(o.NotBefore),
  275. NotAfter: provisioner.NewTimeDuration(o.NotAfter),
  276. }, signOps...)
  277. if err != nil {
  278. // Add subproblem for webhook errors, others can be added later.
  279. var webhookErr *webhook.Error
  280. if errors.As(err, &webhookErr) {
  281. acmeError := NewDetailedError(ErrorUnauthorizedType, webhookErr.Error())
  282. acmeError.AddSubproblems(Subproblem{
  283. Type: fmt.Sprintf("urn:smallstep:acme:error:%s", webhookErr.Code),
  284. Detail: webhookErr.Message,
  285. })
  286. return acmeError
  287. }
  288. return WrapErrorISE(err, "error signing certificate for order %s", o.ID)
  289. }
  290. cert := &Certificate{
  291. AccountID: o.AccountID,
  292. OrderID: o.ID,
  293. Leaf: certChain[0],
  294. Intermediates: certChain[1:],
  295. }
  296. if err := db.CreateCertificate(ctx, cert); err != nil {
  297. return WrapErrorISE(err, "error creating certificate for order %s", o.ID)
  298. }
  299. o.CertificateID = cert.ID
  300. o.Status = StatusValid
  301. if err = db.UpdateOrder(ctx, o); err != nil {
  302. return WrapErrorISE(err, "error updating order %s", o.ID)
  303. }
  304. return nil
  305. }
  306. // containsWireIdentifiers checks if [Order] contains ACME
  307. // identifiers for the WireUser or WireDevice types.
  308. func (o *Order) containsWireIdentifiers() bool {
  309. for _, i := range o.Identifiers {
  310. if i.Type == WireUser || i.Type == WireDevice {
  311. return true
  312. }
  313. }
  314. return false
  315. }
  316. // createWireSubject creates the subject for an [Order] with WireUser identifiers.
  317. func createWireSubject(o *Order, csr *x509.CertificateRequest) (subject x509util.Subject, err error) {
  318. wireUserIDs, wireDeviceIDs, otherIDs := 0, 0, 0
  319. for _, identifier := range o.Identifiers {
  320. switch identifier.Type {
  321. case WireUser:
  322. wireID, err := wire.ParseUserID(identifier.Value)
  323. if err != nil {
  324. return subject, NewErrorISE("unmarshal wireID: %s", err)
  325. }
  326. // TODO: temporarily using a custom OIDC for carrying the display name without having it listed as a DNS SAN.
  327. // reusing LDAP's OID for diplay name see http://oid-info.com/get/2.16.840.1.113730.3.1.241
  328. displayNameOid := asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 3, 1, 241}
  329. var foundDisplayName = false
  330. for _, entry := range csr.Subject.Names {
  331. if entry.Type.Equal(displayNameOid) {
  332. foundDisplayName = true
  333. displayName := entry.Value.(string)
  334. if displayName != wireID.Name {
  335. return subject, NewErrorISE("expected displayName %v, found %v", wireID.Name, displayName)
  336. }
  337. }
  338. }
  339. if !foundDisplayName {
  340. return subject, NewErrorISE("CSR must contain the display name in '2.16.840.1.113730.3.1.241' OID")
  341. }
  342. if len(csr.Subject.Organization) == 0 || !strings.EqualFold(csr.Subject.Organization[0], wireID.Domain) {
  343. return subject, NewErrorISE("expected Organization [%s], found %v", wireID.Domain, csr.Subject.Organization)
  344. }
  345. subject.CommonName = wireID.Name
  346. subject.Organization = []string{wireID.Domain}
  347. wireUserIDs++
  348. case WireDevice:
  349. wireDeviceIDs++
  350. default:
  351. otherIDs++
  352. }
  353. }
  354. if otherIDs > 0 || wireUserIDs != 1 && wireDeviceIDs != 1 {
  355. return subject, NewErrorISE("order must have exactly one WireUser and WireDevice identifier")
  356. }
  357. return
  358. }
  359. func (o *Order) sans(csr *x509.CertificateRequest) ([]x509util.SubjectAlternativeName, error) {
  360. var sans []x509util.SubjectAlternativeName
  361. if len(csr.EmailAddresses) > 0 {
  362. return sans, NewError(ErrorBadCSRType, "Only DNS names and IP addresses are allowed")
  363. }
  364. // order the DNS names and IP addresses, so that they can be compared against the canonicalized CSR
  365. orderNames := make([]string, numberOfIdentifierType(DNS, o.Identifiers))
  366. orderIPs := make([]net.IP, numberOfIdentifierType(IP, o.Identifiers))
  367. orderPIDs := make([]string, numberOfIdentifierType(PermanentIdentifier, o.Identifiers))
  368. tmpOrderURIs := make([]*url.URL, numberOfIdentifierType(WireUser, o.Identifiers)+numberOfIdentifierType(WireDevice, o.Identifiers))
  369. indexDNS, indexIP, indexPID, indexURI := 0, 0, 0, 0
  370. for _, n := range o.Identifiers {
  371. switch n.Type {
  372. case DNS:
  373. orderNames[indexDNS] = n.Value
  374. indexDNS++
  375. case IP:
  376. orderIPs[indexIP] = net.ParseIP(n.Value) // NOTE: this assumes are all valid IPs at this time; or will result in nil entries
  377. indexIP++
  378. case PermanentIdentifier:
  379. orderPIDs[indexPID] = n.Value
  380. indexPID++
  381. case WireUser:
  382. wireID, err := wire.ParseUserID(n.Value)
  383. if err != nil {
  384. return sans, NewErrorISE("unsupported identifier value in order: %s", n.Value)
  385. }
  386. handle, err := url.Parse(wireID.Handle)
  387. if err != nil {
  388. return sans, NewErrorISE("handle must be a URI: %s", wireID.Handle)
  389. }
  390. tmpOrderURIs[indexURI] = handle
  391. indexURI++
  392. case WireDevice:
  393. wireID, err := wire.ParseDeviceID(n.Value)
  394. if err != nil {
  395. return sans, NewErrorISE("unsupported identifier value in order: %s", n.Value)
  396. }
  397. clientID, err := url.Parse(wireID.ClientID)
  398. if err != nil {
  399. return sans, NewErrorISE("clientId must be a URI: %s", wireID.ClientID)
  400. }
  401. tmpOrderURIs[indexURI] = clientID
  402. indexURI++
  403. default:
  404. return sans, NewErrorISE("unsupported identifier type in order: %s", n.Type)
  405. }
  406. }
  407. orderNames = uniqueSortedLowerNames(orderNames)
  408. orderIPs = uniqueSortedIPs(orderIPs)
  409. orderURIs := uniqueSortedURIStrings(tmpOrderURIs)
  410. totalNumberOfSANs := len(csr.DNSNames) + len(csr.IPAddresses) + len(csr.URIs)
  411. sans = make([]x509util.SubjectAlternativeName, totalNumberOfSANs)
  412. index := 0
  413. // Validate identifier names against CSR alternative names.
  414. //
  415. // Note that with certificate templates we are not going to check for the
  416. // absence of other SANs as they will only be set if the template allows
  417. // them.
  418. if len(csr.DNSNames) != len(orderNames) {
  419. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  420. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  421. }
  422. for i := range csr.DNSNames {
  423. if csr.DNSNames[i] != orderNames[i] {
  424. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  425. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  426. }
  427. sans[index] = x509util.SubjectAlternativeName{
  428. Type: x509util.DNSType,
  429. Value: csr.DNSNames[i],
  430. }
  431. index++
  432. }
  433. if len(csr.IPAddresses) != len(orderIPs) {
  434. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  435. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  436. }
  437. for i := range csr.IPAddresses {
  438. if !ipsAreEqual(csr.IPAddresses[i], orderIPs[i]) {
  439. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  440. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  441. }
  442. sans[index] = x509util.SubjectAlternativeName{
  443. Type: x509util.IPType,
  444. Value: csr.IPAddresses[i].String(),
  445. }
  446. index++
  447. }
  448. if len(csr.URIs) != len(tmpOrderURIs) {
  449. return sans, NewError(ErrorBadCSRType, "CSR URIs do not match identifiers exactly: "+
  450. "CSR URIs = %v, Order URIs = %v", csr.URIs, tmpOrderURIs)
  451. }
  452. // sort URI list
  453. csrURIs := uniqueSortedURIStrings(csr.URIs)
  454. for i := range csrURIs {
  455. if csrURIs[i] != orderURIs[i] {
  456. return sans, NewError(ErrorBadCSRType, "CSR URIs do not match identifiers exactly: "+
  457. "CSR URIs = %v, Order URIs = %v", csr.URIs, tmpOrderURIs)
  458. }
  459. sans[index] = x509util.SubjectAlternativeName{
  460. Type: x509util.URIType,
  461. Value: orderURIs[i],
  462. }
  463. index++
  464. }
  465. return sans, nil
  466. }
  467. // numberOfIdentifierType returns the number of Identifiers that
  468. // are of type typ.
  469. func numberOfIdentifierType(typ IdentifierType, ids []Identifier) int {
  470. c := 0
  471. for _, id := range ids {
  472. if id.Type == typ {
  473. c++
  474. }
  475. }
  476. return c
  477. }
  478. // canonicalize canonicalizes a CSR so that it can be compared against an Order
  479. // NOTE: this effectively changes the order of SANs in the CSR, which may be OK,
  480. // but may not be expected. It also adds a Subject Common Name to either the IP
  481. // addresses or DNS names slice, depending on whether it can be parsed as an IP
  482. // or not. This might result in an additional SAN in the final certificate.
  483. func canonicalize(csr *x509.CertificateRequest) (canonicalized *x509.CertificateRequest) {
  484. // for clarity only; we're operating on the same object by pointer
  485. canonicalized = csr
  486. // RFC8555: The CSR MUST indicate the exact same set of requested
  487. // identifiers as the initial newOrder request. Identifiers of type "dns"
  488. // MUST appear either in the commonName portion of the requested subject
  489. // name or in an extensionRequest attribute [RFC2985] requesting a
  490. // subjectAltName extension, or both. Subject Common Names that can be
  491. // parsed as an IP are included as an IP address for the equality check.
  492. // If these were excluded, a certificate could contain an IP as the
  493. // common name without having been challenged.
  494. if csr.Subject.CommonName != "" {
  495. if ip := net.ParseIP(csr.Subject.CommonName); ip != nil {
  496. canonicalized.IPAddresses = append(canonicalized.IPAddresses, ip)
  497. } else {
  498. canonicalized.DNSNames = append(canonicalized.DNSNames, csr.Subject.CommonName)
  499. }
  500. }
  501. canonicalized.DNSNames = uniqueSortedLowerNames(canonicalized.DNSNames)
  502. canonicalized.IPAddresses = uniqueSortedIPs(canonicalized.IPAddresses)
  503. return canonicalized
  504. }
  505. // ipsAreEqual compares IPs to be equal. Nil values (i.e. invalid IPs) are
  506. // not considered equal. IPv6 representations of IPv4 addresses are
  507. // considered equal to the IPv4 address in this implementation, which is
  508. // standard Go behavior. An example is "::ffff:192.168.42.42", which
  509. // is equal to "192.168.42.42". This is considered a known issue within
  510. // step and is tracked here too: https://github.com/golang/go/issues/37921.
  511. func ipsAreEqual(x, y net.IP) bool {
  512. if x == nil || y == nil {
  513. return false
  514. }
  515. return x.Equal(y)
  516. }
  517. // uniqueSortedLowerNames returns the set of all unique names in the input after all
  518. // of them are lowercased. The returned names will be in their lowercased form
  519. // and sorted alphabetically.
  520. func uniqueSortedLowerNames(names []string) (unique []string) {
  521. nameMap := make(map[string]int, len(names))
  522. for _, name := range names {
  523. nameMap[strings.ToLower(name)] = 1
  524. }
  525. unique = make([]string, 0, len(nameMap))
  526. for name := range nameMap {
  527. if name != "" {
  528. unique = append(unique, name)
  529. }
  530. }
  531. sort.Strings(unique)
  532. return
  533. }
  534. func uniqueSortedURIStrings(uris []*url.URL) (unique []string) {
  535. uriMap := make(map[string]struct{}, len(uris))
  536. for _, name := range uris {
  537. uriMap[name.String()] = struct{}{}
  538. }
  539. unique = make([]string, 0, len(uriMap))
  540. for name := range uriMap {
  541. unique = append(unique, name)
  542. }
  543. sort.Strings(unique)
  544. return
  545. }
  546. // uniqueSortedIPs returns the set of all unique net.IPs in the input. They
  547. // are sorted by their bytes (octet) representation.
  548. func uniqueSortedIPs(ips []net.IP) (unique []net.IP) {
  549. type entry struct {
  550. ip net.IP
  551. }
  552. ipEntryMap := make(map[string]entry, len(ips))
  553. for _, ip := range ips {
  554. // reparsing the IP results in the IP being represented using 16 bytes
  555. // for both IPv4 as well as IPv6, even when the ips slice contains IPs that
  556. // are represented by 4 bytes. This ensures a fair comparison and thus ordering.
  557. ipEntryMap[ip.String()] = entry{ip: net.ParseIP(ip.String())}
  558. }
  559. unique = make([]net.IP, 0, len(ipEntryMap))
  560. for _, entry := range ipEntryMap {
  561. unique = append(unique, entry.ip)
  562. }
  563. sort.Slice(unique, func(i, j int) bool {
  564. return bytes.Compare(unique[i], unique[j]) < 0
  565. })
  566. return
  567. }