Skip to content

chore: shorten provisioner key #14017

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 7 commits into from
Jul 25, 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
4 changes: 4 additions & 0 deletions coderd/database/dbauthz/dbauthz.go
Original file line number Diff line number Diff line change
Expand Up @@ -1680,6 +1680,10 @@ func (q *querier) GetProvisionerJobsCreatedAfter(ctx context.Context, createdAt
return q.db.GetProvisionerJobsCreatedAfter(ctx, createdAt)
}

func (q *querier) GetProvisionerKeyByHashedSecret(ctx context.Context, hashedSecret []byte) (database.ProvisionerKey, error) {
return fetch(q.log, q.auth, q.db.GetProvisionerKeyByHashedSecret)(ctx, hashedSecret)
}

func (q *querier) GetProvisionerKeyByID(ctx context.Context, id uuid.UUID) (database.ProvisionerKey, error) {
return fetch(q.log, q.auth, q.db.GetProvisionerKeyByID)(ctx, id)
}
Expand Down
5 changes: 5 additions & 0 deletions coderd/database/dbauthz/dbauthz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1825,6 +1825,11 @@ func (s *MethodTestSuite) TestProvisionerKeys() {
pk := dbgen.ProvisionerKey(s.T(), db, database.ProvisionerKey{OrganizationID: org.ID})
check.Args(pk.ID).Asserts(pk, policy.ActionRead).Returns(pk)
}))
s.Run("GetProvisionerKeyByHashedSecret", s.Subtest(func(db database.Store, check *expects) {
org := dbgen.Organization(s.T(), db, database.Organization{})
pk := dbgen.ProvisionerKey(s.T(), db, database.ProvisionerKey{OrganizationID: org.ID, HashedSecret: []byte("foo")})
check.Args([]byte("foo")).Asserts(pk, policy.ActionRead).Returns(pk)
}))
s.Run("GetProvisionerKeyByName", s.Subtest(func(db database.Store, check *expects) {
org := dbgen.Organization(s.T(), db, database.Organization{})
pk := dbgen.ProvisionerKey(s.T(), db, database.ProvisionerKey{OrganizationID: org.ID})
Expand Down
13 changes: 13 additions & 0 deletions coderd/database/dbmem/dbmem.go
Original file line number Diff line number Diff line change
Expand Up @@ -3240,6 +3240,19 @@ func (q *FakeQuerier) GetProvisionerJobsCreatedAfter(_ context.Context, after ti
return jobs, nil
}

func (q *FakeQuerier) GetProvisionerKeyByHashedSecret(_ context.Context, hashedSecret []byte) (database.ProvisionerKey, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()

for _, key := range q.provisionerKeys {
if bytes.Equal(key.HashedSecret, hashedSecret) {
return key, nil
}
}

return database.ProvisionerKey{}, sql.ErrNoRows
}

func (q *FakeQuerier) GetProvisionerKeyByID(_ context.Context, id uuid.UUID) (database.ProvisionerKey, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()
Expand Down
7 changes: 7 additions & 0 deletions coderd/database/dbmetrics/dbmetrics.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions coderd/database/dbmock/dbmock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions coderd/database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions coderd/database/queries/provisionerkeys.sql
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ FROM
WHERE
id = $1;

-- name: GetProvisionerKeyByHashedSecret :one
SELECT
*
FROM
provisioner_keys
WHERE
hashed_secret = $1;

-- name: GetProvisionerKeyByName :one
SELECT
*
Expand Down
14 changes: 8 additions & 6 deletions coderd/httpmw/provisionerdaemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,17 @@ func ExtractProvisionerDaemonAuthenticated(opts ExtractProvisionerAuthConfig) fu
return
}

id, keyValue, err := provisionerkey.Parse(key)
err := provisionerkey.Validate(key)
if err != nil {
handleOptional(http.StatusUnauthorized, codersdk.Response{
handleOptional(http.StatusBadRequest, codersdk.Response{
Message: "provisioner daemon key invalid",
Detail: err.Error(),
})
return
}

hashedKey := provisionerkey.HashSecret(key)
// nolint:gocritic // System must check if the provisioner key is valid.
pk, err := opts.DB.GetProvisionerKeyByID(dbauthz.AsSystemRestricted(ctx), id)
pk, err := opts.DB.GetProvisionerKeyByHashedSecret(dbauthz.AsSystemRestricted(ctx), hashedKey)
if err != nil {
if httpapi.Is404Error(err) {
handleOptional(http.StatusUnauthorized, codersdk.Response{
Expand All @@ -90,12 +91,13 @@ func ExtractProvisionerDaemonAuthenticated(opts ExtractProvisionerAuthConfig) fu
}

handleOptional(http.StatusInternalServerError, codersdk.Response{
Message: "get provisioner daemon key: " + err.Error(),
Message: "get provisioner daemon key",
Detail: err.Error(),
})
return
}

if provisionerkey.Compare(pk.HashedSecret, provisionerkey.HashSecret(keyValue)) {
if provisionerkey.Compare(pk.HashedSecret, hashedKey) {
handleOptional(http.StatusUnauthorized, codersdk.Response{
Message: "provisioner daemon key invalid",
})
Expand Down
33 changes: 13 additions & 20 deletions coderd/provisionerkey/provisionerkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package provisionerkey
import (
"crypto/sha256"
"crypto/subtle"
"fmt"
"strings"

"github.com/google/uuid"
"golang.org/x/xerrors"
Expand All @@ -14,41 +12,36 @@ import (
"github.com/coder/coder/v2/cryptorand"
)

const (
secretLength = 43
)

func New(organizationID uuid.UUID, name string, tags map[string]string) (database.InsertProvisionerKeyParams, string, error) {
id := uuid.New()
secret, err := cryptorand.HexString(64)
secret, err := cryptorand.String(secretLength)
if err != nil {
return database.InsertProvisionerKeyParams{}, "", xerrors.Errorf("generate token: %w", err)
return database.InsertProvisionerKeyParams{}, "", xerrors.Errorf("generate secret: %w", err)
}
hashedSecret := HashSecret(secret)
token := fmt.Sprintf("%s:%s", id, secret)

if tags == nil {
tags = map[string]string{}
}

return database.InsertProvisionerKeyParams{
ID: id,
ID: uuid.New(),
CreatedAt: dbtime.Now(),
OrganizationID: organizationID,
Name: name,
HashedSecret: hashedSecret,
HashedSecret: HashSecret(secret),
Tags: tags,
}, token, nil
}, secret, nil
}

func Parse(token string) (uuid.UUID, string, error) {
parts := strings.Split(token, ":")
if len(parts) != 2 {
return uuid.UUID{}, "", xerrors.Errorf("invalid token format")
}

id, err := uuid.Parse(parts[0])
if err != nil {
return uuid.UUID{}, "", xerrors.Errorf("parse id: %w", err)
func Validate(token string) error {
if len(token) != secretLength {
return xerrors.Errorf("must be %d characters", secretLength)
}

return id, parts[1], nil
return nil
}

func HashSecret(secret string) []byte {
Expand Down
4 changes: 2 additions & 2 deletions enterprise/cli/provisionerdaemonstart.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,9 @@ func (r *RootCmd) provisionerDaemonStart() *serpent.Command {
if len(rawTags) > 0 {
return xerrors.New("cannot provide tags when using provisioner key")
}
_, _, err := provisionerkey.Parse(provisionerKey)
err = provisionerkey.Validate(provisionerKey)
if err != nil {
return xerrors.Errorf("parse provisioner key: %w", err)
return xerrors.Errorf("validate provisioner key: %w", err)
}
}

Expand Down
7 changes: 2 additions & 5 deletions enterprise/cli/provisionerkeys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"strings"
"testing"

"github.com/google/uuid"
"github.com/stretchr/testify/require"

"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/provisionerkey"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/enterprise/coderd/coderdenttest"
Expand Down Expand Up @@ -58,10 +58,7 @@ func TestProvisionerKeys(t *testing.T) {
_ = pty.ReadLine(ctx)
key := pty.ReadLine(ctx)
require.NotEmpty(t, key)
parts := strings.Split(key, ":")
require.Len(t, parts, 2, "expected 2 parts")
_, err = uuid.Parse(parts[0])
require.NoError(t, err, "expected token to be a uuid")
require.NoError(t, provisionerkey.Validate(key))

inv, conf = newCLI(
t,
Expand Down
29 changes: 2 additions & 27 deletions enterprise/coderd/provisionerdaemons_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"fmt"
"io"
"net/http"
"strings"
"testing"

"github.com/google/uuid"
Expand Down Expand Up @@ -612,36 +611,12 @@ func TestProvisionerDaemonServe(t *testing.T) {
errStatusCode: http.StatusUnauthorized,
},
{
name: "WrongKey",
name: "InvalidKey",
multiOrgFeatureEnabled: true,
multiOrgExperimentEnabled: true,
insertParams: insertParams,
requestProvisionerKey: "provisionersftw",
errStatusCode: http.StatusUnauthorized,
},
{
name: "IdOKKeyValueWrong",
multiOrgFeatureEnabled: true,
multiOrgExperimentEnabled: true,
insertParams: insertParams,
requestProvisionerKey: insertParams.ID.String() + ":" + "wrong",
errStatusCode: http.StatusUnauthorized,
},
{
name: "IdWrongKeyValueOK",
multiOrgFeatureEnabled: true,
multiOrgExperimentEnabled: true,
insertParams: insertParams,
requestProvisionerKey: uuid.NewString() + ":" + token,
errStatusCode: http.StatusUnauthorized,
},
{
name: "KeyValueOnly",
multiOrgFeatureEnabled: true,
multiOrgExperimentEnabled: true,
insertParams: insertParams,
requestProvisionerKey: strings.Split(token, ":")[1],
errStatusCode: http.StatusUnauthorized,
errStatusCode: http.StatusBadRequest,
},
{
name: "KeyAndPSK",
Expand Down
Loading