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
38 changes: 14 additions & 24 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,6 @@ linters-settings:
# - whyNoLint
# - wrapperFunc
# - yodaStyleExpr
settings:
ruleguard:
failOn: all
rules: "${configDir}/lib/go/lintrules/*.go"

goimports:
local-prefixes: coder.com,cdr.dev,go.coder.com,github.com/cdr,github.com/coder
Expand All @@ -113,24 +109,6 @@ linters-settings:

importas:
no-unaliased: true
alias:
- pkg: k8s.io/api/(\w+)/(v[\w\d]+)
alias: ${1}${2}

- pkg: k8s.io/apimachinery/pkg/apis/meta/(v[\w\d]+)
alias: meta${1}

- pkg: k8s.io/client-go/kubernetes/typed/(\w+)/(v[\w\d]+)
alias: ${1}${2}client

- pkg: k8s.io/metrics/pkg/apis/metrics/(v[\w\d]+)
alias: metrics${1}

- pkg: github.com/docker/docker/api/types
alias: dockertypes

- pkg: github.com/docker/docker/client
alias: dockerclient

misspell:
locale: US
Expand Down Expand Up @@ -195,6 +173,20 @@ linters-settings:
- name: var-declaration
- name: var-naming
- name: waitgroup-by-value
varnamelen:
ignore-names:
- err
- rw
- r
- i
- db
# Optional list of variable declarations that should be ignored completely. (defaults to empty list)
# Entries must be in the form of "<variable name> <type>" or "<variable name> *<type>" for
# variables, or "const <name>" for constants.
ignore-decls:
- rw http.ResponseWriter
- r *http.Request
- t testing.T

issues:
# Rules listed here: https://github.com/securego/gosec#available-rules
Expand Down Expand Up @@ -222,7 +214,6 @@ linters:
- asciicheck
- bidichk
- bodyclose
- contextcheck
- deadcode
- dogsled
- errcheck
Expand All @@ -239,7 +230,6 @@ linters:
- govet
- importas
- ineffassign
# - ireturn
- makezero
- misspell
- nilnil
Expand Down
2 changes: 1 addition & 1 deletion cmd/coder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ package main
import "fmt"

func main() {
fmt.Println("Hello World!")
_, _ = fmt.Println("Hello World!")
}
2 changes: 1 addition & 1 deletion coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func New(options *Options) http.Handler {
httpmw.ExtractAPIKey(options.Database, nil),
httpmw.ExtractUser(options.Database),
)
r.Get("/user", users.getAuthenticatedUser)
r.Get("/user", users.authenticatedUser)
})
})
r.NotFound(site.Handler().ServeHTTP)
Expand Down
6 changes: 3 additions & 3 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ func New(t *testing.T) Server {
Database: db,
})
srv := httptest.NewServer(handler)
u, err := url.Parse(srv.URL)
serverURL, err := url.Parse(srv.URL)
require.NoError(t, err)
t.Cleanup(srv.Close)

