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
43 changes: 30 additions & 13 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,6 @@ linters:
linters:
- forbidigo
text: stdout is a command's output
- path: internal/tfstate/apiproxy/
linters:
- forbidigo
text: one HTTP client
# The fake clock is a test's; production code waits on the real one.
- path-except: _test\.go
linters:
Expand Down Expand Up @@ -243,7 +239,15 @@ linters:
- $all
deny:
- pkg: encoding/json$
desc: Use encoding/json/v2 and internal/json instead
desc: Use internal/json instead

json-v2:
files:
- $all
- "!**/internal/json/*.go"
deny:
- pkg: encoding/json/v2
desc: Use internal/json instead

# cobra is used in cmd/ and nowhere else.
cmd:
Expand All @@ -267,8 +271,8 @@ linters:
- log/slog
# a listing yields raw items, and reads a field out of one
- encoding/json/jsontext
- encoding/json/v2
# no direct access to internal/
- github.com/meshcloud/meshstack-cli/internal/json
# no direct access to internal/, apart from the JSON codec above
- github.com/meshcloud/meshstack-cli/pkg
# a parent command calls its children's New, the same way cmd/meshstack calls its own
- github.com/meshcloud/meshstack-cli/cmd
Expand Down Expand Up @@ -305,7 +309,7 @@ linters:
- log/slog
# a request body is checked as JSON, and api-docs writes a part of the OpenAPI document
- encoding/json/jsontext
- encoding/json/v2
- github.com/meshcloud/meshstack-cli/internal/json
- github.com/meshcloud/meshstack-cli/cmd/internal
- github.com/meshcloud/meshstack-cli/client
# the API docs choose the version of a request
Expand Down Expand Up @@ -407,7 +411,7 @@ linters:
- log/slog
# a listing writes raw items, and a command that shows one object marshals it
- encoding/json/jsontext
- encoding/json/v2
- github.com/meshcloud/meshstack-cli/internal/json
- github.com/meshcloud/meshstack-cli/cmd/internal/markdown
- github.com/meshcloud/meshstack-cli/cmd/internal/color
- github.com/meshcloud/meshstack-cli/pkg
Expand Down Expand Up @@ -441,7 +445,6 @@ linters:
desc: Use log/slog instead
allow:
- $gostd
- encoding/json/v2
- encoding/json/jsontext
- log/slog
- github.com/meshcloud/meshstack-cli/client
Expand Down Expand Up @@ -492,13 +495,13 @@ linters:
- "!**/cmd/**/*.go" # ...except cmd, whose internal packages the cmd rules cover
- "!$test"
- "!**/internal/testutil/**/*.go"
- "!**/internal/json/*.go" # client-http covers it
list-mode: strict
deny:
- pkg: log
desc: Use log/slog instead
allow:
- $gostd
- encoding/json/v2
- encoding/json/jsontext
- log/slog
- github.com/meshcloud/meshstack-cli/internal
Expand All @@ -513,7 +516,6 @@ linters:
list-mode: strict
allow:
- $gostd
- encoding/json/v2
- encoding/json/jsontext
- github.com/meshcloud/meshstack-cli
- github.com/stretchr/testify
Expand All @@ -538,17 +540,18 @@ linters:
list-mode: strict
allow:
- $gostd
- github.com/meshcloud/meshstack-cli/internal/json
- github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack

# A test may use every direct dependency in go.mod: the rules above already confine where
# production code uses each one, and a test checks that code with the same libraries.
tests:
files:
- "$test"
- "!**/client/http/*_test.go"
list-mode: strict
allow:
- $gostd
- encoding/json/v2
- encoding/json/jsontext
- github.com/meshcloud/meshstack-cli
- charm.land/bubbles/v2
Expand All @@ -563,3 +566,17 @@ linters:
- github.com/spf13/cobra
- github.com/spf13/pflag
- github.com/stretchr/testify

