Repository: microsoft/go-mssqldb
Pull request #121 (2023-06-26 19:56:13)

Allow for local dns resolution with a custom dialer
If the custom dialer updates the transport to proxy the mssql connection, and only the proxy can reach the network that mssql is running in, then any local DNS resolution will fail.

To address this, this PR ensures the custom dialer is used, if defined, to resolve the DNS.

We've been using this logic on [Grafana's forked repo](https://github.com/grafana/go-mssqldb) for the past few months.

microsoft-github-policy-service[bot]: 
@stephaniehingtgen please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

```
@microsoft-github-policy-service agree [company="{your company}"]
```

> Options:
> - (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
>```
>@microsoft-github-policy-service agree
>```
> - (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
>```
>@microsoft-github-policy-service agree company="Microsoft"
>```

<details>
    <summary>Contributor License Agreement</summary>
    
### Contribution License Agreement
This Contribution License Agreement (**“Agreement”**) is agreed to by the party signing below (**“You”**),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.
1. **Definitions**.
**“Code”** means the computer software code, whether in human-readable or machine-executable form,
that is delivered by You to Microsoft under this Agreement.
**“Project”** means any of the projects owned or managed by Microsoft and offered under a license
approved by the Open Source Initiative (www.opensource.org).
**“Submit”** is the act of uploading, submitting, transmitting, or distributing code or other content to any
Project, including but not limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
discussing and improving that Project, but excluding communication that is conspicuously marked or
otherwise designated in writing by You as “Not a Submission.”
**“Submission”** means the Code and any other copyrightable material Submitted by You, including any
associated comments and documentation.
2. **Your Submission**. You must agree to the terms of this Agreement before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now or in the future (except as
described in Section 4 below), Submit to any Project.
3. **Originality of Work**. You represent that each of Your Submissions is entirely Your original work.
Should You wish to Submit materials that are not Your original work, You may Submit them separately
to the Project if You (a) retain all copyright and license information that was in the materials as You
received them, (b) in the description accompanying Your Submission, include the phrase “Submission
containing materials of a third party:” followed by the names of the third party and any licenses or other
restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
guidelines concerning Submissions.
4. **Your Employer**. References to “employer” in this Agreement include Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your employer has intellectual
property rights in Your Submission by contract or applicable law, You must secure permission from Your
employer to make the Submission before signing this Agreement. In that case, the term “You” in this
Agreement will refer to You and the employer collectively. If You change employers in the future and
desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
and secure permission from the new employer before Submitting those Submissions.
5. **Licenses**.
  * **Copyright License**. You grant Microsoft, and those who receive the Submission directly or
indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
parties.
  * **Patent License**. You grant Microsoft, and those who receive the Submission directly or
indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
Your patent claims that are necessarily infringed by the Submission or the combination of the
Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the Project.
  * **Other Rights Reserved**. Each party reserves all rights not expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.
6. **Representations and Warranties**. You represent that You are legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
have disclosed under Section 3). You represent that You have secured permission from Your employer to
make the Submission in cases where Your Submission is made in the course of Your work for Your
employer or Your employer has intellectual property rights in Your Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7. **Notice to Microsoft**. You agree to notify Microsoft in writing of any facts or circumstances of which
You later become aware that would make Your representations in this Agreement inaccurate in any
respect.
8. **Information about Submissions**. You agree that contributions to Projects and information about
contributions may be maintained indefinitely and disclosed publicly, including Your name and other
information that You submit with Your Submission.
9. **Governing Law/Jurisdiction**. This Agreement is governed by the laws of the State of Washington, and
the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
defenses of lack of personal jurisdiction and forum non-conveniens.
10. **Entire Agreement/Assignment**. This Agreement is the entire agreement between the parties, and
supersedes any and all prior agreements, understandings or communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

</details>
<!-- Policy app identification https://img.shields.io/static/v1?label=ContributorLicenseAgreement. -->
codecov-commenter: ## [Codecov](https://app.codecov.io/gh/microsoft/go-mssqldb/pull/121?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=microsoft) Report
> Merging [#121](https://app.codecov.io/gh/microsoft/go-mssqldb/pull/121?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=microsoft) (fd2dcf7) into [main](https://app.codecov.io/gh/microsoft/go-mssqldb/commit/dd3e503886b5f5af48a759ed2891a1320db5126f?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=microsoft) (dd3e503) will **decrease** coverage by `0.04%`.
> The diff coverage is `100.00%`.

```diff
@@            Coverage Diff             @@
##             main     #121      +/-   ##
==========================================
- Coverage   73.95%   73.91%   -0.04%     
==========================================
  Files          29       29              
  Lines        5613     5620       +7     
==========================================
+ Hits         4151     4154       +3     
- Misses       1212     1215       +3     
- Partials      250      251       +1     
```


| [Impacted Files](https://app.codecov.io/gh/microsoft/go-mssqldb/pull/121?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=microsoft) | Coverage Δ | |
|---|---|---|
| [protocol.go](https://app.codecov.io/gh/microsoft/go-mssqldb/pull/121?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=microsoft#diff-cHJvdG9jb2wuZ28=) | `93.06% <100.00%> (-0.55%)` | :arrow_down: |

... and [2 files with indirect coverage changes](https://app.codecov.io/gh/microsoft/go-mssqldb/pull/121/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=microsoft)


shueybubbles: thank you for submitting a PR!
stephaniehingtgen: @microsoft-github-policy-service agree company="Grafana"
stephaniehingtgen: @shueybubbles updated the README & Changelog! Thanks for the review!

@apoorvdeshmukh I updated the unit test, but I'm unable to kick off running the tests. Would you be able to kick it off for me?

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 433a384..7b954d9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
 # Changelog
 
+## 1.2.0
+
+### Features
+
+* A connector's dialer can now be used to resolve DNS if the dialer implements the `HostDialer` interface
+
 ## 1.0.0
 
 ### Features
diff --git a/README.md b/README.md
index 03162f3..48dd471 100644
--- a/README.md
+++ b/README.md
@@ -72,6 +72,10 @@ Other supported formats are listed below.
 
 If no pipe name can be derived from the DSN, connection attempts will first query the SQL Browser service to find the pipe name for the instance.
 
+### DNS Resolution through a Custom Dialer
+
+Custom Dialers can be used to resolve DNS if the Connection's Dialer implements the `HostDialer` interface. This is helpful when the dialer is proxying requests to a different, private network and the DNS record is local to the private network.
+
 ### Protocol configuration
 
 To force a specific protocol for the connection there two several options:
diff --git a/mssql.go b/mssql.go
index a875e8a..23a271d 100644
--- a/mssql.go
+++ b/mssql.go
@@ -194,7 +194,9 @@ type Connector struct {
 	// SessionInitSQL is empty.
 	SessionInitSQL string
 
-	// Dialer sets a custom dialer for all network operations.
+	// Dialer sets a custom dialer for all network operations, except DNS resolution unless
+	// the dialer implements the HostDialer.
+	//
 	// If Dialer is not set, normal net dialers are used.
 	Dialer Dialer
 }
@@ -203,6 +205,13 @@ type Dialer interface {
 	DialContext(ctx context.Context, network string, addr string) (net.Conn, error)
 }
 
+// HostDialer should be used if the dialer is proxying requests to a different network
+// and DNS should be resolved in that other network
+type HostDialer interface {
+	Dialer
+	HostName() string
+}
+
 func (c *Connector) getDialer(p *msdsn.Config) Dialer {
 	if c != nil && c.Dialer != nil {
 		return c.Dialer
diff --git a/protocol.go b/protocol.go
index 755075b..f7635d5 100644
--- a/protocol.go
+++ b/protocol.go
@@ -51,6 +51,14 @@ func (t tcpDialer) DialSqlConnection(ctx context.Context, c *Connector, p *msdsn
 	var ips []net.IP
 	ip := net.ParseIP(p.Host)
 	if ip == nil {
+		// if the custom dialer is a host dialer, the DNS is resolved within the network
+		// the dialer is sending the request to, rather than the one the driver is running on
+		d := c.getDialer(p)
+		if _, ok := d.(HostDialer); ok {
+			addr := net.JoinHostPort(p.Host, strconv.Itoa(int(resolveServerPort(p.Port))))
+			return d.DialContext(ctx, "tcp", addr)
+		}
+
 		ips, err = net.LookupIP(p.Host)
 		if err != nil {
 			return
diff --git a/ucs22str.go b/ucs22str.go
index 9c9c66e..b60a254 100644
--- a/ucs22str.go
+++ b/ucs22str.go
@@ -1,5 +1,5 @@
-//go:build !386 && !arm
-// +build !386,!arm
+//go:build !386 && !arm && !mips && !mipsle
+// +build !386,!arm,!mips,!mipsle
 
 package mssql
 
diff --git a/ucs22str_32bit.go b/ucs22str_32bit.go
index 22ef73b..2746170 100644
--- a/ucs22str_32bit.go
+++ b/ucs22str_32bit.go
@@ -1,5 +1,5 @@
-//go:build arm || 386
-// +build arm 386
+//go:build arm || 386 || mips || mipsle
+// +build arm 386 mips mipsle
 
 package mssql
 


Test patch:
diff --git a/tds_login_test.go b/tds_login_test.go
index 70a6b29..780ae58 100644
--- a/tds_login_test.go
+++ b/tds_login_test.go
@@ -43,6 +43,19 @@ func (d *MockTransportDialer) DialContext(ctx context.Context, network string, a
 	return d.client, nil
 }
 
+type MockHostTransportDialer struct {
+	Dialer *MockTransportDialer
+	Host   string
+}
+
+func (m MockHostTransportDialer) DialContext(ctx context.Context, network string, addr string) (conn net.Conn, err error) {
+	return m.Dialer.DialContext(ctx, network, addr)
+}
+
+func (m MockHostTransportDialer) HostName() string {
+	return m.Host
+}
+
 func testLoginSequenceServer(result chan error, conn net.Conn, expectedPackets, responsePackets []string) {
 	defer func() {
 		conn.Close()
diff --git a/tds_test.go b/tds_test.go
index 94d1be6..448491b 100644
--- a/tds_test.go
+++ b/tds_test.go
@@ -971,3 +971,56 @@ func versionToHexString(v uint32) string {
 	binary.LittleEndian.PutUint32(b, v)
 	return hex.EncodeToString(b)
 }
+
+func TestDialSqlConnectionCustomDialer(t *testing.T) {
+	tl := testLogger{t: t}
+	defer tl.StopLogging()
+	SetLogger(&tl)
+
+	params := msdsn.Config{
+		Host: "nonexistant-dns.svc.cluster.local",
+	}
+	connector, err := NewConnector(params.URL().String())
+	if err != nil {
+		t.Error(err)
+	}
+
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
+	defer cancel()
+
+	// if a host dialer is specified, the dialer should be used to resolve the DNS
+	mock := NewMockTransportDialer(
+		[]string{},
+		[]string{},
+	)
+	connector.Dialer = MockHostTransportDialer{
+		Dialer: mock,
+		Host:   params.Host,
+	}
+
+	if mock.count != 0 {
+		t.Error("expecting no connections")
+	}
+	sqlDialer, _ := msdsn.ProtocolDialers["tcp"].(MssqlProtocolDialer)
+	conn, err := sqlDialer.DialSqlConnection(ctx, connector, &params)
+	if err != nil {
+		t.Error(err)
+	}
+
+	if mock.count != 1 {
+		t.Error("expecting 1 connection")
+	}
+
+	err = conn.Close()
+	if err != nil {
+		t.Error(err)
+	}
+
+	// if it is not a host dialer, the dialer should not be used to resolve DNS
+	connector.Dialer = mock
+	sqlDialer, _ = msdsn.ProtocolDialers["tcp"].(MssqlProtocolDialer)
+	_, err = sqlDialer.DialSqlConnection(ctx, connector, &params)
+	if err == nil {
+		t.Error(fmt.Errorf("dialer should not be used to resolve dns if not a host dialer"))
+	}
+}