Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cli: add telemetry wrapper for cli commands #333

Merged
merged 2 commits into from
Apr 22, 2024
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
1 change: 1 addition & 0 deletions .github/workflows/e2e_openssl.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ on:
env:
container_registry: ghcr.io/edgelesssys
azure_resource_group: contrast-ci
DO_NOT_TRACK: 1

jobs:
test:
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/e2e_servicemesh.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ on:
env:
container_registry: ghcr.io/edgelesssys
azure_resource_group: contrast-ci
DO_NOT_TRACK: 1

jobs:
test:
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/e2e_simple.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ on:
env:
container_registry: ghcr.io/edgelesssys
azure_resource_group: contrast-ci
DO_NOT_TRACK: 1

jobs:
test:
Expand Down
21 changes: 21 additions & 0 deletions cli/cmd/common.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package cmd

import (
"context"
_ "embed"
"os"
"path/filepath"
"time"

"github.com/edgelesssys/contrast/cli/telemetry"
"github.com/spf13/cobra"
)

const (
Expand Down Expand Up @@ -44,3 +49,19 @@ func must(err error) {
panic(err)
}
}

func withTelemetry(runFunc func(*cobra.Command, []string) error) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, args []string) error {
cmdErr := runFunc(cmd, args)

if os.Getenv("DO_NOT_TRACK") != "1" {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()

cl := telemetry.NewClient()
_ = cl.SendTelemetry(ctx, cmd, cmdErr)
}

return cmdErr
}
}
2 changes: 1 addition & 1 deletion cli/cmd/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ If the Kubernetes YAML contains a Contrast Coordinator pod whose policy differs
the embedded default, the generated policy will be printed to stdout, alongside a
warning message on stderr. This hash needs to be passed to the set and verify
subcommands.`,
RunE: runGenerate,
RunE: withTelemetry(runGenerate),
}

cmd.Flags().StringP("policy", "p", rulesFilename, "path to policy (.rego) file")
Expand Down
2 changes: 1 addition & 1 deletion cli/cmd/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ reference values embedded into the CLI.
After the connection is established, the manifest is set. The Coordinator
will re-generate the mesh root certificate and accept new workloads to
issuer certificates.`,
RunE: runSet,
RunE: withTelemetry(runSet),
}

cmd.Flags().StringP("manifest", "m", manifestFilename, "path to manifest (.json) file")
Expand Down
2 changes: 1 addition & 1 deletion cli/cmd/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ reference values embedded into the CLI.

After the connection is established, the CLI will request the manifest history,
all policies, and the certificates of the Coordinator certificate authority.`,
RunE: runVerify,
RunE: withTelemetry(runVerify),
}

// Override persistent workspace-dir flag with a default value.
Expand Down
12 changes: 12 additions & 0 deletions cli/telemetry/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package telemetry

// classifyCmdErr maps errors to fixed strings to avoid leaking sensitive data inside error messages.
func classifyCmdErr(e error) string {
if e == nil {
return ""
}
switch {
default:
return "unknown error"
}
}
93 changes: 93 additions & 0 deletions cli/telemetry/telemetry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package telemetry

import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"runtime"

"github.com/spf13/cobra"
)

const (
apiHost = "telemetry.confidential.cloud"
telemetryPath = "api/contrast/v1"
)

// RequestV1 holds the information to be sent to the telemetry server.
type RequestV1 struct {
Version string `json:"version"`
GOOS string `json:"goos"`
GOARCH string `json:"goarch"`
Cmd string `json:"cmd"`
CmdErrClass string `json:"cmderrclass"`
Test bool `json:"test" gorm:"-"`
}

// IsTest checks if the request is used for testing.
func (r *RequestV1) IsTest() bool {
return r.Test
}

// Client sends the telemetry.
type Client struct {
httpClient *http.Client
}

// NewClient creates a new Client.
func NewClient() *Client {
return &Client{
httpClient: &http.Client{},
}
}

// SendTelemetry sends telemetry data to the telemetry server.
func (c *Client) SendTelemetry(ctx context.Context, cmd *cobra.Command, cmdErr error) error {
cmdErrClass := classifyCmdErr(cmdErr)

if cmd.Root().Version == "" {
return fmt.Errorf("no cli version found")
}

telemetryRequest := RequestV1{
Version: cmd.Root().Version,
GOOS: runtime.GOOS,
GOARCH: runtime.GOARCH,
Cmd: cmd.Name(),
CmdErrClass: cmdErrClass,
Test: false,
}

reqBody, err := json.Marshal(telemetryRequest)
if err != nil {
return fmt.Errorf("marshalling input: %w", err)
}

req, err := http.NewRequestWithContext(ctx, http.MethodPost, telemetryURL().String(), bytes.NewReader(reqBody))
if err != nil {
return fmt.Errorf("creating request: %w", err)
}
req.Header.Add("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("doing request: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("http error %d", resp.StatusCode)
}

return nil
}

func telemetryURL() *url.URL {
return &url.URL{
Scheme: "https",
Host: apiHost,
Path: telemetryPath,
}
}
85 changes: 85 additions & 0 deletions cli/telemetry/telemetry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package telemetry

import (
"context"
"fmt"
"net/http"
"testing"

"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
)

type roundTripFunc func(req *http.Request) *http.Response

func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}

func newTestClient(fn roundTripFunc) *http.Client {
return &http.Client{
Transport: fn,
}
}

func TestSendTelemetry(t *testing.T) {
rootTestCmd := &cobra.Command{Version: "0.0.0-dev"}
goodTestCmd := &cobra.Command{}
rootTestCmd.AddCommand(goodTestCmd)

badTestCmd := &cobra.Command{}

testCases := map[string]struct {
cmd *cobra.Command
cmdErr error
serverResponseCode int
wantError bool
}{
"success no cmdError": {
cmd: goodTestCmd,
cmdErr: nil,
serverResponseCode: http.StatusOK,
wantError: false,
},
"success with cmdError": {
cmd: goodTestCmd,
cmdErr: fmt.Errorf("test error"),
serverResponseCode: http.StatusOK,
wantError: false,
},
"bad command": {
cmd: badTestCmd,
cmdErr: nil,
serverResponseCode: http.StatusOK,
wantError: true,
},
"bad http response": {
cmd: goodTestCmd,
cmdErr: nil,
serverResponseCode: http.StatusInternalServerError,
wantError: true,
},
}

for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)

client := &Client{
httpClient: newTestClient(func(_ *http.Request) *http.Response {
return &http.Response{
StatusCode: tc.serverResponseCode,
}
}),
}

err := client.SendTelemetry(context.Background(), tc.cmd, tc.cmdErr)

if tc.wantError {
assert.Error(err)
return
}
assert.NoError(err)
})
}
}
5 changes: 4 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@
gotools
just
];
shellHook = ''alias make=just'';
shellHook = ''
alias make=just
export DO_NOT_TRACK=1
'';
};
docs = pkgs.mkShell {
packages = with pkgs; [
Expand Down