Skip to content

chore: move agent functions from codersdk into agentsdk #5903

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

Merged
merged 19 commits into from
Jan 29, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
chore: remove BypassRatelimits option in codersdk.Client
It feels wrong to have this as a direct option because it's so infrequently
needed by API callers. It's better to directly modify headers in the two
places that we actually use it.
  • Loading branch information
kylecarbs committed Jan 29, 2023
commit b9a0e2eeacf7117b6975a110619cfd97c75adb8f
19 changes: 17 additions & 2 deletions cli/scaletest.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
Expand Down Expand Up @@ -328,7 +329,14 @@ func scaletestCleanup() *cobra.Command {
return err
}

client.BypassRatelimits = true
client.HTTPClient = &http.Client{
Transport: &headerTransport{
transport: http.DefaultTransport,
headers: map[string]string{
codersdk.BypassRatelimitHeader: "true",
},
},
}

cmd.PrintErrln("Fetching scaletest workspaces...")
var (
Expand Down Expand Up @@ -506,7 +514,14 @@ It is recommended that all rate limits are disabled on the server before running
return err
}

client.BypassRatelimits = true
client.HTTPClient = &http.Client{
Transport: &headerTransport{
transport: http.DefaultTransport,
headers: map[string]string{
codersdk.BypassRatelimitHeader: "true",
},
},
}

