Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions cmd/domains_authenticate.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ type dnsSetupLinkResponse struct {
}

func runDomainsConfigure(cmd *cobra.Command, args []string) error {
return runDNSSetupLink(cmd, args, "domain_auth")
}

// runDNSSetupLink mints a DNS-setup handoff link for one Entri flow and prints
// the URL the browser opens to run it.
func runDNSSetupLink(cmd *cobra.Command, args []string, flow string) error {
c := clientFromCmd(cmd)
if c == nil {
return errNoClient(cmd)
Expand All @@ -89,6 +95,7 @@ func runDomainsConfigure(cmd *cobra.Command, args []string) error {
"domain": dom.Name,
"domain_id": dom.ID,
"env_id": envID,
"flow": flow,
"will_fetch": []string{"POST dns_setup_link"},
})
}
Expand All @@ -98,8 +105,8 @@ func runDomainsConfigure(cmd *cobra.Command, args []string) error {
// server-side — so the link stays short enough to survive a terminal and
// the records reflect completed provisioning rather than whatever existed
// when the link was minted.
linkPath := fmt.Sprintf("/v1/environments/%s/domains/%s/dns_setup_link?flow=domain_auth", envID, dom.ID)
raw, err := c.Do(cmd.Context(), "POST", linkPath, nil, nil)
linkPath := fmt.Sprintf("/v1/environments/%s/domains/%s/dns_setup_link", envID, dom.ID)
raw, err := c.Do(cmd.Context(), "POST", linkPath, map[string]string{"flow": flow}, nil)
if err != nil {
return handleWriteError(cmd, "POST", err)
}
Expand Down
157 changes: 157 additions & 0 deletions cmd/domains_postmaster_tools.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
package cmd

import (
"encoding/json"
"fmt"

"github.com/customerio/cli/internal/output"
"github.com/spf13/cobra"
)

var domainsPostmasterToolsCmd = &cobra.Command{
Use: "postmaster_tools",
Short: "Set up and verify a domain's Postmaster Tools record",
Long: `Publish and verify the Postmaster Tools record for a domain.

Postmaster Tools is Google's report on how Gmail treats your mail. Once the
workspace has connected a Google account, each sending domain's registrable
root (example.com for mail.example.com) needs a TXT record that proves you own
it.

Subcommands:
configure Launch guided DNS setup for the record via Entri
verify Check the record with Google`,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}

var domainsPostmasterToolsConfigureCmd = &cobra.Command{
Use: "configure <domain>",
Short: "Launch guided DNS setup for the Postmaster Tools record via Entri",
Long: `Open the Entri DNS setup flow in a browser to publish the domain's
Postmaster Tools TXT record at its registrable root, without touching its other
DNS records. Use it for a domain whose authentication is already set up.

POST /v1/environments/:env_id/domains/:domain_id/dns_setup_link?flow=postmaster_tools

The domain must have a pending Postmaster Tools record: the workspace has
connected a Google account and the domain's root is added in Postmaster Tools.

Examples:
cio domains --env-id 456 postmaster_tools configure mail.example.com`,
Args: requireArg("domain"),
RunE: func(cmd *cobra.Command, args []string) error {
return runDNSSetupLink(cmd, args, "postmaster_tools")
},
}

var domainsPostmasterToolsVerifyCmd = &cobra.Command{
Use: "verify <domain>",
Short: "Check the Postmaster Tools record with Google",
Long: `Ask Google to verify the domain's Postmaster Tools record and report its status.

POST /v1/environments/:env_id/domains/:domain_id/verify

Returns the registrable root, its status (verified, pending, not_added or
not_connected) and, while pending, the TXT record to publish.

Examples:
cio domains --env-id 456 postmaster_tools verify mail.example.com`,
Args: requireArg("domain"),
RunE: runPostmasterToolsVerify,
}

func init() {
domainsPostmasterToolsCmd.AddCommand(domainsPostmasterToolsConfigureCmd)
domainsPostmasterToolsCmd.AddCommand(domainsPostmasterToolsVerifyCmd)
domainsCmd.AddCommand(domainsPostmasterToolsCmd)
}

// postmasterToolsVerifyResponse is the part of the domain verify response this
// command reports; postmaster is absent where Postmaster Tools isn't set up.
type postmasterToolsVerifyResponse struct {
Postmaster *struct {
Root string `json:"root"`
Status string `json:"status"`
Record *struct {
Domain string `json:"domain"`
Type string `json:"type"`
Value string `json:"value"`
} `json:"record,omitempty"`
} `json:"postmaster"`
}

func runPostmasterToolsVerify(cmd *cobra.Command, args []string) error {
c := clientFromCmd(cmd)
if c == nil {
return errNoClient(cmd)
}

envID, err := resolveEnvID(cmd)
if err != nil {
return err
}

dom, err := resolveDomain(cmd.Context(), c, envID, args[0])
if err != nil {
output.PrintError(output.CodeValidationError, err.Error(), map[string]any{
"argument": "domain",
})
return err
}

path := fmt.Sprintf("/v1/environments/%s/domains/%s/verify", envID, dom.ID)

if GetDryRun(cmd) {
return output.FprintJSON(cmd.OutOrStdout(), map[string]any{
"dry_run": true,
"method": "POST",
"url": c.BaseURL() + path,
})
}

result, err := c.Do(cmd.Context(), "POST", path, nil, nil)
if err != nil {
return handleWriteError(cmd, "POST", err)
}

if GetJQFlag(cmd) != "" {
return printWriteResult(cmd, "POST", result, GetJQFlag(cmd))
}

var resp postmasterToolsVerifyResponse
if err := json.Unmarshal(result, &resp); err != nil {
return output.FprintJSON(cmd.OutOrStdout(), json.RawMessage(result))
}

w := cmd.ErrOrStderr()
out := map[string]any{"domain": dom.Name, "verified": false}
setup := resp.Postmaster
if setup == nil {
fmt.Fprintf(w, "Postmaster Tools isn't set up for %s's workspace.\n", dom.Name)
out["status"] = "unavailable"
return output.FprintJSON(cmd.OutOrStdout(), out)
}
out["root"] = setup.Root
out["status"] = setup.Status
switch setup.Status {
case "verified":
out["verified"] = true
fmt.Fprintf(w, "Postmaster Tools record for %s: verified.\n", setup.Root)
case "pending":
fmt.Fprintf(w, "Postmaster Tools record for %s: not verified yet.\n", setup.Root)
if setup.Record != nil {
out["record"] = setup.Record
fmt.Fprintf(w, "\n %s %s\n %s\n", setup.Record.Type, setup.Record.Domain, setup.Record.Value)
}
fmt.Fprintf(w, "\nPublish the record, or run 'cio domains postmaster_tools configure %s', then re-run verify.\n", dom.Name)
case "not_added":
fmt.Fprintf(w, "%s isn't in Postmaster Tools yet. Add it in Customer.io to get its record.\n", setup.Root)
case "not_connected":
fmt.Fprintln(w, "The workspace hasn't connected a Google account for Postmaster Tools yet.")
default:
fmt.Fprintf(w, "Postmaster Tools record for %s: %s.\n", setup.Root, setup.Status)
}
return output.FprintJSON(cmd.OutOrStdout(), out)
}
153 changes: 153 additions & 0 deletions cmd/domains_postmaster_tools_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package cmd

import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

// postmasterToolsServer answers OAuth, the domain list, dns_setup_link (recording
// the flow it was asked for) and domain verify with the given postmaster state.
func postmasterToolsServer(t *testing.T, postmaster string, flows *[]string) *httptest.Server {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/v1/service_accounts/oauth/token":
_, _ = w.Write([]byte(`{"access_token":"jwt-test-session","token_type":"Bearer","expires_in":3600}`))
case r.Header.Get("Authorization") != "Bearer jwt-test-session":
w.WriteHeader(http.StatusUnauthorized)
case r.Method == "GET" && r.URL.Path == "/v1/environments/456/domains":
_, _ = w.Write([]byte(`{"domains":[{"id":"789","domain":"mail.example.com"}]}`))
case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/dns_setup_link"):
*flows = append(*flows, r.URL.Query().Get("flow"))
_, _ = w.Write([]byte(`{"handoff_token":"test.handoff.token","expires_in":300}`))
case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/verify"):
_, _ = w.Write([]byte(`{"domain":{"id":"789","domain":"mail.example.com","verified":true}` + postmaster + `}`))
default:
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(server.Close)
return server
}

func setupPostmasterToolsTest(t *testing.T, postmaster string) (*httptest.Server, *[]string) {
t.Helper()
t.Setenv("HOME", t.TempDir())
t.Setenv("CIO_TOKEN", "sa_live_test123")
t.Setenv("CIO_ACCESS_TOKEN", "")
t.Setenv("CIO_UI_URL", "")
resetDomainFlags()
flows := []string{}
return postmasterToolsServer(t, postmaster, &flows), &flows
}

func TestDomains_PostmasterTools_Configure(t *testing.T) {
server, flows := setupPostmasterToolsTest(t, "")

stdout, stderr, err := executeCommand("domains", "postmaster_tools", "configure",
"--env-id", "456", "mail.example.com", "--api-url", server.URL)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*flows) != 1 || (*flows)[0] != "postmaster_tools" {
t.Errorf("expected one dns_setup_link call with flow=postmaster_tools, got %v", *flows)
}
if !strings.Contains(stderr, "/cli/dns-setup#test.handoff.token") {
t.Errorf("expected the setup URL in stderr, got: %s", stderr)
}
var result map[string]any
if err := json.Unmarshal([]byte(stdout), &result); err != nil {
t.Fatalf("invalid JSON on stdout: %v\nstdout: %s", err, stdout)
}
if result["domain"] != "mail.example.com" || result["domain_id"] != "789" {
t.Errorf("unexpected stdout: %v", result)
}
}