client := codersdk.New(u)
client := codersdk.New(serverURL)
_, err = client.CreateInitialUser(context.Background(), coderd.CreateUserRequest{
Email: "testuser@coder.com",
Username: "testuser",
Expand All @@ -54,6 +54,6 @@ func New(t *testing.T) Server {

return Server{
Client: client,
URL: u,
URL: serverURL,
}
}
6 changes: 3 additions & 3 deletions coderd/userpassword/userpassword.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ func Compare(hashed string, password string) (bool, error) {
if len(parts[0]) != 0 {
return false, xerrors.Errorf("hash prefix is invalid")
}
if string(parts[1]) != hashScheme {
if parts[1] != hashScheme {
return false, xerrors.Errorf("hash isn't %q scheme: %q", hashScheme, parts[1])
}
iter, err := strconv.Atoi(string(parts[2]))
iter, err := strconv.Atoi(parts[2])
if err != nil {
return false, xerrors.Errorf("parse iter from hash: %w", err)
}
salt, err := base64.RawStdEncoding.DecodeString(string(parts[3]))
salt, err := base64.RawStdEncoding.DecodeString(parts[3])
if err != nil {
return false, xerrors.Errorf("decode salt: %w", err)
}
Expand Down
26 changes: 16 additions & 10 deletions coderd/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (users *users) createInitialUser(rw http.ResponseWriter, r *http.Request) {
})
return
}
user, err := users.Database.GetUserByEmailOrUsername(r.Context(), database.GetUserByEmailOrUsernameParams{
_, err = users.Database.GetUserByEmailOrUsername(r.Context(), database.GetUserByEmailOrUsernameParams{
Email: createUser.Email,
Username: createUser.Username,
})
Expand All @@ -91,7 +91,7 @@ func (users *users) createInitialUser(rw http.ResponseWriter, r *http.Request) {
return
}

user, err = users.Database.InsertUser(context.Background(), database.InsertUserParams{
user, err := users.Database.InsertUser(context.Background(), database.InsertUserParams{
ID: uuid.NewString(),
Email: createUser.Email,
HashedPassword: []byte(hashedPassword),
Expand All @@ -111,7 +111,7 @@ func (users *users) createInitialUser(rw http.ResponseWriter, r *http.Request) {
}

// Returns the currently authenticated user.
func (users *users) getAuthenticatedUser(rw http.ResponseWriter, r *http.Request) {
func (*users) authenticatedUser(rw http.ResponseWriter, r *http.Request) {
user := httpmw.User(r)

render.JSON(rw, r, User{
Expand Down Expand Up @@ -158,11 +158,17 @@ func (users *users) loginWithPassword(rw http.ResponseWriter, r *http.Request) {
return
}

id, secret, err := generateAPIKeyIDSecret()
hashed := sha256.Sum256([]byte(secret))
keyID, keySecret, err := generateAPIKeyIDSecret()
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: fmt.Sprintf("generate api key parts: %s", err.Error()),
})
return
}
hashed := sha256.Sum256([]byte(keySecret))

_, err = users.Database.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
ID: id,
ID: keyID,
UserID: user.ID,
ExpiresAt: database.Now().Add(24 * time.Hour),
CreatedAt: database.Now(),
Expand All @@ -178,7 +184,7 @@ func (users *users) loginWithPassword(rw http.ResponseWriter, r *http.Request) {
}

// This format is consumed by the APIKey middleware.
sessionToken := fmt.Sprintf("%s-%s", id, secret)
sessionToken := fmt.Sprintf("%s-%s", keyID, keySecret)
http.SetCookie(rw, &http.Cookie{
Name: httpmw.AuthCookie,
Value: sessionToken,
Expand All @@ -194,14 +200,14 @@ func (users *users) loginWithPassword(rw http.ResponseWriter, r *http.Request) {
}

// Generates a new ID and secret for an API key.
func generateAPIKeyIDSecret() (string, string, error) {
func generateAPIKeyIDSecret() (id string, secret string, err error) {
// Length of an API Key ID.
id, err := cryptorand.String(10)
id, err = cryptorand.String(10)
if err != nil {
return "", "", err
}
// Length of an API Key secret.
secret, err := cryptorand.String(22)
secret, err = cryptorand.String(22)
if err != nil {
return "", "", err
}
Expand Down
3 changes: 2 additions & 1 deletion coderd/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import (
"context"
"testing"

"github.com/stretchr/testify/require"

"github.com/coder/coder/coderd"
"github.com/coder/coder/coderd/coderdtest"
"github.com/stretchr/testify/require"
)

func TestUsers(t *testing.T) {
Expand Down
10 changes: 5 additions & 5 deletions codersdk/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ import (
)

// New creates a Coder client for the provided URL.
func New(url *url.URL) *Client {
func New(serverURL *url.URL) *Client {
return &Client{
url: url,
url: serverURL,
httpClient: &http.Client{},
}
}
Expand Down Expand Up @@ -50,7 +50,7 @@ func (c *Client) SetSessionToken(token string) error {
// request performs an HTTP request with the body provided.
// The caller is responsible for closing the response body.
func (c *Client) request(ctx context.Context, method, path string, body interface{}) (*http.Response, error) {
url, err := c.url.Parse(path)
serverURL, err := c.url.Parse(path)
if err != nil {
return nil, xerrors.Errorf("parse url: %w", err)
}
Expand All @@ -65,7 +65,7 @@ func (c *Client) request(ctx context.Context, method, path string, body interfac
}
}

req, err := http.NewRequestWithContext(ctx, method, url.String(), &buf)
req, err := http.NewRequestWithContext(ctx, method, serverURL.String(), &buf)
if err != nil {
return nil, xerrors.Errorf("create request: %w", err)
}
Expand All @@ -81,7 +81,7 @@ func (c *Client) request(ctx context.Context, method, path string, body interfac
}

// readBodyAsError reads the response as an httpapi.Message, and
// wraps it in a codersdk.Error type for easy marshalling.
// wraps it in a codersdk.Error type for easy marshaling.
func readBodyAsError(res *http.Response) error {
var m httpapi.Response
err := json.NewDecoder(res.Body).Decode(&m)
Expand Down
2 changes: 1 addition & 1 deletion codersdk/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func (c *Client) CreateInitialUser(ctx context.Context, req coderd.CreateUserReq

// User returns a user for the ID provided.
// If the ID string is empty, the current user will be returned.
func (c *Client) User(ctx context.Context, id string) (coderd.User, error) {
func (c *Client) User(ctx context.Context, _ string) (coderd.User, error) {
res, err := c.request(ctx, http.MethodGet, "/api/v2/user", nil)
if err != nil {
return coderd.User{}, err
Expand Down
3 changes: 2 additions & 1 deletion codersdk/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import (
"net/http"
"testing"

"github.com/stretchr/testify/require"

"github.com/coder/coder/coderd"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/codersdk"
"github.com/stretchr/testify/require"
)

func TestUsers(t *testing.T) {
Expand Down
31 changes: 16 additions & 15 deletions cryptorand/numbers.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,42 +73,43 @@ func Int() (int, error) {
return int(i), nil
}

// Int63n returns a non-negative random integer in [0,n) as a int64.
func Int63n(n int64) (int64, error) {
if n <= 0 {
// Int63n returns a non-negative random integer in [0,max) as a int64.
func Int63n(max int64) (int64, error) {
if max <= 0 {
panic("invalid argument to Int63n")
}

max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
trueMax := int64((1 << 63) - 1 - (1<<63)%uint64(max))
i, err := Int63()
if err != nil {
return 0, err
}

for i > max {
for i > trueMax {
i, err = Int63()
if err != nil {
return 0, err
}
}

return i % n, nil
return i % max, nil
}

// Int31n returns a non-negative integer in [0,n) as a int32.
func Int31n(n int32) (int32, error) {
// Int31n returns a non-negative integer in [0,max) as a int32.
func Int31n(max int32) (int32, error) {
i, err := Uint32()
if err != nil {
return 0, err
}

return UnbiasedModulo32(i, n)
return UnbiasedModulo32(i, max)
}

// UnbiasedModulo32 uniformly modulos v by n over a sufficiently large data
// set, regenerating v if necessary. n must be > 0. All input bits in v must be
// fully random, you cannot cast a random uint8/uint16 for input into this
// function.
//nolint:varnamelen
func UnbiasedModulo32(v uint32, n int32) (int32, error) {
prod := uint64(v) * uint64(n)
low := uint32(prod)
Expand All @@ -127,22 +128,22 @@ func UnbiasedModulo32(v uint32, n int32) (int32, error) {
return int32(prod >> 32), nil
}

// Intn returns a non-negative integer in [0,n) as a int.
func Intn(n int) (int, error) {
if n <= 0 {
// Intn returns a non-negative integer in [0,max) as a int.
func Intn(max int) (int, error) {
if max <= 0 {
panic("n must be a positive nonzero number")
}

if n <= 1<<31-1 {
i, err := Int31n(int32(n))
if max <= 1<<31-1 {
i, err := Int31n(int32(max))
if err != nil {
return 0, err
}

return int(i), nil
}

i, err := Int63n(int64(n))
i, err := Int63n(int64(max))
if err != nil {
return 0, err
}
Expand Down
5 changes: 3 additions & 2 deletions cryptorand/numbers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import (
"encoding/binary"
"testing"

"github.com/coder/coder/cryptorand"
"github.com/stretchr/testify/require"

"github.com/coder/coder/cryptorand"
)

func TestInt63(t *testing.T) {
Expand Down Expand Up @@ -144,7 +145,7 @@ func TestBool(t *testing.T) {
const iterations = 10000
trueCount := 0

for i := 0; i < iterations; i += 1 {
for i := 0; i < iterations; i++ {
v, err := cryptorand.Bool()
require.NoError(t, err, "unexpected error from Bool")
if v {
Expand Down
4 changes: 2 additions & 2 deletions cryptorand/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ func StringCharset(charSetStr string, size int) (string, error) {
buf.Grow(size)

for i := 0; i < size; i++ {
c, err := UnbiasedModulo32(
count, err := UnbiasedModulo32(
binary.BigEndian.Uint32(ibuf[i*4:(i+1)*4]),
int32(len(charSet)),
)
if err != nil {
return "", err
}

_, _ = buf.WriteRune(charSet[c])
_, _ = buf.WriteRune(charSet[count])
}

return buf.String(), nil
Expand Down
Loading