mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
chore: add provisioner key crud apis (#13857)
This commit is contained in:
@@ -205,7 +205,7 @@ func New(ctx context.Context, options *Options) (_ *API, err error) {
|
||||
})
|
||||
r.Route("/workspaceproxies", func(r chi.Router) {
|
||||
r.Use(
|
||||
api.moonsEnabledMW,
|
||||
api.RequireFeatureMW(codersdk.FeatureWorkspaceProxy),
|
||||
)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(
|
||||
@@ -254,6 +254,22 @@ func New(ctx context.Context, options *Options) (_ *API, err error) {
|
||||
r.Get("/", api.groupByOrganization)
|
||||
})
|
||||
})
|
||||
r.Route("/organizations/{organization}/provisionerkeys", func(r chi.Router) {
|
||||
r.Use(
|
||||
apiKeyMiddleware,
|
||||
httpmw.ExtractOrganizationParam(api.Database),
|
||||
api.RequireFeatureMW(codersdk.FeatureMultipleOrganizations),
|
||||
httpmw.RequireExperiment(api.AGPL.Experiments, codersdk.ExperimentMultiOrganization),
|
||||
)
|
||||
r.Get("/", api.provisionerKeys)
|
||||
r.Post("/", api.postProvisionerKey)
|
||||
r.Route("/{provisionerkey}", func(r chi.Router) {
|
||||
r.Use(
|
||||
httpmw.ExtractProvisionerKeyParam(options.Database),
|
||||
)
|
||||
r.Delete("/", api.deleteProvisionerKey)
|
||||
})
|
||||
})
|
||||
// TODO: provisioner daemons are not scoped to organizations in the database, so placing them
|
||||
// under an organization route doesn't make sense. In order to allow the /serve endpoint to
|
||||
// work with a pre-shared key (PSK) without an API key, these routes will simply ignore the
|
||||
@@ -566,6 +582,7 @@ func (api *API) updateEntitlements(ctx context.Context) error {
|
||||
codersdk.FeatureUserRoleManagement: true,
|
||||
codersdk.FeatureAccessControl: true,
|
||||
codersdk.FeatureControlSharedPorts: true,
|
||||
codersdk.FeatureMultipleOrganizations: true,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -751,6 +768,11 @@ func (api *API) updateEntitlements(ctx context.Context) error {
|
||||
api.AGPL.CustomRoleHandler.Store(&handler)
|
||||
}
|
||||
|
||||
if initial, changed, enabled := featureChanged(codersdk.FeatureMultipleOrganizations); shouldUpdate(initial, changed, enabled) {
|
||||
var handler coderd.CustomRoleHandler = &enterpriseCustomRoleHandler{API: api, Enabled: enabled}
|
||||
api.AGPL.CustomRoleHandler.Store(&handler)
|
||||
}
|
||||
|
||||
// External token encryption is soft-enforced
|
||||
featureExternalTokenEncryption := entitlements.Features[codersdk.FeatureExternalTokenEncryption]
|
||||
featureExternalTokenEncryption.Enabled = len(api.ExternalTokenEncryption) > 0
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package coderd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
"github.com/coder/coder/v2/coderd/httpmw"
|
||||
"github.com/coder/coder/v2/coderd/provisionerkey"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
)
|
||||
|
||||
// @Summary Create provisioner key
|
||||
// @ID create-provisioner-key
|
||||
// @Security CoderSessionToken
|
||||
// @Produce json
|
||||
// @Tags Enterprise
|
||||
// @Param organization path string true "Organization ID"
|
||||
// @Success 201 {object} codersdk.CreateProvisionerKeyResponse
|
||||
// @Router /organizations/{organization}/provisionerkeys [post]
|
||||
func (api *API) postProvisionerKey(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
organization := httpmw.OrganizationParam(r)
|
||||
|
||||
var req codersdk.CreateProvisionerKeyRequest
|
||||
if !httpapi.Read(ctx, rw, r, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: "Name is required",
|
||||
Validations: []codersdk.ValidationError{
|
||||
{
|
||||
Field: "name",
|
||||
Detail: "Name is required",
|
||||
},
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.Name) > 64 {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: "Name must be at most 64 characters",
|
||||
Validations: []codersdk.ValidationError{
|
||||
{
|
||||
Field: "name",
|
||||
Detail: "Name must be at most 64 characters",
|
||||
},
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
params, token, err := provisionerkey.New(organization.ID, req.Name)
|
||||
if err != nil {
|
||||
httpapi.InternalServerError(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = api.Database.InsertProvisionerKey(ctx, params)
|
||||
if database.IsUniqueViolation(err, database.UniqueProvisionerKeysOrganizationIDNameIndex) {
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: fmt.Sprintf("Provisioner key with name '%s' already exists in organization", req.Name),
|
||||
})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
httpapi.InternalServerError(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpapi.Write(ctx, rw, http.StatusCreated, codersdk.CreateProvisionerKeyResponse{
|
||||
Key: token,
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary List provisioner key
|
||||
// @ID list-provisioner-key
|
||||
// @Security CoderSessionToken
|
||||
// @Produce json
|
||||
// @Tags Enterprise
|
||||
// @Param organization path string true "Organization ID"
|
||||
// @Success 200 {object} []codersdk.ProvisionerKey
|
||||
// @Router /organizations/{organization}/provisionerkeys [get]
|
||||
func (api *API) provisionerKeys(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
organization := httpmw.OrganizationParam(r)
|
||||
|
||||
pks, err := api.Database.ListProvisionerKeysByOrganization(ctx, organization.ID)
|
||||
if err != nil {
|
||||
httpapi.InternalServerError(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpapi.Write(ctx, rw, http.StatusOK, convertProvisionerKeys(pks))
|
||||
}
|
||||
|
||||
// @Summary Delete provisioner key
|
||||
// @ID delete-provisioner-key
|
||||
// @Security CoderSessionToken
|
||||
// @Tags Enterprise
|
||||
// @Param organization path string true "Organization ID"
|
||||
// @Param provisionerkey path string true "Provisioner key name"
|
||||
// @Success 204
|
||||
// @Router /organizations/{organization}/provisionerkeys/{provisionerkey} [delete]
|
||||
func (api *API) deleteProvisionerKey(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
organization := httpmw.OrganizationParam(r)
|
||||
provisionerKey := httpmw.ProvisionerKeyParam(r)
|
||||
|
||||
pk, err := api.Database.GetProvisionerKeyByName(ctx, database.GetProvisionerKeyByNameParams{
|
||||
OrganizationID: organization.ID,
|
||||
Name: provisionerKey.Name,
|
||||
})
|
||||
if err != nil {
|
||||
if httpapi.Is404Error(err) {
|
||||
httpapi.ResourceNotFound(rw)
|
||||
return
|
||||
}
|
||||
|
||||
httpapi.InternalServerError(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
err = api.Database.DeleteProvisionerKey(ctx, pk.ID)
|
||||
if err != nil {
|
||||
httpapi.InternalServerError(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpapi.Write(ctx, rw, http.StatusNoContent, nil)
|
||||
}
|
||||
|
||||
func convertProvisionerKeys(dbKeys []database.ProvisionerKey) []codersdk.ProvisionerKey {
|
||||
keys := make([]codersdk.ProvisionerKey, 0, len(dbKeys))
|
||||
for _, dbKey := range dbKeys {
|
||||
keys = append(keys, codersdk.ProvisionerKey{
|
||||
ID: dbKey.ID,
|
||||
CreatedAt: dbKey.CreatedAt,
|
||||
OrganizationID: dbKey.OrganizationID,
|
||||
Name: dbKey.Name,
|
||||
// HashedSecret - never include the access token in the API response
|
||||
})
|
||||
}
|
||||
return keys
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package coderd_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/coderdtest"
|
||||
"github.com/coder/coder/v2/coderd/rbac"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/enterprise/coderd/coderdenttest"
|
||||
"github.com/coder/coder/v2/enterprise/coderd/license"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
)
|
||||
|
||||
func TestProvisionerKeys(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong*10)
|
||||
t.Cleanup(cancel)
|
||||
dv := coderdtest.DeploymentValues(t)
|
||||
dv.Experiments = []string{string(codersdk.ExperimentMultiOrganization)}
|
||||
client, owner := coderdenttest.New(t, &coderdenttest.Options{
|
||||
Options: &coderdtest.Options{
|
||||
DeploymentValues: dv,
|
||||
},
|
||||
LicenseOptions: &coderdenttest.LicenseOptions{
|
||||
Features: license.Features{
|
||||
codersdk.FeatureMultipleOrganizations: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
orgAdmin, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.ScopedRoleOrgAdmin(owner.OrganizationID))
|
||||
member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
|
||||
otherOrg := coderdtest.CreateOrganization(t, client, coderdtest.CreateOrganizationOptions{})
|
||||
outsideOrgAdmin, _ := coderdtest.CreateAnotherUser(t, client, otherOrg.ID, rbac.ScopedRoleOrgAdmin(otherOrg.ID))
|
||||
|
||||
// member cannot create a provisioner key
|
||||
_, err := member.CreateProvisionerKey(ctx, otherOrg.ID, codersdk.CreateProvisionerKeyRequest{
|
||||
Name: "key",
|
||||
})
|
||||
require.ErrorContains(t, err, "Resource not found")
|
||||
|
||||
// member cannot list provisioner keys
|
||||
_, err = member.ListProvisionerKeys(ctx, otherOrg.ID)
|
||||
require.ErrorContains(t, err, "Resource not found")
|
||||
|
||||
// member cannot delete a provisioner key
|
||||
err = member.DeleteProvisionerKey(ctx, otherOrg.ID, "key")
|
||||
require.ErrorContains(t, err, "Resource not found")
|
||||
|
||||
// outside org admin cannot create a provisioner key
|
||||
_, err = outsideOrgAdmin.CreateProvisionerKey(ctx, owner.OrganizationID, codersdk.CreateProvisionerKeyRequest{
|
||||
Name: "key",
|
||||
})
|
||||
require.ErrorContains(t, err, "Resource not found")
|
||||
|
||||
// outside org admin cannot list provisioner keys
|
||||
_, err = outsideOrgAdmin.ListProvisionerKeys(ctx, owner.OrganizationID)
|
||||
require.ErrorContains(t, err, "Resource not found")
|
||||
|
||||
// outside org admin cannot delete a provisioner key
|
||||
err = outsideOrgAdmin.DeleteProvisionerKey(ctx, owner.OrganizationID, "key")
|
||||
require.ErrorContains(t, err, "Resource not found")
|
||||
|
||||
// org admin can list provisioner keys and get an empty list
|
||||
keys, err := orgAdmin.ListProvisionerKeys(ctx, owner.OrganizationID)
|
||||
require.NoError(t, err, "org admin list provisioner keys")
|
||||
require.Len(t, keys, 0, "org admin list provisioner keys")
|
||||
|
||||
// org admin can create a provisioner key
|
||||
_, err = orgAdmin.CreateProvisionerKey(ctx, owner.OrganizationID, codersdk.CreateProvisionerKeyRequest{
|
||||
Name: "Key", // case insensitive
|
||||
})
|
||||
require.NoError(t, err, "org admin create provisioner key")
|
||||
|
||||
// org admin can conflict on name creating a provisioner key
|
||||
_, err = orgAdmin.CreateProvisionerKey(ctx, owner.OrganizationID, codersdk.CreateProvisionerKeyRequest{
|
||||
Name: "KEY", // still conflicts
|
||||
})
|
||||
require.ErrorContains(t, err, "already exists in organization")
|
||||
|
||||
// key name cannot be too long
|
||||
_, err = orgAdmin.CreateProvisionerKey(ctx, owner.OrganizationID, codersdk.CreateProvisionerKeyRequest{
|
||||
Name: "Everyone please pass your watermelons to the front of the pool, the storm is approaching.",
|
||||
})
|
||||
require.ErrorContains(t, err, "must be at most 64 characters")
|
||||
|
||||
// key name cannot be empty
|
||||
_, err = orgAdmin.CreateProvisionerKey(ctx, owner.OrganizationID, codersdk.CreateProvisionerKeyRequest{
|
||||
Name: "",
|
||||
})
|
||||
require.ErrorContains(t, err, "is required")
|
||||
|
||||
// org admin can list provisioner keys
|
||||
keys, err = orgAdmin.ListProvisionerKeys(ctx, owner.OrganizationID)
|
||||
require.NoError(t, err, "org admin list provisioner keys")
|
||||
require.Len(t, keys, 1, "org admin list provisioner keys")
|
||||
|
||||
// org admin can delete a provisioner key
|
||||
err = orgAdmin.DeleteProvisionerKey(ctx, owner.OrganizationID, "key") // using lowercase here works
|
||||
require.NoError(t, err, "org admin delete provisioner key")
|
||||
|
||||
// org admin cannot delete a provisioner key that doesn't exist
|
||||
err = orgAdmin.DeleteProvisionerKey(ctx, owner.OrganizationID, "key")
|
||||
require.ErrorContains(t, err, "Resource not found")
|
||||
}
|
||||
@@ -327,7 +327,7 @@ func convertSDKTemplateRole(role codersdk.TemplateRole) []policy.Action {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO reduce the duplication across all of these.
|
||||
// TODO move to api.RequireFeatureMW when we are OK with changing the behavior.
|
||||
func (api *API) templateRBACEnabledMW(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
api.entitlementsMu.RLock()
|
||||
@@ -343,19 +343,21 @@ func (api *API) templateRBACEnabledMW(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
func (api *API) moonsEnabledMW(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
// Entitlement must be enabled.
|
||||
api.entitlementsMu.RLock()
|
||||
proxy := api.entitlements.Features[codersdk.FeatureWorkspaceProxy].Enabled
|
||||
api.entitlementsMu.RUnlock()
|
||||
if !proxy {
|
||||
httpapi.Write(r.Context(), rw, http.StatusForbidden, codersdk.Response{
|
||||
Message: "External workspace proxies is an Enterprise feature. Contact sales!",
|
||||
})
|
||||
return
|
||||
}
|
||||
func (api *API) RequireFeatureMW(feat codersdk.FeatureName) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
// Entitlement must be enabled.
|
||||
api.entitlementsMu.RLock()
|
||||
enabled := api.entitlements.Features[feat].Enabled
|
||||
api.entitlementsMu.RUnlock()
|
||||
if !enabled {
|
||||
httpapi.Write(r.Context(), rw, http.StatusForbidden, codersdk.Response{
|
||||
Message: fmt.Sprintf("%s is an Enterprise feature. Contact sales!", feat.Humanize()),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(rw, r)
|
||||
})
|
||||
next.ServeHTTP(rw, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user