func TestDomains_Configure_StillMintsDomainAuth(t *testing.T) {
server, flows := setupPostmasterToolsTest(t, "")

if _, _, err := executeCommand("domains", "configure",
"--env-id", "456", "mail.example.com", "--api-url", server.URL); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*flows) != 1 || (*flows)[0] != "domain_auth" {
t.Errorf("expected flow=domain_auth, got %v", *flows)
}
}

func TestDomains_PostmasterTools_Configure_DryRun(t *testing.T) {
server, flows := setupPostmasterToolsTest(t, "")

stdout, _, err := executeCommand("domains", "postmaster_tools", "configure",
"--env-id", "456", "mail.example.com", "--dry-run", "--api-url", server.URL)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*flows) != 0 {
t.Errorf("dry run must not mint a link, got %v", *flows)
}
if !strings.Contains(stdout, `"flow": "postmaster_tools"`) && !strings.Contains(stdout, `"flow":"postmaster_tools"`) {
t.Errorf("expected the flow in the dry-run output, got: %s", stdout)
}
}

func TestDomains_PostmasterTools_Verify(t *testing.T) {
cases := []struct {
name string
postmaster string
wantStatus string
wantVerified bool
wantStderr string
}{
{
name: "verified",
postmaster: `,"postmaster":{"root":"example.com","status":"verified"}`,
wantStatus: "verified",
wantVerified: true,
wantStderr: "Postmaster Tools record for example.com: verified.",
},
{
name: "pending shows the record",
postmaster: `,"postmaster":{"root":"example.com","status":"pending","record":{"domain":"example.com","type":"TXT","value":"google-site-verification=abc"}}`,
wantStatus: "pending",
wantStderr: "google-site-verification=abc",
},
{
name: "not added",
postmaster: `,"postmaster":{"root":"example.com","status":"not_added"}`,
wantStatus: "not_added",
wantStderr: "isn't in Postmaster Tools yet",
},
{
name: "not set up for the workspace",
postmaster: "",
wantStatus: "unavailable",
wantStderr: "Postmaster Tools isn't set up",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
server, _ := setupPostmasterToolsTest(t, tc.postmaster)

stdout, stderr, err := executeCommand("domains", "postmaster_tools", "verify",
"--env-id", "456", "mail.example.com", "--api-url", server.URL)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var result map[string]any
if err := json.Unmarshal([]byte(stdout), &result); err != nil {
t.Fatalf("invalid JSON on stdout: %v\nstdout: %s", err, stdout)
}
if result["status"] != tc.wantStatus || result["verified"] != tc.wantVerified {
t.Errorf("expected status=%s verified=%v, got %v", tc.wantStatus, tc.wantVerified, result)
}
if !strings.Contains(stderr, tc.wantStderr) {
t.Errorf("expected %q in stderr, got: %s", tc.wantStderr, stderr)
}
})
}
}
2 changes: 2 additions & 0 deletions cmd/domains_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ func resetDomainFlags() {
domainsFromAddressesUpdateCmd,
domainsLinkTrackingConfigureCmd,
domainsLinkTrackingVerifyCmd,
domainsPostmasterToolsConfigureCmd,
domainsPostmasterToolsVerifyCmd,
domainsFromAddressesDeleteCmd,
} {
cmd.Flags().Visit(func(f *pflag.Flag) {
Expand Down
Loading