2024-07-16 13:27:12 -04:00
|
|
|
package provisionerkey
|
|
|
|
|
|
|
|
|
|
import (
|
2024-07-25 10:22:55 -04:00
|
|
|
"crypto/subtle"
|
2024-07-16 13:27:12 -04:00
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
|
"golang.org/x/xerrors"
|
|
|
|
|
|
2025-10-23 15:38:49 -05:00
|
|
|
"github.com/coder/coder/v2/coderd/apikey"
|
2024-07-16 13:27:12 -04:00
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
|
|
|
"github.com/coder/coder/v2/coderd/database/dbtime"
|
|
|
|
|
)
|
|
|
|
|
|
2024-07-25 17:08:12 -04:00
|
|
|
const (
|
|
|
|
|
secretLength = 43
|
|
|
|
|
)
|
|
|
|
|
|
2024-07-25 11:20:45 -04:00
|
|
|
func New(organizationID uuid.UUID, name string, tags map[string]string) (database.InsertProvisionerKeyParams, string, error) {
|
2025-10-23 15:38:49 -05:00
|
|
|
secret, hashed, err := apikey.GenerateSecret(secretLength)
|
2024-07-16 13:27:12 -04:00
|
|
|
if err != nil {
|
2024-07-25 17:08:12 -04:00
|
|
|
return database.InsertProvisionerKeyParams{}, "", xerrors.Errorf("generate secret: %w", err)
|
2024-07-16 13:27:12 -04:00
|
|
|
}
|
|
|
|
|
|
2024-07-25 11:20:45 -04:00
|
|
|
if tags == nil {
|
|
|
|
|
tags = map[string]string{}
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-16 13:27:12 -04:00
|
|
|
return database.InsertProvisionerKeyParams{
|
2024-07-25 17:08:12 -04:00
|
|
|
ID: uuid.New(),
|
2024-07-16 13:27:12 -04:00
|
|
|
CreatedAt: dbtime.Now(),
|
|
|
|
|
OrganizationID: organizationID,
|
|
|
|
|
Name: name,
|
2025-10-23 15:38:49 -05:00
|
|
|
HashedSecret: hashed,
|
2024-07-25 11:20:45 -04:00
|
|
|
Tags: tags,
|
2024-07-25 17:08:12 -04:00
|
|
|
}, secret, nil
|
2024-07-16 13:27:12 -04:00
|
|
|
}
|
2024-07-25 10:22:55 -04:00
|
|
|
|
2024-07-25 17:08:12 -04:00
|
|
|
func Validate(token string) error {
|
|
|
|
|
if len(token) != secretLength {
|
|
|
|
|
return xerrors.Errorf("must be %d characters", secretLength)
|
2024-07-25 10:22:55 -04:00
|
|
|
}
|
|
|
|
|
|
2024-07-25 17:08:12 -04:00
|
|
|
return nil
|
2024-07-25 10:22:55 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func HashSecret(secret string) []byte {
|
2025-10-23 15:38:49 -05:00
|
|
|
return apikey.HashSecret(secret)
|
2024-07-25 10:22:55 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func Compare(a []byte, b []byte) bool {
|
|
|
|
|
return subtle.ConstantTimeCompare(a, b) != 1
|
|
|
|
|
}
|