# client/http breaks connections on purpose, which toxiproxy does in process.
tests-client-http:
files:
- "**/client/http/*_test.go"
list-mode: strict
allow:
- $gostd
- encoding/json/jsontext
- github.com/meshcloud/meshstack-cli
- github.com/stretchr/testify
- github.com/Shopify/toxiproxy/v2
# toxiproxy.NewServer takes a zerolog.Logger, and zerolog.Nop() is the only use
- github.com/rs/zerolog
2 changes: 1 addition & 1 deletion client/building_block_definition_version.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package client
import (
"context"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"uuid"
Expand All @@ -12,6 +11,7 @@ import (
"github.com/meshcloud/meshstack-cli/client/internal"
"github.com/meshcloud/meshstack-cli/client/types"
"github.com/meshcloud/meshstack-cli/client/types/enum"
"github.com/meshcloud/meshstack-cli/internal/json"
)

type MeshBuildingBlockDefinitionVersionState string
Expand Down
2 changes: 1 addition & 1 deletion client/building_block_definition_version_implementation.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package client

import (
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"

"github.com/meshcloud/meshstack-cli/client/types"
"github.com/meshcloud/meshstack-cli/client/types/enum"
"github.com/meshcloud/meshstack-cli/client/types/variant"
"github.com/meshcloud/meshstack-cli/internal/json"
)

type MeshBuildingBlockImplementationType string
Expand Down
2 changes: 1 addition & 1 deletion client/building_block_definition_version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ package client

import (
"embed"
"encoding/json/v2"
"path"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/meshcloud/meshstack-cli/client/types"
"github.com/meshcloud/meshstack-cli/internal/json"
)

//go:embed testdata/building_block_definition_version_input
Expand Down
8 changes: 3 additions & 5 deletions client/building_block_run_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package client
import (
"context"
"fmt"
gohttp "net/http"
"net/url"

"github.com/meshcloud/meshstack-cli/client/http"
Expand Down Expand Up @@ -49,7 +48,7 @@ func (c *MeshBuildingBlockRunActionClient) ReadLogs(ctx context.Context, link Li
// ApproveRun takes the predecessor because meshStack replaces the plan of a run that waits for
// approval when the run is planned again. The predecessor names the plan that is approved.
func (c *MeshBuildingBlockRunActionClient) ApproveRun(ctx context.Context, approve Link, predecessorRunUuid string) error {
_, err := c.doAtLink[[]byte](ctx, http.MethodPost, approve, http.WithJsonPayload(struct {
_, err := c.doAtLink[struct{}](ctx, http.MethodPost, approve, http.WithJsonRequest(struct {
PredecessorRunUuid string `json:"predecessorRunUuid"`
}{predecessorRunUuid}, c.run.MeshObjectMimeType()))
return err
Expand All @@ -64,8 +63,7 @@ func (c *MeshBuildingBlockRunActionClient) AbortRun(ctx context.Context, abort L
}

func (c *MeshBuildingBlockRunActionClient) postWithoutBody(ctx context.Context, link Link) error {
_, err := c.doAtLink[[]byte](ctx, http.MethodPost, link,
http.WithHeaders(gohttp.Header{"Content-Type": {c.run.MeshObjectMimeType()}}))
_, err := c.doAtLink[struct{}](ctx, http.MethodPost, link, http.WithContentType(c.run.MeshObjectMimeType()))
return err
}

Expand All @@ -84,5 +82,5 @@ func (c *MeshBuildingBlockRunActionClient) doAtLink[R any](ctx context.Context,
}
below := c.httpClient.EndpointUrl.JoinPath(path)
below.RawQuery = target.RawQuery
return c.httpClient.DoRequest[R](ctx, method, below, append(options, http.WithAccept(c.run.MeshObjectMimeType()))...)
return http.UnmarshalJsonBody[R](c.httpClient.DoRequest(ctx, method, below, append(options, http.WithHeader("Accept", c.run.MeshObjectMimeType()))...))
}
2 changes: 1 addition & 1 deletion client/building_block_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package client
import (
"context"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"slices"
Expand All @@ -12,6 +11,7 @@ import (
"github.com/meshcloud/meshstack-cli/client/internal"
"github.com/meshcloud/meshstack-cli/client/types"
"github.com/meshcloud/meshstack-cli/client/types/enum"
"github.com/meshcloud/meshstack-cli/internal/json"
)

type BuildingBlockLifecycleState string
Expand Down
95 changes: 52 additions & 43 deletions client/http/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import (
"context"
"errors"
"fmt"
"io"
"log/slog"
gohttp "net/http"
"net/url"
"strings"
)

// Authorization produces the bearer token for each request. An implementation renews the token
Expand All @@ -19,62 +21,65 @@ type Authorization interface {
// rejected token unchanged tells the caller that there is nothing new to try.
RefreshBearerToken(ctx context.Context, rejected BearerToken) (BearerToken, error)

// Scope names what meshStack grants access by, so that a 403 says it. Empty names nothing.
Scope() string
}

func (c Client) WithAuthorization(auth Authorization) AuthorizedClient {
return AuthorizedClient{c, auth}
fmt.Stringer
}

type AuthorizedClient struct {
Client

Authorization Authorization
client Client
auth Authorization
}

func (c AuthorizedClient) DoRequest[R any](ctx context.Context, method string, url *url.URL, options ...RequestOption) (R, error) {
result, err := withBearerToken(ctx, c.Authorization, method, url, func(token RequestOption) (R, error) {
return c.Client.DoRequest[R](ctx, method, url, append(options, token)...)
})
if httpErr, ok := errors.AsType[Error](err); ok && httpErr.IsForbidden() && c.Authorization.Scope() != "" {
err = fmt.Errorf("auth scope %s: %w", c.Authorization.Scope(), err)
}
return result, err
func (c Client) WithAuthorization(auth Authorization) AuthorizedClient {
return AuthorizedClient{c, auth}
}

// Authorize is for a request that this client does not send itself, such as one a reverse proxy
// passes on. Such a request gets no second try after a 401.
func (c AuthorizedClient) Authorize(r *gohttp.Request) error {
token, err := c.Authorization.GetBearerToken(r.Context())
func (c AuthorizedClient) DoRequest(ctx context.Context, method string, url *url.URL, options ...RequestOption) (io.ReadCloser, error) {
token, err := c.auth.GetBearerToken(ctx)
if err != nil {
return err
}
r.Header.Set("Authorization", "Bearer "+string(token))
return nil
}

func withBearerToken[R any](ctx context.Context, auth Authorization, method string, url *url.URL, send func(token RequestOption) (R, error)) (result R, err error) {
token, tokenErr := auth.GetBearerToken(ctx)
if tokenErr != nil {
return result, tokenErr
return nil, err
}
result, err = send(token.asRequestOption())

body, err := c.client.DoRequest(ctx, method, url, append(options, token.asRequestOption())...)
if httpErr, ok := errors.AsType[Error](err); ok && httpErr.IsUnauthorized() {
// Clock skew between this machine and the server can make a token look valid here and
// expired there, so one 401 earns one retry with a freshly minted token.
refreshedToken, refreshErr := auth.RefreshBearerToken(ctx, token)
refreshedToken, refreshErr := c.auth.RefreshBearerToken(ctx, token)
switch {
case refreshErr != nil:
return result, errors.Join(err, fmt.Errorf("cannot renew the rejected token: %w", refreshErr))
case refreshedToken == token:
return result, err
err = errors.Join(err, fmt.Errorf("cannot renew the rejected token: %w", refreshErr))
case refreshedToken != token:
slog.DebugContext(ctx, "retrying after 401 with a freshly minted token", "url", url.String(), "method", method)
body, err = c.client.DoRequest(ctx, method, url, append(options, refreshedToken.asRequestOption())...)
}
slog.DebugContext(ctx, "retrying after 401 with a freshly minted token", "url", url.String(), "method", method)
return send(refreshedToken.asRequestOption())
}
return result, err
if httpErr, ok := errors.AsType[Error](err); ok && httpErr.IsForbidden() {
err = fmt.Errorf("auth %s: %w", c.auth, err)
}
return body, err
}

func (c AuthorizedClient) String() string {
return "authorized client " + c.client.userAgent.String()
}

func (c AuthorizedClient) ProxyTransport() gohttp.RoundTripper {
return proxyTransport{c}
}

type proxyTransport struct {
AuthorizedClient
}

func (t proxyTransport) RoundTrip(in *gohttp.Request) (*gohttp.Response, error) {
out := in.Clone(in.Context())
out.Header.Set("User-Agent", strings.TrimSpace(in.Header.Get("User-Agent")+" "+t.client.userAgent.String()))
if in.Header.Get("Authorization") != "" {
token, err := t.auth.GetBearerToken(in.Context())
if err != nil {
return nil, err
}
out.Header.Set("Authorization", "Bearer "+string(token))
}
return goClient.Transport.RoundTrip(out)
}

// BearerToken is both the token Authorization produces and an Authorization of its own, for a
Expand All @@ -89,10 +94,14 @@ func (token BearerToken) RefreshBearerToken(_ context.Context, _ BearerToken) (B
return "", fmt.Errorf("cannot renew %T", token)
}

func (token BearerToken) Scope() string {
return ""
// String shows only the start of a long token, so that formatting one never leaks it.
func (token BearerToken) String() string {
if len(token) < 32 {
return "BearerToken [REDACTED]"
}
return "BearerToken " + string(token[:6]) + "...[REDACTED]"
}

func (token BearerToken) asRequestOption() RequestOption {
return withHeader("Authorization", fmt.Sprintf("Bearer %s", token))
return WithHeader("Authorization", "Bearer "+string(token))
}
Loading
Loading