if count <= 0 {
return xerrors.Errorf("--count is required and must be greater than 0")
Expand Down
2 changes: 1 addition & 1 deletion cli/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func createToken() *cobra.Command {
cmd.Println(cliui.Styles.Code.Render(strings.TrimSpace(res.Key)))
cmd.Println()
cmd.Println(cliui.Styles.Wrap.Render(
fmt.Sprintf("You can use this token by setting the --%s CLI flag, the %s environment variable, or the %q HTTP header.", varToken, envSessionToken, codersdk.SessionCustomHeader),
fmt.Sprintf("You can use this token by setting the --%s CLI flag, the %s environment variable, or the %q HTTP header.", varToken, envSessionToken, codersdk.SessionTokenHeader),
))

return nil
Expand Down
2 changes: 1 addition & 1 deletion coderd/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ func (api *API) createAPIKey(ctx context.Context, params createAPIKeyParams) (*h
// This format is consumed by the APIKey middleware.
sessionToken := fmt.Sprintf("%s-%s", keyID, keySecret)
return &http.Cookie{
Name: codersdk.SessionTokenKey,
Name: codersdk.SessionTokenCookie,
Value: sessionToken,
Path: "/",
HttpOnly: true,
Expand Down
2 changes: 1 addition & 1 deletion coderd/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ func (api *API) convertAuditLog(ctx context.Context, dblog database.GetAuditLogs

func auditLogDescription(alog database.GetAuditLogsOffsetRow, additionalFields AdditionalFields) string {
str := fmt.Sprintf("{user} %s",
codersdk.AuditAction(alog.Action).FriendlyString(),
codersdk.AuditAction(alog.Action).Friendly(),
)

// Strings for starting/stopping workspace builds follow the below format:
Expand Down
2 changes: 1 addition & 1 deletion coderd/authorize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ func TestCheckPermissions(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
t.Cleanup(cancel)

resp, err := c.Client.CheckAuthorization(ctx, codersdk.AuthorizationRequest{Checks: params})
resp, err := c.Client.AuthCheck(ctx, codersdk.AuthorizationRequest{Checks: params})
require.NoError(t, err, "check perms")
require.Equal(t, c.Check, resp)
})
Expand Down
6 changes: 3 additions & 3 deletions coderd/httpapi/cookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ func StripCoderCookies(header string) string {
continue
}
name, _, _ := strings.Cut(part, "=")
if name == codersdk.SessionTokenKey ||
name == codersdk.OAuth2StateKey ||
name == codersdk.OAuth2RedirectKey {
if name == codersdk.SessionTokenCookie ||
name == codersdk.OAuth2StateCookie ||
name == codersdk.OAuth2RedirectCookie {
continue
}
cookies = append(cookies, part)
Expand Down
8 changes: 4 additions & 4 deletions coderd/httpmw/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func ExtractAPIKey(cfg ExtractAPIKeyConfig) func(http.Handler) http.Handler {
if token == "" {
optionalWrite(http.StatusUnauthorized, codersdk.Response{
Message: SignedOutErrorMessage,
Detail: fmt.Sprintf("Cookie %q or query parameter must be provided.", codersdk.SessionTokenKey),
Detail: fmt.Sprintf("Cookie %q or query parameter must be provided.", codersdk.SessionTokenCookie),
})
return
}
Expand Down Expand Up @@ -364,17 +364,17 @@ func ExtractAPIKey(cfg ExtractAPIKeyConfig) func(http.Handler) http.Handler {
// 4. The coder_session_token query parameter
// 5. The custom auth header
func apiTokenFromRequest(r *http.Request) string {
cookie, err := r.Cookie(codersdk.SessionTokenKey)
cookie, err := r.Cookie(codersdk.SessionTokenCookie)
if err == nil && cookie.Value != "" {
return cookie.Value
}

urlValue := r.URL.Query().Get(codersdk.SessionTokenKey)
urlValue := r.URL.Query().Get(codersdk.SessionTokenCookie)
if urlValue != "" {
return urlValue
}

headerValue := r.Header.Get(codersdk.SessionCustomHeader)
headerValue := r.Header.Get(codersdk.SessionTokenHeader)
if headerValue != "" {
return headerValue
}
Expand Down
30 changes: 15 additions & 15 deletions coderd/httpmw/apikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func TestAPIKey(t *testing.T) {
r = httptest.NewRequest("GET", "/", nil)
rw = httptest.NewRecorder()
)
r.Header.Set(codersdk.SessionCustomHeader, "test-wow-hello")
r.Header.Set(codersdk.SessionTokenHeader, "test-wow-hello")

httpmw.ExtractAPIKey(httpmw.ExtractAPIKeyConfig{
DB: db,
Expand All @@ -100,7 +100,7 @@ func TestAPIKey(t *testing.T) {
r = httptest.NewRequest("GET", "/", nil)
rw = httptest.NewRecorder()
)
r.Header.Set(codersdk.SessionCustomHeader, "test-wow")
r.Header.Set(codersdk.SessionTokenHeader, "test-wow")

httpmw.ExtractAPIKey(httpmw.ExtractAPIKeyConfig{
DB: db,
Expand All @@ -118,7 +118,7 @@ func TestAPIKey(t *testing.T) {
r = httptest.NewRequest("GET", "/", nil)
rw = httptest.NewRecorder()
)
r.Header.Set(codersdk.SessionCustomHeader, "testtestid-wow")
r.Header.Set(codersdk.SessionTokenHeader, "testtestid-wow")

httpmw.ExtractAPIKey(httpmw.ExtractAPIKeyConfig{
DB: db,
Expand All @@ -137,7 +137,7 @@ func TestAPIKey(t *testing.T) {
r = httptest.NewRequest("GET", "/", nil)
rw = httptest.NewRecorder()
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

httpmw.ExtractAPIKey(httpmw.ExtractAPIKeyConfig{
DB: db,
Expand All @@ -157,7 +157,7 @@ func TestAPIKey(t *testing.T) {
rw = httptest.NewRecorder()
user = createUser(r.Context(), t, db)
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

// Use a different secret so they don't match!
hashed := sha256.Sum256([]byte("differentsecret"))
Expand Down Expand Up @@ -188,7 +188,7 @@ func TestAPIKey(t *testing.T) {
rw = httptest.NewRecorder()
user = createUser(r.Context(), t, db)
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

_, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
ID: id,
Expand Down Expand Up @@ -217,7 +217,7 @@ func TestAPIKey(t *testing.T) {
rw = httptest.NewRecorder()
user = createUser(r.Context(), t, db)
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

sentAPIKey, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
ID: id,
Expand Down Expand Up @@ -259,7 +259,7 @@ func TestAPIKey(t *testing.T) {
user = createUser(r.Context(), t, db)
)
r.AddCookie(&http.Cookie{
Name: codersdk.SessionTokenKey,
Name: codersdk.SessionTokenCookie,
Value: fmt.Sprintf("%s-%s", id, secret),
})

Expand Down Expand Up @@ -302,7 +302,7 @@ func TestAPIKey(t *testing.T) {
user = createUser(r.Context(), t, db)
)
q := r.URL.Query()
q.Add(codersdk.SessionTokenKey, fmt.Sprintf("%s-%s", id, secret))
q.Add(codersdk.SessionTokenCookie, fmt.Sprintf("%s-%s", id, secret))
r.URL.RawQuery = q.Encode()

_, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
Expand Down Expand Up @@ -339,7 +339,7 @@ func TestAPIKey(t *testing.T) {
rw = httptest.NewRecorder()
user = createUser(r.Context(), t, db)
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

sentAPIKey, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
ID: id,
Expand Down Expand Up @@ -376,7 +376,7 @@ func TestAPIKey(t *testing.T) {
rw = httptest.NewRecorder()
user = createUser(r.Context(), t, db)
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

sentAPIKey, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
ID: id,
Expand Down Expand Up @@ -413,7 +413,7 @@ func TestAPIKey(t *testing.T) {
rw = httptest.NewRecorder()
user = createUser(r.Context(), t, db)
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

sentAPIKey, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
ID: id,
Expand Down Expand Up @@ -457,7 +457,7 @@ func TestAPIKey(t *testing.T) {
rw = httptest.NewRecorder()
user = createUser(r.Context(), t, db)
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

sentAPIKey, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
ID: id,
Expand Down Expand Up @@ -514,7 +514,7 @@ func TestAPIKey(t *testing.T) {
user = createUser(r.Context(), t, db)
)
r.RemoteAddr = "1.1.1.1"
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

_, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
ID: id,
Expand Down Expand Up @@ -602,7 +602,7 @@ func TestAPIKey(t *testing.T) {
rw = httptest.NewRecorder()
user = createUser(r.Context(), t, db)
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

sentAPIKey, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
ID: id,
Expand Down
2 changes: 1 addition & 1 deletion coderd/httpmw/authorize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ func TestExtractUserRoles(t *testing.T) {
})

req := httptest.NewRequest("GET", "/", nil)
req.Header.Set(codersdk.SessionCustomHeader, token)
req.Header.Set(codersdk.SessionTokenHeader, token)

rtr.ServeHTTP(rw, req)
resp := rw.Result()
Expand Down
6 changes: 3 additions & 3 deletions coderd/httpmw/csrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,19 @@ func CSRF(secureCookie bool) func(next http.Handler) http.Handler {
// CSRF only affects requests that automatically attach credentials via a cookie.
// If no cookie is present, then there is no risk of CSRF.
//nolint:govet
sessCookie, err := r.Cookie(codersdk.SessionTokenKey)
sessCookie, err := r.Cookie(codersdk.SessionTokenCookie)
if xerrors.Is(err, http.ErrNoCookie) {
return true
}

if token := r.Header.Get(codersdk.SessionCustomHeader); token == sessCookie.Value {
if token := r.Header.Get(codersdk.SessionTokenHeader); token == sessCookie.Value {
// If the cookie and header match, we can assume this is the same as just using the
// custom header auth. Custom header auth can bypass CSRF, as CSRF attacks
// cannot add custom headers.
return true
}

if token := r.URL.Query().Get(codersdk.SessionTokenKey); token == sessCookie.Value {
if token := r.URL.Query().Get(codersdk.SessionTokenCookie); token == sessCookie.Value {
// If the auth is set in a url param and matches the cookie, it
// is the same as just using the url param.
return true
Expand Down
10 changes: 5 additions & 5 deletions coderd/httpmw/oauth2.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func ExtractOAuth2(config OAuth2Config, client *http.Client) func(http.Handler)
}

http.SetCookie(rw, &http.Cookie{
Name: codersdk.OAuth2StateKey,
Name: codersdk.OAuth2StateCookie,
Value: state,
Path: "/",
HttpOnly: true,
Expand All @@ -80,7 +80,7 @@ func ExtractOAuth2(config OAuth2Config, client *http.Client) func(http.Handler)
// Redirect must always be specified, otherwise
// an old redirect could apply!
http.SetCookie(rw, &http.Cookie{
Name: codersdk.OAuth2RedirectKey,
Name: codersdk.OAuth2RedirectCookie,
Value: r.URL.Query().Get("redirect"),
Path: "/",
HttpOnly: true,
Expand All @@ -98,10 +98,10 @@ func ExtractOAuth2(config OAuth2Config, client *http.Client) func(http.Handler)
return
}

stateCookie, err := r.Cookie(codersdk.OAuth2StateKey)
stateCookie, err := r.Cookie(codersdk.OAuth2StateCookie)
if err != nil {
httpapi.Write(ctx, rw, http.StatusUnauthorized, codersdk.Response{
Message: fmt.Sprintf("Cookie %q must be provided.", codersdk.OAuth2StateKey),
Message: fmt.Sprintf("Cookie %q must be provided.", codersdk.OAuth2StateCookie),
})
return
}
Expand All @@ -113,7 +113,7 @@ func ExtractOAuth2(config OAuth2Config, client *http.Client) func(http.Handler)
}

var redirect string
stateRedirect, err := r.Cookie(codersdk.OAuth2RedirectKey)
stateRedirect, err := r.Cookie(codersdk.OAuth2RedirectCookie)
if err == nil {
redirect = stateRedirect.Value
}
Expand Down
4 changes: 2 additions & 2 deletions coderd/httpmw/oauth2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestOAuth2(t *testing.T) {
t.Parallel()
req := httptest.NewRequest("GET", "/?code=something&state=test", nil)
req.AddCookie(&http.Cookie{
Name: codersdk.OAuth2StateKey,
Name: codersdk.OAuth2StateCookie,
Value: "mismatch",
})
res := httptest.NewRecorder()
Expand All @@ -84,7 +84,7 @@ func TestOAuth2(t *testing.T) {
t.Parallel()
req := httptest.NewRequest("GET", "/?code=test&state=something", nil)
req.AddCookie(&http.Cookie{
Name: codersdk.OAuth2StateKey,
Name: codersdk.OAuth2StateCookie,
Value: "something",
})
req.AddCookie(&http.Cookie{
Expand Down
2 changes: 1 addition & 1 deletion coderd/httpmw/organizationparam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestOrganizationParam(t *testing.T) {
r = httptest.NewRequest("GET", "/", nil)
hashed = sha256.Sum256([]byte(secret))
)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

userID := uuid.New()
username, err := cryptorand.String(8)
Expand Down
6 changes: 3 additions & 3 deletions coderd/httpmw/ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func TestRateLimit(t *testing.T) {

// Bypass must fail
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set(codersdk.SessionCustomHeader, key)
req.Header.Set(codersdk.SessionTokenHeader, key)
req.Header.Set(codersdk.BypassRatelimitHeader, "true")
rec := httptest.NewRecorder()
// Assert we're not using IP address.
Expand All @@ -123,7 +123,7 @@ func TestRateLimit(t *testing.T) {

require.Eventually(t, func() bool {
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set(codersdk.SessionCustomHeader, key)
req.Header.Set(codersdk.SessionTokenHeader, key)
rec := httptest.NewRecorder()
// Assert we're not using IP address.
req.RemoteAddr = randRemoteAddr()
Expand Down Expand Up @@ -160,7 +160,7 @@ func TestRateLimit(t *testing.T) {

require.Never(t, func() bool {
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set(codersdk.SessionCustomHeader, key)
req.Header.Set(codersdk.SessionTokenHeader, key)
req.Header.Set(codersdk.BypassRatelimitHeader, "true")
rec := httptest.NewRecorder()
// Assert we're not using IP address.
Expand Down
2 changes: 1 addition & 1 deletion coderd/httpmw/templateparam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestTemplateParam(t *testing.T) {
hashed = sha256.Sum256([]byte(secret))
)
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

userID := uuid.New()
username, err := cryptorand.String(8)
Expand Down
2 changes: 1 addition & 1 deletion coderd/httpmw/templateversionparam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestTemplateVersionParam(t *testing.T) {
hashed = sha256.Sum256([]byte(secret))
)
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set(codersdk.SessionCustomHeader, fmt.Sprintf("%s-%s", id, secret))
r.Header.Set(codersdk.SessionTokenHeader, fmt.Sprintf("%s-%s", id, secret))

userID := uuid.New()
username, err := cryptorand.String(8)
Expand Down
Loading